From 426df3d7e61b05b4e96c909ce747207d6c06e67a Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Wed, 30 Dec 2020 17:10:51 -0800 Subject: [PATCH] fixup: update compiled --- packages/next/compiled/schema-utils3/LICENSE | 20 + packages/next/compiled/schema-utils3/index.js | 1 + .../next/compiled/schema-utils3/package.json | 1 + .../next/compiled/thread-loader/worker.js | 2 +- .../next/compiled/webpack-sources/LICENSE | 21 + .../next/compiled/webpack-sources/index.js | 1 + .../compiled/webpack-sources/package.json | 1 + .../next/compiled/webpack-sources2/LICENSE | 21 + .../next/compiled/webpack-sources2/index.js | 1 + .../compiled/webpack-sources2/package.json | 1 + packages/next/compiled/webpack/LICENSE | 20 + packages/next/compiled/webpack/amd-define.js | 55 + packages/next/compiled/webpack/amd-options.js | 54 + packages/next/compiled/webpack/assert.js | 1276 + packages/next/compiled/webpack/browser.js | 101 + packages/next/compiled/webpack/browser1.js | 236 + packages/next/compiled/webpack/bundle4.js | 106014 ++++++++++++ packages/next/compiled/webpack/bundle5.js | 132760 +++++++++++++++ packages/next/compiled/webpack/constants.json | 209 + packages/next/compiled/webpack/duplex.js | 3033 + packages/next/compiled/webpack/empty.js | 52 + packages/next/compiled/webpack/events.js | 501 + packages/next/compiled/webpack/global.js | 72 + .../next/compiled/webpack/harmony-module.js | 76 + packages/next/compiled/webpack/index.js | 2105 + packages/next/compiled/webpack/index1.js | 155 + packages/next/compiled/webpack/index10.js | 201 + packages/next/compiled/webpack/index11.js | 6883 + packages/next/compiled/webpack/index12.js | 109 + packages/next/compiled/webpack/index2.js | 16403 ++ packages/next/compiled/webpack/index3.js | 130 + packages/next/compiled/webpack/index4.js | 3848 + packages/next/compiled/webpack/index5.js | 99 + packages/next/compiled/webpack/index6.js | 351 + packages/next/compiled/webpack/index7.js | 240 + packages/next/compiled/webpack/index8.js | 3248 + packages/next/compiled/webpack/index9.js | 63 + packages/next/compiled/webpack/main.js | 308 + packages/next/compiled/webpack/minify.js | 345 + packages/next/compiled/webpack/module.js | 74 + packages/next/compiled/webpack/package.json | 1 + packages/next/compiled/webpack/passthrough.js | 3033 + packages/next/compiled/webpack/punycode.js | 598 + packages/next/compiled/webpack/readable.js | 3025 + .../next/compiled/webpack/string_decoder.js | 427 + packages/next/compiled/webpack/system.js | 59 + packages/next/compiled/webpack/transform.js | 3033 + packages/next/compiled/webpack/url.js | 822 + packages/next/compiled/webpack/util.js | 817 + packages/next/compiled/webpack/webpack.js | 27 + packages/next/compiled/webpack/worker.js | 281 + packages/next/compiled/webpack/writable.js | 2739 + 52 files changed, 293952 insertions(+), 1 deletion(-) create mode 100644 packages/next/compiled/schema-utils3/LICENSE create mode 100644 packages/next/compiled/schema-utils3/index.js create mode 100644 packages/next/compiled/schema-utils3/package.json create mode 100644 packages/next/compiled/webpack-sources/LICENSE create mode 100644 packages/next/compiled/webpack-sources/index.js create mode 100644 packages/next/compiled/webpack-sources/package.json create mode 100644 packages/next/compiled/webpack-sources2/LICENSE create mode 100644 packages/next/compiled/webpack-sources2/index.js create mode 100644 packages/next/compiled/webpack-sources2/package.json create mode 100644 packages/next/compiled/webpack/LICENSE create mode 100644 packages/next/compiled/webpack/amd-define.js create mode 100644 packages/next/compiled/webpack/amd-options.js create mode 100644 packages/next/compiled/webpack/assert.js create mode 100644 packages/next/compiled/webpack/browser.js create mode 100644 packages/next/compiled/webpack/browser1.js create mode 100644 packages/next/compiled/webpack/bundle4.js create mode 100644 packages/next/compiled/webpack/bundle5.js create mode 100644 packages/next/compiled/webpack/constants.json create mode 100644 packages/next/compiled/webpack/duplex.js create mode 100644 packages/next/compiled/webpack/empty.js create mode 100644 packages/next/compiled/webpack/events.js create mode 100644 packages/next/compiled/webpack/global.js create mode 100644 packages/next/compiled/webpack/harmony-module.js create mode 100644 packages/next/compiled/webpack/index.js create mode 100644 packages/next/compiled/webpack/index1.js create mode 100644 packages/next/compiled/webpack/index10.js create mode 100644 packages/next/compiled/webpack/index11.js create mode 100644 packages/next/compiled/webpack/index12.js create mode 100644 packages/next/compiled/webpack/index2.js create mode 100644 packages/next/compiled/webpack/index3.js create mode 100644 packages/next/compiled/webpack/index4.js create mode 100644 packages/next/compiled/webpack/index5.js create mode 100644 packages/next/compiled/webpack/index6.js create mode 100644 packages/next/compiled/webpack/index7.js create mode 100644 packages/next/compiled/webpack/index8.js create mode 100644 packages/next/compiled/webpack/index9.js create mode 100644 packages/next/compiled/webpack/main.js create mode 100644 packages/next/compiled/webpack/minify.js create mode 100644 packages/next/compiled/webpack/module.js create mode 100644 packages/next/compiled/webpack/package.json create mode 100644 packages/next/compiled/webpack/passthrough.js create mode 100644 packages/next/compiled/webpack/punycode.js create mode 100644 packages/next/compiled/webpack/readable.js create mode 100644 packages/next/compiled/webpack/string_decoder.js create mode 100644 packages/next/compiled/webpack/system.js create mode 100644 packages/next/compiled/webpack/transform.js create mode 100644 packages/next/compiled/webpack/url.js create mode 100644 packages/next/compiled/webpack/util.js create mode 100644 packages/next/compiled/webpack/webpack.js create mode 100644 packages/next/compiled/webpack/worker.js create mode 100644 packages/next/compiled/webpack/writable.js diff --git a/packages/next/compiled/schema-utils3/LICENSE b/packages/next/compiled/schema-utils3/LICENSE new file mode 100644 index 000000000000000..8c11fc7289b7546 --- /dev/null +++ b/packages/next/compiled/schema-utils3/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/next/compiled/schema-utils3/index.js b/packages/next/compiled/schema-utils3/index.js new file mode 100644 index 000000000000000..410cb4cf83944a0 --- /dev/null +++ b/packages/next/compiled/schema-utils3/index.js @@ -0,0 +1 @@ +module.exports=(()=>{var e={601:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},8938:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},2133:(e,n,f)=>{"use strict";var s=f(2670);e.exports=defineKeywords;function defineKeywords(e,n){if(Array.isArray(n)){for(var f=0;f{"use strict";var s=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;var l=/t|\s/i;var v={date:compareDate,time:compareTime,"date-time":compareDateTime};var r={type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false};e.exports=function(e){var n="format"+e;return function defFunc(s){defFunc.definition={type:"string",inline:f(7194),statements:true,errors:"full",dependencies:["format"],metaSchema:{anyOf:[{type:"string"},r]}};s.addKeyword(n,defFunc.definition);s.addKeyword("formatExclusive"+e,{dependencies:["format"+e],metaSchema:{anyOf:[{type:"boolean"},r]}});extendFormats(s);return s}};function extendFormats(e){var n=e._formats;for(var f in v){var s=n[f];if(typeof s!="object"||s instanceof RegExp||!s.validate)s=n[f]={validate:s};if(!s.compare)s.compare=v[f]}}function compareDate(e,n){if(!(e&&n))return;if(e>n)return 1;if(en)return 1;if(e{"use strict";e.exports={metaSchemaRef:metaSchemaRef};var n="http://json-schema.org/draft-07/schema";function metaSchemaRef(e){var f=e._opts.defaultMeta;if(typeof f=="string")return{$ref:f};if(e.getSchema(n))return{$ref:n};console.warn("meta schema not defined");return{}}},5541:e=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",macro:function(e,n){if(!e)return true;var f=Object.keys(n.properties);if(f.length==0)return true;return{required:f}},metaSchema:{type:"boolean"},dependencies:["properties"]};e.addKeyword("allRequired",defFunc.definition);return e}},7039:e=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",macro:function(e){if(e.length==0)return true;if(e.length==1)return{required:e};var n=e.map(function(e){return{required:[e]}});return{anyOf:n}},metaSchema:{type:"array",items:{type:"string"}}};e.addKeyword("anyRequired",defFunc.definition);return e}},1673:(e,n,f)=>{"use strict";var s=f(3733);e.exports=function defFunc(e){defFunc.definition={type:"object",macro:function(e){var n=[];for(var f in e)n.push(getSchema(f,e[f]));return{allOf:n}},metaSchema:{type:"object",propertyNames:{type:"string",format:"json-pointer"},additionalProperties:s.metaSchemaRef(e)}};e.addKeyword("deepProperties",defFunc.definition);return e};function getSchema(e,n){var f=e.split("/");var s={};var l=s;for(var v=1;v{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",inline:function(e,n,f){var s="";for(var l=0;l{"use strict";e.exports=function generate__formatLimit(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j="valid"+l;s+="var "+j+" = undefined;";if(e.opts.format===false){s+=" "+j+" = true; ";return s}var w=e.schema.format,F=e.opts.$data&&w.$data,E="";if(F){var A=e.util.getData(w.$data,v,e.dataPathArr),N="format"+l,a="compare"+l;s+=" var "+N+" = formats["+A+"] , "+a+" = "+N+" && "+N+".compare;"}else{var N=e.formats[w];if(!(N&&N.compare)){s+=" "+j+" = true; ";return s}var a="formats"+e.util.getProperty(w)+".compare"}var z=n=="formatMaximum",x="formatExclusive"+(z?"Maximum":"Minimum"),O=e.schema[x],q=e.opts.$data&&O&&O.$data,Q=z?"<":">",U="result"+l;var I=e.opts.$data&&r&&r.$data,T;if(I){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";T="schema"+l}else{T=r}if(q){var J=e.util.getData(O.$data,v,e.dataPathArr),L="exclusive"+l,M="op"+l,C="' + "+M+" + '";s+=" var schemaExcl"+l+" = "+J+"; ";J="schemaExcl"+l;s+=" if (typeof "+J+" != 'boolean' && "+J+" !== undefined) { "+j+" = false; ";var d=x;var H=H||[];H.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_formatExclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: '"+x+" should be boolean' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var G=s;s=H.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+G+"]); "}else{s+=" validate.errors = ["+G+"]; return false; "}}else{s+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(p){E+="}";s+=" else { "}if(I){s+=" if ("+T+" === undefined) "+j+" = true; else if (typeof "+T+" != 'string') "+j+" = false; else { ";E+="}"}if(F){s+=" if (!"+a+") "+j+" = true; else { ";E+="}"}s+=" var "+U+" = "+a+"("+R+", ";if(I){s+=""+T}else{s+=""+e.util.toQuotedString(r)}s+=" ); if ("+U+" === undefined) "+j+" = false; var "+L+" = "+J+" === true; if ("+j+" === undefined) { "+j+" = "+L+" ? "+U+" "+Q+" 0 : "+U+" "+Q+"= 0; } if (!"+j+") var op"+l+" = "+L+" ? '"+Q+"' : '"+Q+"=';"}else{var L=O===true,C=Q;if(!L)C+="=";var M="'"+C+"'";if(I){s+=" if ("+T+" === undefined) "+j+" = true; else if (typeof "+T+" != 'string') "+j+" = false; else { ";E+="}"}if(F){s+=" if (!"+a+") "+j+" = true; else { ";E+="}"}s+=" var "+U+" = "+a+"("+R+", ";if(I){s+=""+T}else{s+=""+e.util.toQuotedString(r)}s+=" ); if ("+U+" === undefined) "+j+" = false; if ("+j+" === undefined) "+j+" = "+U+" "+Q;if(!L){s+="="}s+=" 0;"}s+=""+E+"if (!"+j+") { ";var d=n;var H=H||[];H.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_formatLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { comparison: "+M+", limit: ";if(I){s+=""+T}else{s+=""+e.util.toQuotedString(r)}s+=" , exclusive: "+L+" } ";if(e.opts.messages!==false){s+=" , message: 'should be "+C+' "';if(I){s+="' + "+T+" + '"}else{s+=""+e.util.escapeQuotes(r)}s+="\"' "}if(e.opts.verbose){s+=" , schema: ";if(I){s+="validate.schema"+g}else{s+=""+e.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var G=s;s=H.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+G+"]); "}else{s+=" validate.errors = ["+G+"]; return false; "}}else{s+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="}";return s}},3724:e=>{"use strict";e.exports=function generate_patternRequired(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="key"+l,w="idx"+l,F="patternMatched"+l,E="dataProperties"+l,A="",N=e.opts.ownProperties;s+="var "+R+" = true;";if(N){s+=" var "+E+" = undefined;"}var a=r;if(a){var z,x=-1,O=a.length-1;while(x{"use strict";e.exports=function generate_switch(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);var F="";w.level++;var E="valid"+w.level;var A="ifPassed"+e.level,N=w.baseId,a;s+="var "+A+";";var z=r;if(z){var x,O=-1,q=z.length-1;while(O0:e.util.schemaHasRules(x.if,e.RULES.all))){s+=" var "+j+" = errors; ";var Q=e.compositeRule;e.compositeRule=w.compositeRule=true;w.createErrors=false;w.schema=x.if;w.schemaPath=g+"["+O+"].if";w.errSchemaPath=b+"/"+O+"/if";s+=" "+e.validate(w)+" ";w.baseId=N;w.createErrors=true;e.compositeRule=w.compositeRule=Q;s+=" "+A+" = "+E+"; if ("+A+") { ";if(typeof x.then=="boolean"){if(x.then===false){var U=U||[];U.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"switch"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { caseIndex: "+O+" } ";if(e.opts.messages!==false){s+=" , message: 'should pass \"switch\" keyword validation' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var I=s;s=U.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+I+"]); "}else{s+=" validate.errors = ["+I+"]; return false; "}}else{s+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}s+=" var "+E+" = "+x.then+"; "}else{w.schema=x.then;w.schemaPath=g+"["+O+"].then";w.errSchemaPath=b+"/"+O+"/then";s+=" "+e.validate(w)+" ";w.baseId=N}s+=" } else { errors = "+j+"; if (vErrors !== null) { if ("+j+") vErrors.length = "+j+"; else vErrors = null; } } "}else{s+=" "+A+" = true; ";if(typeof x.then=="boolean"){if(x.then===false){var U=U||[];U.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"switch"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { caseIndex: "+O+" } ";if(e.opts.messages!==false){s+=" , message: 'should pass \"switch\" keyword validation' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var I=s;s=U.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+I+"]); "}else{s+=" validate.errors = ["+I+"]; return false; "}}else{s+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}s+=" var "+E+" = "+x.then+"; "}else{w.schema=x.then;w.schemaPath=g+"["+O+"].then";w.errSchemaPath=b+"/"+O+"/then";s+=" "+e.validate(w)+" ";w.baseId=N}}a=x.continue}}s+=""+F+"var "+R+" = "+E+";";return s}},2107:e=>{"use strict";var n={};var f={timestamp:function(){return Date.now()},datetime:function(){return(new Date).toISOString()},date:function(){return(new Date).toISOString().slice(0,10)},time:function(){return(new Date).toISOString().slice(11)},random:function(){return Math.random()},randomint:function(e){var n=e&&e.max||2;return function(){return Math.floor(Math.random()*n)}},seq:function(e){var f=e&&e.name||"";n[f]=n[f]||0;return function(){return n[f]++}}};e.exports=function defFunc(e){defFunc.definition={compile:function(e,n,f){var s={};for(var l in e){var v=e[l];var r=getDefault(typeof v=="string"?v:v.func);s[l]=r.length?r(v.args):r}return f.opts.useDefaults&&!f.compositeRule?assignDefaults:noop;function assignDefaults(n){for(var l in e){if(n[l]===undefined||f.opts.useDefaults=="empty"&&(n[l]===null||n[l]===""))n[l]=s[l]()}return true}function noop(){return true}},DEFAULTS:f,metaSchema:{type:"object",additionalProperties:{type:["string","object"],additionalProperties:false,required:["func","args"],properties:{func:{type:"string"},args:{type:"object"}}}}};e.addKeyword("dynamicDefaults",defFunc.definition);return e;function getDefault(e){var n=f[e];if(n)return n;throw new Error('invalid "dynamicDefaults" keyword property value: '+e)}}},6153:(e,n,f)=>{"use strict";e.exports=f(2784)("Maximum")},4409:(e,n,f)=>{"use strict";e.exports=f(2784)("Minimum")},2670:(e,n,f)=>{"use strict";e.exports={instanceof:f(2479),range:f(9159),regexp:f(3284),typeof:f(2608),dynamicDefaults:f(2107),allRequired:f(5541),anyRequired:f(7039),oneRequired:f(2135),prohibited:f(3115),uniqueItemProperties:f(3786),deepProperties:f(1673),deepRequired:f(2541),formatMinimum:f(4409),formatMaximum:f(6153),patternRequired:f(5844),switch:f(682),select:f(2308),transform:f(159)}},2479:e=>{"use strict";var n={Object:Object,Array:Array,Function:Function,Number:Number,String:String,Date:Date,RegExp:RegExp};e.exports=function defFunc(e){if(typeof Buffer!="undefined")n.Buffer=Buffer;if(typeof Promise!="undefined")n.Promise=Promise;defFunc.definition={compile:function(e){if(typeof e=="string"){var n=getConstructor(e);return function(e){return e instanceof n}}var f=e.map(getConstructor);return function(e){for(var n=0;n{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",macro:function(e){if(e.length==0)return true;if(e.length==1)return{required:e};var n=e.map(function(e){return{required:[e]}});return{oneOf:n}},metaSchema:{type:"array",items:{type:"string"}}};e.addKeyword("oneRequired",defFunc.definition);return e}},5844:(e,n,f)=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",inline:f(3724),statements:true,errors:"full",metaSchema:{type:"array",items:{type:"string",format:"regex"},uniqueItems:true}};e.addKeyword("patternRequired",defFunc.definition);return e}},3115:e=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"object",macro:function(e){if(e.length==0)return true;if(e.length==1)return{not:{required:e}};var n=e.map(function(e){return{required:[e]}});return{not:{anyOf:n}}},metaSchema:{type:"array",items:{type:"string"}}};e.addKeyword("prohibited",defFunc.definition);return e}},9159:e=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"number",macro:function(e,n){var f=e[0],s=e[1],l=n.exclusiveRange;validateRangeSchema(f,s,l);return l===true?{exclusiveMinimum:f,exclusiveMaximum:s}:{minimum:f,maximum:s}},metaSchema:{type:"array",minItems:2,maxItems:2,items:{type:"number"}}};e.addKeyword("range",defFunc.definition);e.addKeyword("exclusiveRange");return e;function validateRangeSchema(e,n,f){if(f!==undefined&&typeof f!="boolean")throw new Error("Invalid schema for exclusiveRange keyword, should be boolean");if(e>n||f&&e==n)throw new Error("There are no numbers in range")}}},3284:e=>{"use strict";e.exports=function defFunc(e){defFunc.definition={type:"string",inline:function(e,n,f){return getRegExp()+".test(data"+(e.dataLevel||"")+")";function getRegExp(){try{if(typeof f=="object")return new RegExp(f.pattern,f.flags);var e=f.match(/^\/(.*)\/([gimuy]*)$/);if(e)return new RegExp(e[1],e[2]);throw new Error("cannot parse string into RegExp")}catch(e){console.error("regular expression",f,"is invalid");throw e}}},metaSchema:{type:["string","object"],properties:{pattern:{type:"string"},flags:{type:"string"}},required:["pattern"],additionalProperties:false}};e.addKeyword("regexp",defFunc.definition);return e}},2308:(e,n,f)=>{"use strict";var s=f(3733);e.exports=function defFunc(e){if(!e._opts.$data){console.warn("keyword select requires $data option");return e}var n=s.metaSchemaRef(e);var f=[];defFunc.definition={validate:function v(e,n,f){if(f.selectCases===undefined)throw new Error('keyword "selectCases" is absent');var s=getCompiledSchemas(f,false);var l=s.cases[e];if(l===undefined)l=s.default;if(typeof l=="boolean")return l;var r=l(n);if(!r)v.errors=l.errors;return r},$data:true,metaSchema:{type:["string","number","boolean","null"]}};e.addKeyword("select",defFunc.definition);e.addKeyword("selectCases",{compile:function(e,n){var f=getCompiledSchemas(n);for(var s in e)f.cases[s]=compileOrBoolean(e[s]);return function(){return true}},valid:true,metaSchema:{type:"object",additionalProperties:n}});e.addKeyword("selectDefault",{compile:function(e,n){var f=getCompiledSchemas(n);f.default=compileOrBoolean(e);return function(){return true}},valid:true,metaSchema:n});return e;function getCompiledSchemas(e,n){var s;f.some(function(n){if(n.parentSchema===e){s=n;return true}});if(!s&&n!==false){s={parentSchema:e,cases:{},default:true};f.push(s)}return s}function compileOrBoolean(n){return typeof n=="boolean"?n:e.compile(n)}}},682:(e,n,f)=>{"use strict";var s=f(3733);e.exports=function defFunc(e){if(e.RULES.keywords.switch&&e.RULES.keywords.if)return;var n=s.metaSchemaRef(e);defFunc.definition={inline:f(608),statements:true,errors:"full",metaSchema:{type:"array",items:{required:["then"],properties:{if:n,then:{anyOf:[{type:"boolean"},n]},continue:{type:"boolean"}},additionalProperties:false,dependencies:{continue:["if"]}}}};e.addKeyword("switch",defFunc.definition);return e}},159:e=>{"use strict";e.exports=function defFunc(e){var n={trimLeft:function(e){return e.replace(/^[\s]+/,"")},trimRight:function(e){return e.replace(/[\s]+$/,"")},trim:function(e){return e.trim()},toLowerCase:function(e){return e.toLowerCase()},toUpperCase:function(e){return e.toUpperCase()},toEnumCase:function(e,n){return n.hash[makeHashTableKey(e)]||e}};defFunc.definition={type:"string",errors:false,modifying:true,valid:true,compile:function(e,f){var s;if(e.indexOf("toEnumCase")!==-1){s={hash:{}};if(!f.enum)throw new Error('Missing enum. To use `transform:["toEnumCase"]`, `enum:[...]` is required.');for(var l=f.enum.length;l--;l){var v=f.enum[l];if(typeof v!=="string")continue;var r=makeHashTableKey(v);if(s.hash[r])throw new Error('Invalid enum uniqueness. To use `transform:["toEnumCase"]`, all values must be unique when case insensitive.');s.hash[r]=v}}return function(f,l,v,r){if(!v)return;for(var g=0,b=e.length;g{"use strict";var n=["undefined","string","number","object","function","boolean","symbol"];e.exports=function defFunc(e){defFunc.definition={inline:function(e,n,f){var s="data"+(e.dataLevel||"");if(typeof f=="string")return"typeof "+s+' == "'+f+'"';f="validate.schema"+e.schemaPath+"."+n;return f+".indexOf(typeof "+s+") >= 0"},metaSchema:{anyOf:[{type:"string",enum:n},{type:"array",items:{type:"string",enum:n}}]}};e.addKeyword("typeof",defFunc.definition);return e}},3786:e=>{"use strict";var n=["number","integer","string","boolean","null"];e.exports=function defFunc(e){defFunc.definition={type:"array",compile:function(e,n,f){var s=f.util.equal;var l=getScalarKeys(e,n);return function(n){if(n.length>1){for(var f=0;f=0})}},1414:(e,n,f)=>{"use strict";var s=f(1645),l=f(2630),v=f(7246),r=f(7837),g=f(3600),b=f(9290),p=f(1665),d=f(6989),R=f(6057);e.exports=Ajv;Ajv.prototype.validate=validate;Ajv.prototype.compile=compile;Ajv.prototype.addSchema=addSchema;Ajv.prototype.addMetaSchema=addMetaSchema;Ajv.prototype.validateSchema=validateSchema;Ajv.prototype.getSchema=getSchema;Ajv.prototype.removeSchema=removeSchema;Ajv.prototype.addFormat=addFormat;Ajv.prototype.errorsText=errorsText;Ajv.prototype._addSchema=_addSchema;Ajv.prototype._compile=_compile;Ajv.prototype.compileAsync=f(75);var j=f(8093);Ajv.prototype.addKeyword=j.add;Ajv.prototype.getKeyword=j.get;Ajv.prototype.removeKeyword=j.remove;Ajv.prototype.validateKeyword=j.validate;var w=f(2718);Ajv.ValidationError=w.Validation;Ajv.MissingRefError=w.MissingRef;Ajv.$dataMetaSchema=d;var F="http://json-schema.org/draft-07/schema";var E=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var A=["/properties"];function Ajv(e){if(!(this instanceof Ajv))return new Ajv(e);e=this._opts=R.copy(e)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=b(e.format);this._cache=e.cache||new v;this._loadingSchemas={};this._compilations=[];this.RULES=p();this._getId=chooseGetId(e);e.loopRequired=e.loopRequired||Infinity;if(e.errorDataPath=="property")e._errorDataPathProperty=true;if(e.serialize===undefined)e.serialize=g;this._metaOpts=getMetaSchemaOptions(this);if(e.formats)addInitialFormats(this);if(e.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof e.meta=="object")this.addMetaSchema(e.meta);if(e.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(e,n){var f;if(typeof e=="string"){f=this.getSchema(e);if(!f)throw new Error('no schema with key or ref "'+e+'"')}else{var s=this._addSchema(e);f=s.validate||this._compile(s)}var l=f(n);if(f.$async!==true)this.errors=f.errors;return l}function compile(e,n){var f=this._addSchema(e,undefined,n);return f.validate||this._compile(f)}function addSchema(e,n,f,s){if(Array.isArray(e)){for(var v=0;v{"use strict";var n=e.exports=function Cache(){this._cache={}};n.prototype.put=function Cache_put(e,n){this._cache[e]=n};n.prototype.get=function Cache_get(e){return this._cache[e]};n.prototype.del=function Cache_del(e){delete this._cache[e]};n.prototype.clear=function Cache_clear(){this._cache={}}},75:(e,n,f)=>{"use strict";var s=f(2718).MissingRef;e.exports=compileAsync;function compileAsync(e,n,f){var l=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof n=="function"){f=n;n=undefined}var v=loadMetaSchemaOf(e).then(function(){var f=l._addSchema(e,undefined,n);return f.validate||_compileAsync(f)});if(f){v.then(function(e){f(null,e)},f)}return v;function loadMetaSchemaOf(e){var n=e.$schema;return n&&!l.getSchema(n)?compileAsync.call(l,{$ref:n},true):Promise.resolve()}function _compileAsync(e){try{return l._compile(e)}catch(e){if(e instanceof s)return loadMissingSchema(e);throw e}function loadMissingSchema(f){var s=f.missingSchema;if(added(s))throw new Error("Schema "+s+" is loaded but "+f.missingRef+" cannot be resolved");var v=l._loadingSchemas[s];if(!v){v=l._loadingSchemas[s]=l._opts.loadSchema(s);v.then(removePromise,removePromise)}return v.then(function(e){if(!added(s)){return loadMetaSchemaOf(e).then(function(){if(!added(s))l.addSchema(e,s,undefined,n)})}}).then(function(){return _compileAsync(e)});function removePromise(){delete l._loadingSchemas[s]}function added(e){return l._refs[e]||l._schemas[e]}}}}},2718:(e,n,f)=>{"use strict";var s=f(2630);e.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(e){this.message="validation failed";this.errors=e;this.ajv=this.validation=true}MissingRefError.message=function(e,n){return"can't resolve reference "+n+" from id "+e};function MissingRefError(e,n,f){this.message=f||MissingRefError.message(e,n);this.missingRef=s.url(e,n);this.missingSchema=s.normalizeId(s.fullPath(this.missingRef))}function errorSubclass(e){e.prototype=Object.create(Error.prototype);e.prototype.constructor=e;return e}},9290:(e,n,f)=>{"use strict";var s=f(6057);var l=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var v=[0,31,28,31,30,31,30,31,31,30,31,30,31];var r=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;var g=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;var b=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;var p=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;var d=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;var R=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;var j=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var w=/^(?:\/(?:[^~/]|~0|~1)*)*$/;var F=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var E=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;e.exports=formats;function formats(e){e=e=="full"?"full":"fast";return s.copy(formats[e])}formats.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":d,url:R,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:g,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:j,"json-pointer":w,"json-pointer-uri-fragment":F,"relative-json-pointer":E};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":p,"uri-template":d,url:R,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:g,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:j,"json-pointer":w,"json-pointer-uri-fragment":F,"relative-json-pointer":E};function isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}function date(e){var n=e.match(l);if(!n)return false;var f=+n[1];var s=+n[2];var r=+n[3];return s>=1&&s<=12&&r>=1&&r<=(s==2&&isLeapYear(f)?29:v[s])}function time(e,n){var f=e.match(r);if(!f)return false;var s=f[1];var l=f[2];var v=f[3];var g=f[5];return(s<=23&&l<=59&&v<=59||s==23&&l==59&&v==60)&&(!n||g)}var A=/t|\s/i;function date_time(e){var n=e.split(A);return n.length==2&&date(n[0])&&time(n[1],true)}var N=/\/|:/;function uri(e){return N.test(e)&&b.test(e)}var a=/[^\\]\\Z/;function regex(e){if(a.test(e))return false;try{new RegExp(e);return true}catch(e){return false}}},1645:(e,n,f)=>{"use strict";var s=f(2630),l=f(6057),v=f(2718),r=f(3600);var g=f(6131);var b=l.ucs2length;var p=f(3933);var d=v.Validation;e.exports=compile;function compile(e,n,f,R){var j=this,w=this._opts,F=[undefined],E={},A=[],N={},a=[],z={},x=[];n=n||{schema:e,refVal:F,refs:E};var O=checkCompiling.call(this,e,n,R);var q=this._compilations[O.index];if(O.compiling)return q.callValidate=callValidate;var Q=this._formats;var U=this.RULES;try{var I=localCompile(e,n,f,R);q.validate=I;var T=q.callValidate;if(T){T.schema=I.schema;T.errors=null;T.refs=I.refs;T.refVal=I.refVal;T.root=I.root;T.$async=I.$async;if(w.sourceCode)T.source=I.source}return I}finally{endCompiling.call(this,e,n,R)}function callValidate(){var e=q.validate;var n=e.apply(this,arguments);callValidate.errors=e.errors;return n}function localCompile(e,f,r,R){var N=!f||f&&f.schema==e;if(f.schema!=n.schema)return compile.call(j,e,f,r,R);var z=e.$async===true;var O=g({isTop:true,schema:e,isRoot:N,baseId:R,root:f,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:v.MissingRef,RULES:U,validate:g,util:l,resolve:s,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:w,formats:Q,logger:j.logger,self:j});O=vars(F,refValCode)+vars(A,patternCode)+vars(a,defaultCode)+vars(x,customRuleCode)+O;if(w.processCode)O=w.processCode(O,e);var q;try{var I=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",O);q=I(j,U,Q,n,F,a,x,p,b,d);F[0]=q}catch(e){j.logger.error("Error compiling schema, function code:",O);throw e}q.schema=e;q.errors=null;q.refs=E;q.refVal=F;q.root=N?q:f;if(z)q.$async=true;if(w.sourceCode===true){q.source={code:O,patterns:A,defaults:a}}return q}function resolveRef(e,l,v){l=s.url(e,l);var r=E[l];var g,b;if(r!==undefined){g=F[r];b="refVal["+r+"]";return resolvedRef(g,b)}if(!v&&n.refs){var p=n.refs[l];if(p!==undefined){g=n.refVal[p];b=addLocalRef(l,g);return resolvedRef(g,b)}}b=addLocalRef(l);var d=s.call(j,localCompile,n,l);if(d===undefined){var R=f&&f[l];if(R){d=s.inlineRef(R,w.inlineRefs)?R:compile.call(j,R,n,f,e)}}if(d===undefined){removeLocalRef(l)}else{replaceLocalRef(l,d);return resolvedRef(d,b)}}function addLocalRef(e,n){var f=F.length;F[f]=n;E[e]=f;return"refVal"+f}function removeLocalRef(e){delete E[e]}function replaceLocalRef(e,n){var f=E[e];F[f]=n}function resolvedRef(e,n){return typeof e=="object"||typeof e=="boolean"?{code:n,schema:e,inline:true}:{code:n,$async:e&&!!e.$async}}function usePattern(e){var n=N[e];if(n===undefined){n=N[e]=A.length;A[n]=e}return"pattern"+n}function useDefault(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return l.toQuotedString(e);case"object":if(e===null)return"null";var n=r(e);var f=z[n];if(f===undefined){f=z[n]=a.length;a[f]=e}return"default"+f}}function useCustomRule(e,n,f,s){if(j._opts.validateSchema!==false){var l=e.definition.dependencies;if(l&&!l.every(function(e){return Object.prototype.hasOwnProperty.call(f,e)}))throw new Error("parent schema must have all required keywords: "+l.join(","));var v=e.definition.validateSchema;if(v){var r=v(n);if(!r){var g="keyword schema is invalid: "+j.errorsText(v.errors);if(j._opts.validateSchema=="log")j.logger.error(g);else throw new Error(g)}}}var b=e.definition.compile,p=e.definition.inline,d=e.definition.macro;var R;if(b){R=b.call(j,n,f,s)}else if(d){R=d.call(j,n,f,s);if(w.validateSchema!==false)j.validateSchema(R,true)}else if(p){R=p.call(j,s,e.keyword,n,f)}else{R=e.definition.validate;if(!R)return}if(R===undefined)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var F=x.length;x[F]=R;return{code:"customRule"+F,validate:R}}}function checkCompiling(e,n,f){var s=compIndex.call(this,e,n,f);if(s>=0)return{index:s,compiling:true};s=this._compilations.length;this._compilations[s]={schema:e,root:n,baseId:f};return{index:s,compiling:false}}function endCompiling(e,n,f){var s=compIndex.call(this,e,n,f);if(s>=0)this._compilations.splice(s,1)}function compIndex(e,n,f){for(var s=0;s{"use strict";var s=f(4007),l=f(3933),v=f(6057),r=f(7837),g=f(2437);e.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(e,n,f){var s=this._refs[f];if(typeof s=="string"){if(this._refs[s])s=this._refs[s];else return resolve.call(this,e,n,s)}s=s||this._schemas[f];if(s instanceof r){return inlineRef(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s)}var l=resolveSchema.call(this,n,f);var v,g,b;if(l){v=l.schema;n=l.root;b=l.baseId}if(v instanceof r){g=v.validate||e.call(this,v.schema,n,undefined,b)}else if(v!==undefined){g=inlineRef(v,this._opts.inlineRefs)?v:e.call(this,v,n,undefined,b)}return g}function resolveSchema(e,n){var f=s.parse(n),l=_getFullPath(f),v=getFullPath(this._getId(e.schema));if(Object.keys(e.schema).length===0||l!==v){var g=normalizeId(l);var b=this._refs[g];if(typeof b=="string"){return resolveRecursive.call(this,e,b,f)}else if(b instanceof r){if(!b.validate)this._compile(b);e=b}else{b=this._schemas[g];if(b instanceof r){if(!b.validate)this._compile(b);if(g==normalizeId(n))return{schema:b,root:e,baseId:v};e=b}else{return}}if(!e.schema)return;v=getFullPath(this._getId(e.schema))}return getJsonPointer.call(this,f,v,e.schema,e)}function resolveRecursive(e,n,f){var s=resolveSchema.call(this,e,n);if(s){var l=s.schema;var v=s.baseId;e=s.root;var r=this._getId(l);if(r)v=resolveUrl(v,r);return getJsonPointer.call(this,f,v,l,e)}}var b=v.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(e,n,f,s){e.fragment=e.fragment||"";if(e.fragment.slice(0,1)!="/")return;var l=e.fragment.split("/");for(var r=1;r{"use strict";var s=f(4124),l=f(6057).toHash;e.exports=function rules(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}];var n=["type","$comment"];var f=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"];var v=["number","integer","string","array","object","boolean","null"];e.all=l(n);e.types=l(v);e.forEach(function(f){f.rules=f.rules.map(function(f){var l;if(typeof f=="object"){var v=Object.keys(f)[0];l=f[v];f=v;l.forEach(function(f){n.push(f);e.all[f]=true})}n.push(f);var r=e.all[f]={keyword:f,code:s[f],implements:l};return r});e.all.$comment={keyword:"$comment",code:s.$comment};if(f.type)e.types[f.type]=f});e.keywords=l(n.concat(f));e.custom={};return e}},7837:(e,n,f)=>{"use strict";var s=f(6057);e.exports=SchemaObject;function SchemaObject(e){s.copy(e,this)}},9652:e=>{"use strict";e.exports=function ucs2length(e){var n=0,f=e.length,s=0,l;while(s=55296&&l<=56319&&s{"use strict";e.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:f(3933),ucs2length:f(9652),varOccurences:varOccurences,varReplace:varReplace,schemaHasRules:schemaHasRules,schemaHasRulesExcept:schemaHasRulesExcept,schemaUnknownRules:schemaUnknownRules,toQuotedString:toQuotedString,getPathExpr:getPathExpr,getPath:getPath,getData:getData,unescapeFragment:unescapeFragment,unescapeJsonPointer:unescapeJsonPointer,escapeFragment:escapeFragment,escapeJsonPointer:escapeJsonPointer};function copy(e,n){n=n||{};for(var f in e)n[f]=e[f];return n}function checkDataType(e,n,f,s){var l=s?" !== ":" === ",v=s?" || ":" && ",r=s?"!":"",g=s?"":"!";switch(e){case"null":return n+l+"null";case"array":return r+"Array.isArray("+n+")";case"object":return"("+r+n+v+"typeof "+n+l+'"object"'+v+g+"Array.isArray("+n+"))";case"integer":return"(typeof "+n+l+'"number"'+v+g+"("+n+" % 1)"+v+n+l+n+(f?v+r+"isFinite("+n+")":"")+")";case"number":return"(typeof "+n+l+'"'+e+'"'+(f?v+r+"isFinite("+n+")":"")+")";default:return"typeof "+n+l+'"'+e+'"'}}function checkDataTypes(e,n,f){switch(e.length){case 1:return checkDataType(e[0],n,f,true);default:var s="";var l=toHash(e);if(l.array&&l.object){s=l.null?"(":"(!"+n+" || ";s+="typeof "+n+' !== "object")';delete l.null;delete l.array;delete l.object}if(l.number)delete l.integer;for(var v in l)s+=(s?" && ":"")+checkDataType(v,n,f,true);return s}}var s=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(e,n){if(Array.isArray(n)){var f=[];for(var l=0;l=n)throw new Error("Cannot access property/index "+s+" levels up, current level is "+n);return f[n-s]}if(s>n)throw new Error("Cannot access data "+s+" levels up, current level is "+n);v="data"+(n-s||"");if(!l)return v}var p=v;var d=l.split("/");for(var R=0;R{"use strict";var n=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];e.exports=function(e,f){for(var s=0;s{"use strict";var s=f(8938);e.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:s.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:s.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},3711:e=>{"use strict";e.exports=function generate__limit(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}var F=n=="maximum",E=F?"exclusiveMaximum":"exclusiveMinimum",A=e.schema[E],N=e.opts.$data&&A&&A.$data,a=F?"<":">",z=F?">":"<",d=undefined;if(!(j||typeof r=="number"||r===undefined)){throw new Error(n+" must be number")}if(!(N||A===undefined||typeof A=="number"||typeof A=="boolean")){throw new Error(E+" must be number or boolean")}if(N){var x=e.util.getData(A.$data,v,e.dataPathArr),O="exclusive"+l,q="exclType"+l,Q="exclIsNumber"+l,U="op"+l,I="' + "+U+" + '";s+=" var schemaExcl"+l+" = "+x+"; ";x="schemaExcl"+l;s+=" var "+O+"; var "+q+" = typeof "+x+"; if ("+q+" != 'boolean' && "+q+" != 'undefined' && "+q+" != 'number') { ";var d=E;var T=T||[];T.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: '"+E+" should be boolean' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var J=s;s=T.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+J+"]); "}else{s+=" validate.errors = ["+J+"]; return false; "}}else{s+=" var err = "+J+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}s+=" "+q+" == 'number' ? ( ("+O+" = "+w+" === undefined || "+x+" "+a+"= "+w+") ? "+R+" "+z+"= "+x+" : "+R+" "+z+" "+w+" ) : ( ("+O+" = "+x+" === true) ? "+R+" "+z+"= "+w+" : "+R+" "+z+" "+w+" ) || "+R+" !== "+R+") { var op"+l+" = "+O+" ? '"+a+"' : '"+a+"='; ";if(r===undefined){d=E;b=e.errSchemaPath+"/"+E;w=x;j=N}}else{var Q=typeof A=="number",I=a;if(Q&&j){var U="'"+I+"'";s+=" if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}s+=" ( "+w+" === undefined || "+A+" "+a+"= "+w+" ? "+R+" "+z+"= "+A+" : "+R+" "+z+" "+w+" ) || "+R+" !== "+R+") { "}else{if(Q&&r===undefined){O=true;d=E;b=e.errSchemaPath+"/"+E;w=A;z+="="}else{if(Q)w=Math[F?"min":"max"](A,r);if(A===(Q?w:true)){O=true;d=E;b=e.errSchemaPath+"/"+E;z+="="}else{O=false;I+="="}}var U="'"+I+"'";s+=" if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}s+=" "+R+" "+z+" "+w+" || "+R+" !== "+R+") { "}}d=d||n;var T=T||[];T.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { comparison: "+U+", limit: "+w+", exclusive: "+O+" } ";if(e.opts.messages!==false){s+=" , message: 'should be "+I+" ";if(j){s+="' + "+w}else{s+=""+w+"'"}}if(e.opts.verbose){s+=" , schema: ";if(j){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var J=s;s=T.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+J+"]); "}else{s+=" validate.errors = ["+J+"]; return false; "}}else{s+=" var err = "+J+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(p){s+=" else { "}return s}},5675:e=>{"use strict";e.exports=function generate__limitItems(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}if(!(j||typeof r=="number")){throw new Error(n+" must be number")}var F=n=="maxItems"?">":"<";s+="if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}s+=" "+R+".length "+F+" "+w+") { ";var d=n;var E=E||[];E.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { limit: "+w+" } ";if(e.opts.messages!==false){s+=" , message: 'should NOT have ";if(n=="maxItems"){s+="more"}else{s+="fewer"}s+=" than ";if(j){s+="' + "+w+" + '"}else{s+=""+r}s+=" items' "}if(e.opts.verbose){s+=" , schema: ";if(j){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var A=s;s=E.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+A+"]); "}else{s+=" validate.errors = ["+A+"]; return false; "}}else{s+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(p){s+=" else { "}return s}},6051:e=>{"use strict";e.exports=function generate__limitLength(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}if(!(j||typeof r=="number")){throw new Error(n+" must be number")}var F=n=="maxLength"?">":"<";s+="if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}if(e.opts.unicode===false){s+=" "+R+".length "}else{s+=" ucs2length("+R+") "}s+=" "+F+" "+w+") { ";var d=n;var E=E||[];E.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { limit: "+w+" } ";if(e.opts.messages!==false){s+=" , message: 'should NOT be ";if(n=="maxLength"){s+="longer"}else{s+="shorter"}s+=" than ";if(j){s+="' + "+w+" + '"}else{s+=""+r}s+=" characters' "}if(e.opts.verbose){s+=" , schema: ";if(j){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var A=s;s=E.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+A+"]); "}else{s+=" validate.errors = ["+A+"]; return false; "}}else{s+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(p){s+=" else { "}return s}},7043:e=>{"use strict";e.exports=function generate__limitProperties(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}if(!(j||typeof r=="number")){throw new Error(n+" must be number")}var F=n=="maxProperties"?">":"<";s+="if ( ";if(j){s+=" ("+w+" !== undefined && typeof "+w+" != 'number') || "}s+=" Object.keys("+R+").length "+F+" "+w+") { ";var d=n;var E=E||[];E.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { limit: "+w+" } ";if(e.opts.messages!==false){s+=" , message: 'should NOT have ";if(n=="maxProperties"){s+="more"}else{s+="fewer"}s+=" than ";if(j){s+="' + "+w+" + '"}else{s+=""+r}s+=" properties' "}if(e.opts.verbose){s+=" , schema: ";if(j){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var A=s;s=E.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+A+"]); "}else{s+=" validate.errors = ["+A+"]; return false; "}}else{s+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(p){s+=" else { "}return s}},3639:e=>{"use strict";e.exports=function generate_allOf(e,n,f){var s=" ";var l=e.schema[n];var v=e.schemaPath+e.util.getProperty(n);var r=e.errSchemaPath+"/"+n;var g=!e.opts.allErrors;var b=e.util.copy(e);var p="";b.level++;var d="valid"+b.level;var R=b.baseId,j=true;var w=l;if(w){var F,E=-1,A=w.length-1;while(E0||F===false:e.util.schemaHasRules(F,e.RULES.all)){j=false;b.schema=F;b.schemaPath=v+"["+E+"]";b.errSchemaPath=r+"/"+E;s+=" "+e.validate(b)+" ";b.baseId=R;if(g){s+=" if ("+d+") { ";p+="}"}}}}if(g){if(j){s+=" if (true) { "}else{s+=" "+p.slice(0,-1)+" "}}return s}},1256:e=>{"use strict";e.exports=function generate_anyOf(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);var F="";w.level++;var E="valid"+w.level;var A=r.every(function(n){return e.opts.strictKeywords?typeof n=="object"&&Object.keys(n).length>0||n===false:e.util.schemaHasRules(n,e.RULES.all)});if(A){var N=w.baseId;s+=" var "+j+" = errors; var "+R+" = false; ";var a=e.compositeRule;e.compositeRule=w.compositeRule=true;var z=r;if(z){var x,O=-1,q=z.length-1;while(O{"use strict";e.exports=function generate_comment(e,n,f){var s=" ";var l=e.schema[n];var v=e.errSchemaPath+"/"+n;var r=!e.opts.allErrors;var g=e.util.toQuotedString(l);if(e.opts.$comment===true){s+=" console.log("+g+");"}else if(typeof e.opts.$comment=="function"){s+=" self._opts.$comment("+g+", "+e.util.toQuotedString(v)+", validate.root.schema);"}return s}},184:e=>{"use strict";e.exports=function generate_const(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}if(!j){s+=" var schema"+l+" = validate.schema"+g+";"}s+="var "+R+" = equal("+d+", schema"+l+"); if (!"+R+") { ";var F=F||[];F.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { allowedValue: schema"+l+" } ";if(e.opts.messages!==false){s+=" , message: 'should be equal to constant' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var E=s;s=F.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+E+"]); "}else{s+=" validate.errors = ["+E+"]; return false; "}}else{s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" }";if(p){s+=" else { "}return s}},7419:e=>{"use strict";e.exports=function generate_contains(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);var F="";w.level++;var E="valid"+w.level;var A="i"+l,N=w.dataLevel=e.dataLevel+1,a="data"+N,z=e.baseId,x=e.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:e.util.schemaHasRules(r,e.RULES.all);s+="var "+j+" = errors;var "+R+";";if(x){var O=e.compositeRule;e.compositeRule=w.compositeRule=true;w.schema=r;w.schemaPath=g;w.errSchemaPath=b;s+=" var "+E+" = false; for (var "+A+" = 0; "+A+" < "+d+".length; "+A+"++) { ";w.errorPath=e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers,true);var q=d+"["+A+"]";w.dataPathArr[N]=A;var Q=e.validate(w);w.baseId=z;if(e.util.varOccurences(Q,a)<2){s+=" "+e.util.varReplace(Q,a,q)+" "}else{s+=" var "+a+" = "+q+"; "+Q+" "}s+=" if ("+E+") break; } ";e.compositeRule=w.compositeRule=O;s+=" "+F+" if (!"+E+") {"}else{s+=" if ("+d+".length == 0) {"}var U=U||[];U.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: 'should contain a valid item' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var I=s;s=U.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+I+"]); "}else{s+=" validate.errors = ["+I+"]; return false; "}}else{s+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { ";if(x){s+=" errors = "+j+"; if (vErrors !== null) { if ("+j+") vErrors.length = "+j+"; else vErrors = null; } "}if(e.opts.allErrors){s+=" } "}return s}},7921:e=>{"use strict";e.exports=function generate_custom(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d;var R="data"+(v||"");var j="valid"+l;var w="errs__"+l;var F=e.opts.$data&&r&&r.$data,E;if(F){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";E="schema"+l}else{E=r}var A=this,N="definition"+l,a=A.definition,z="";var x,O,q,Q,U;if(F&&a.$data){U="keywordValidate"+l;var I=a.validateSchema;s+=" var "+N+" = RULES.custom['"+n+"'].definition; var "+U+" = "+N+".validate;"}else{Q=e.useCustomRule(A,r,e.schema,e);if(!Q)return;E="validate.schema"+g;U=Q.code;x=a.compile;O=a.inline;q=a.macro}var T=U+".errors",J="i"+l,L="ruleErr"+l,M=a.async;if(M&&!e.async)throw new Error("async keyword in sync schema");if(!(O||q)){s+=""+T+" = null;"}s+="var "+w+" = errors;var "+j+";";if(F&&a.$data){z+="}";s+=" if ("+E+" === undefined) { "+j+" = true; } else { ";if(I){z+="}";s+=" "+j+" = "+N+".validateSchema("+E+"); if ("+j+") { "}}if(O){if(a.statements){s+=" "+Q.validate+" "}else{s+=" "+j+" = "+Q.validate+"; "}}else if(q){var C=e.util.copy(e);var z="";C.level++;var H="valid"+C.level;C.schema=Q.validate;C.schemaPath="";var G=e.compositeRule;e.compositeRule=C.compositeRule=true;var Y=e.validate(C).replace(/validate\.schema/g,U);e.compositeRule=C.compositeRule=G;s+=" "+Y}else{var W=W||[];W.push(s);s="";s+=" "+U+".call( ";if(e.opts.passContext){s+="this"}else{s+="self"}if(x||a.schema===false){s+=" , "+R+" "}else{s+=" , "+E+" , "+R+" , validate.schema"+e.schemaPath+" "}s+=" , (dataPath || '')";if(e.errorPath!='""'){s+=" + "+e.errorPath}var X=v?"data"+(v-1||""):"parentData",c=v?e.dataPathArr[v]:"parentDataProperty";s+=" , "+X+" , "+c+" , rootData ) ";var B=s;s=W.pop();if(a.errors===false){s+=" "+j+" = ";if(M){s+="await "}s+=""+B+"; "}else{if(M){T="customErrors"+l;s+=" var "+T+" = null; try { "+j+" = await "+B+"; } catch (e) { "+j+" = false; if (e instanceof ValidationError) "+T+" = e.errors; else throw e; } "}else{s+=" "+T+" = null; "+j+" = "+B+"; "}}}if(a.modifying){s+=" if ("+X+") "+R+" = "+X+"["+c+"];"}s+=""+z;if(a.valid){if(p){s+=" if (true) { "}}else{s+=" if ( ";if(a.valid===undefined){s+=" !";if(q){s+=""+H}else{s+=""+j}}else{s+=" "+!a.valid+" "}s+=") { ";d=A.keyword;var W=W||[];W.push(s);s="";var W=W||[];W.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(d||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { keyword: '"+A.keyword+"' } ";if(e.opts.messages!==false){s+=" , message: 'should pass \""+A.keyword+"\" keyword validation' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+R+" "}s+=" } "}else{s+=" {} "}var Z=s;s=W.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+Z+"]); "}else{s+=" validate.errors = ["+Z+"]; return false; "}}else{s+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var y=s;s=W.pop();if(O){if(a.errors){if(a.errors!="full"){s+=" for (var "+J+"="+w+"; "+J+"{"use strict";e.exports=function generate_dependencies(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="errs__"+l;var j=e.util.copy(e);var w="";j.level++;var F="valid"+j.level;var E={},A={},N=e.opts.ownProperties;for(O in r){if(O=="__proto__")continue;var a=r[O];var z=Array.isArray(a)?A:E;z[O]=a}s+="var "+R+" = errors;";var x=e.errorPath;s+="var missing"+l+";";for(var O in A){z=A[O];if(z.length){s+=" if ( "+d+e.util.getProperty(O)+" !== undefined ";if(N){s+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "}if(p){s+=" && ( ";var q=z;if(q){var Q,U=-1,I=q.length-1;while(U0||a===false:e.util.schemaHasRules(a,e.RULES.all)){s+=" "+F+" = true; if ( "+d+e.util.getProperty(O)+" !== undefined ";if(N){s+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "}s+=") { ";j.schema=a;j.schemaPath=g+e.util.getProperty(O);j.errSchemaPath=b+"/"+e.util.escapeFragment(O);s+=" "+e.validate(j)+" ";j.baseId=X;s+=" } ";if(p){s+=" if ("+F+") { ";w+="}"}}}if(p){s+=" "+w+" if ("+R+" == errors) {"}return s}},9795:e=>{"use strict";e.exports=function generate_enum(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}var F="i"+l,E="schema"+l;if(!j){s+=" var "+E+" = validate.schema"+g+";"}s+="var "+R+";";if(j){s+=" if (schema"+l+" === undefined) "+R+" = true; else if (!Array.isArray(schema"+l+")) "+R+" = false; else {"}s+=""+R+" = false;for (var "+F+"=0; "+F+"<"+E+".length; "+F+"++) if (equal("+d+", "+E+"["+F+"])) { "+R+" = true; break; }";if(j){s+=" } "}s+=" if (!"+R+") { ";var A=A||[];A.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { allowedValues: schema"+l+" } ";if(e.opts.messages!==false){s+=" , message: 'should be equal to one of the allowed values' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var N=s;s=A.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+N+"]); "}else{s+=" validate.errors = ["+N+"]; return false; "}}else{s+=" var err = "+N+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" }";if(p){s+=" else { "}return s}},5801:e=>{"use strict";e.exports=function generate_format(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");if(e.opts.format===false){if(p){s+=" if (true) { "}return s}var R=e.opts.$data&&r&&r.$data,j;if(R){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";j="schema"+l}else{j=r}var w=e.opts.unknownFormats,F=Array.isArray(w);if(R){var E="format"+l,A="isObject"+l,N="formatType"+l;s+=" var "+E+" = formats["+j+"]; var "+A+" = typeof "+E+" == 'object' && !("+E+" instanceof RegExp) && "+E+".validate; var "+N+" = "+A+" && "+E+".type || 'string'; if ("+A+") { ";if(e.async){s+=" var async"+l+" = "+E+".async; "}s+=" "+E+" = "+E+".validate; } if ( ";if(R){s+=" ("+j+" !== undefined && typeof "+j+" != 'string') || "}s+=" (";if(w!="ignore"){s+=" ("+j+" && !"+E+" ";if(F){s+=" && self._opts.unknownFormats.indexOf("+j+") == -1 "}s+=") || "}s+=" ("+E+" && "+N+" == '"+f+"' && !(typeof "+E+" == 'function' ? ";if(e.async){s+=" (async"+l+" ? await "+E+"("+d+") : "+E+"("+d+")) "}else{s+=" "+E+"("+d+") "}s+=" : "+E+".test("+d+"))))) {"}else{var E=e.formats[r];if(!E){if(w=="ignore"){e.logger.warn('unknown format "'+r+'" ignored in schema at path "'+e.errSchemaPath+'"');if(p){s+=" if (true) { "}return s}else if(F&&w.indexOf(r)>=0){if(p){s+=" if (true) { "}return s}else{throw new Error('unknown format "'+r+'" is used in schema at path "'+e.errSchemaPath+'"')}}var A=typeof E=="object"&&!(E instanceof RegExp)&&E.validate;var N=A&&E.type||"string";if(A){var a=E.async===true;E=E.validate}if(N!=f){if(p){s+=" if (true) { "}return s}if(a){if(!e.async)throw new Error("async format in sync schema");var z="formats"+e.util.getProperty(r)+".validate";s+=" if (!(await "+z+"("+d+"))) { "}else{s+=" if (! ";var z="formats"+e.util.getProperty(r);if(A)z+=".validate";if(typeof E=="function"){s+=" "+z+"("+d+") "}else{s+=" "+z+".test("+d+") "}s+=") { "}}var x=x||[];x.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { format: ";if(R){s+=""+j}else{s+=""+e.util.toQuotedString(r)}s+=" } ";if(e.opts.messages!==false){s+=" , message: 'should match format \"";if(R){s+="' + "+j+" + '"}else{s+=""+e.util.escapeQuotes(r)}s+="\"' "}if(e.opts.verbose){s+=" , schema: ";if(R){s+="validate.schema"+g}else{s+=""+e.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var O=s;s=x.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+O+"]); "}else{s+=" validate.errors = ["+O+"]; return false; "}}else{s+=" var err = "+O+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(p){s+=" else { "}return s}},4962:e=>{"use strict";e.exports=function generate_if(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);w.level++;var F="valid"+w.level;var E=e.schema["then"],A=e.schema["else"],N=E!==undefined&&(e.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===false:e.util.schemaHasRules(E,e.RULES.all)),a=A!==undefined&&(e.opts.strictKeywords?typeof A=="object"&&Object.keys(A).length>0||A===false:e.util.schemaHasRules(A,e.RULES.all)),z=w.baseId;if(N||a){var x;w.createErrors=false;w.schema=r;w.schemaPath=g;w.errSchemaPath=b;s+=" var "+j+" = errors; var "+R+" = true; ";var O=e.compositeRule;e.compositeRule=w.compositeRule=true;s+=" "+e.validate(w)+" ";w.baseId=z;w.createErrors=true;s+=" errors = "+j+"; if (vErrors !== null) { if ("+j+") vErrors.length = "+j+"; else vErrors = null; } ";e.compositeRule=w.compositeRule=O;if(N){s+=" if ("+F+") { ";w.schema=e.schema["then"];w.schemaPath=e.schemaPath+".then";w.errSchemaPath=e.errSchemaPath+"/then";s+=" "+e.validate(w)+" ";w.baseId=z;s+=" "+R+" = "+F+"; ";if(N&&a){x="ifClause"+l;s+=" var "+x+" = 'then'; "}else{x="'then'"}s+=" } ";if(a){s+=" else { "}}else{s+=" if (!"+F+") { "}if(a){w.schema=e.schema["else"];w.schemaPath=e.schemaPath+".else";w.errSchemaPath=e.errSchemaPath+"/else";s+=" "+e.validate(w)+" ";w.baseId=z;s+=" "+R+" = "+F+"; ";if(N&&a){x="ifClause"+l;s+=" var "+x+" = 'else'; "}else{x="'else'"}s+=" } "}s+=" if (!"+R+") { var err = ";if(e.createErrors!==false){s+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { failingKeyword: "+x+" } ";if(e.opts.messages!==false){s+=" , message: 'should match \"' + "+x+" + '\" schema' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+=" } ";if(p){s+=" else { "}}else{if(p){s+=" if (true) { "}}return s}},4124:(e,n,f)=>{"use strict";e.exports={$ref:f(5746),allOf:f(3639),anyOf:f(1256),$comment:f(2660),const:f(184),contains:f(7419),dependencies:f(7299),enum:f(9795),format:f(5801),if:f(4962),items:f(9623),maximum:f(3711),minimum:f(3711),maxItems:f(5675),minItems:f(5675),maxLength:f(6051),minLength:f(6051),maxProperties:f(7043),minProperties:f(7043),multipleOf:f(9251),not:f(7739),oneOf:f(6857),pattern:f(8099),properties:f(9438),propertyNames:f(3466),required:f(8430),uniqueItems:f(2207),validate:f(6131)}},9623:e=>{"use strict";e.exports=function generate_items(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);var F="";w.level++;var E="valid"+w.level;var A="i"+l,N=w.dataLevel=e.dataLevel+1,a="data"+N,z=e.baseId;s+="var "+j+" = errors;var "+R+";";if(Array.isArray(r)){var x=e.schema.additionalItems;if(x===false){s+=" "+R+" = "+d+".length <= "+r.length+"; ";var O=b;b=e.errSchemaPath+"/additionalItems";s+=" if (!"+R+") { ";var q=q||[];q.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { limit: "+r.length+" } ";if(e.opts.messages!==false){s+=" , message: 'should NOT have more than "+r.length+" items' "}if(e.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var Q=s;s=q.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+Q+"]); "}else{s+=" validate.errors = ["+Q+"]; return false; "}}else{s+=" var err = "+Q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";b=O;if(p){F+="}";s+=" else { "}}var U=r;if(U){var I,T=-1,J=U.length-1;while(T0||I===false:e.util.schemaHasRules(I,e.RULES.all)){s+=" "+E+" = true; if ("+d+".length > "+T+") { ";var L=d+"["+T+"]";w.schema=I;w.schemaPath=g+"["+T+"]";w.errSchemaPath=b+"/"+T;w.errorPath=e.util.getPathExpr(e.errorPath,T,e.opts.jsonPointers,true);w.dataPathArr[N]=T;var M=e.validate(w);w.baseId=z;if(e.util.varOccurences(M,a)<2){s+=" "+e.util.varReplace(M,a,L)+" "}else{s+=" var "+a+" = "+L+"; "+M+" "}s+=" } ";if(p){s+=" if ("+E+") { ";F+="}"}}}}if(typeof x=="object"&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===false:e.util.schemaHasRules(x,e.RULES.all))){w.schema=x;w.schemaPath=e.schemaPath+".additionalItems";w.errSchemaPath=e.errSchemaPath+"/additionalItems";s+=" "+E+" = true; if ("+d+".length > "+r.length+") { for (var "+A+" = "+r.length+"; "+A+" < "+d+".length; "+A+"++) { ";w.errorPath=e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers,true);var L=d+"["+A+"]";w.dataPathArr[N]=A;var M=e.validate(w);w.baseId=z;if(e.util.varOccurences(M,a)<2){s+=" "+e.util.varReplace(M,a,L)+" "}else{s+=" var "+a+" = "+L+"; "+M+" "}if(p){s+=" if (!"+E+") break; "}s+=" } } ";if(p){s+=" if ("+E+") { ";F+="}"}}}else if(e.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:e.util.schemaHasRules(r,e.RULES.all)){w.schema=r;w.schemaPath=g;w.errSchemaPath=b;s+=" for (var "+A+" = "+0+"; "+A+" < "+d+".length; "+A+"++) { ";w.errorPath=e.util.getPathExpr(e.errorPath,A,e.opts.jsonPointers,true);var L=d+"["+A+"]";w.dataPathArr[N]=A;var M=e.validate(w);w.baseId=z;if(e.util.varOccurences(M,a)<2){s+=" "+e.util.varReplace(M,a,L)+" "}else{s+=" var "+a+" = "+L+"; "+M+" "}if(p){s+=" if (!"+E+") break; "}s+=" }"}if(p){s+=" "+F+" if ("+j+" == errors) {"}return s}},9251:e=>{"use strict";e.exports=function generate_multipleOf(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R=e.opts.$data&&r&&r.$data,j;if(R){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";j="schema"+l}else{j=r}if(!(R||typeof r=="number")){throw new Error(n+" must be number")}s+="var division"+l+";if (";if(R){s+=" "+j+" !== undefined && ( typeof "+j+" != 'number' || "}s+=" (division"+l+" = "+d+" / "+j+", ";if(e.opts.multipleOfPrecision){s+=" Math.abs(Math.round(division"+l+") - division"+l+") > 1e-"+e.opts.multipleOfPrecision+" "}else{s+=" division"+l+" !== parseInt(division"+l+") "}s+=" ) ";if(R){s+=" ) "}s+=" ) { ";var w=w||[];w.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { multipleOf: "+j+" } ";if(e.opts.messages!==false){s+=" , message: 'should be multiple of ";if(R){s+="' + "+j}else{s+=""+j+"'"}}if(e.opts.verbose){s+=" , schema: ";if(R){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var F=s;s=w.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+F+"]); "}else{s+=" validate.errors = ["+F+"]; return false; "}}else{s+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(p){s+=" else { "}return s}},7739:e=>{"use strict";e.exports=function generate_not(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="errs__"+l;var j=e.util.copy(e);j.level++;var w="valid"+j.level;if(e.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:e.util.schemaHasRules(r,e.RULES.all)){j.schema=r;j.schemaPath=g;j.errSchemaPath=b;s+=" var "+R+" = errors; ";var F=e.compositeRule;e.compositeRule=j.compositeRule=true;j.createErrors=false;var E;if(j.opts.allErrors){E=j.opts.allErrors;j.opts.allErrors=false}s+=" "+e.validate(j)+" ";j.createErrors=true;if(E)j.opts.allErrors=E;e.compositeRule=j.compositeRule=F;s+=" if ("+w+") { ";var A=A||[];A.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var N=s;s=A.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+N+"]); "}else{s+=" validate.errors = ["+N+"]; return false; "}}else{s+=" var err = "+N+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { errors = "+R+"; if (vErrors !== null) { if ("+R+") vErrors.length = "+R+"; else vErrors = null; } ";if(e.opts.allErrors){s+=" } "}}else{s+=" var err = ";if(e.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(p){s+=" if (false) { "}}return s}},6857:e=>{"use strict";e.exports=function generate_oneOf(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j="errs__"+l;var w=e.util.copy(e);var F="";w.level++;var E="valid"+w.level;var A=w.baseId,N="prevValid"+l,a="passingSchemas"+l;s+="var "+j+" = errors , "+N+" = false , "+R+" = false , "+a+" = null; ";var z=e.compositeRule;e.compositeRule=w.compositeRule=true;var x=r;if(x){var O,q=-1,Q=x.length-1;while(q0||O===false:e.util.schemaHasRules(O,e.RULES.all)){w.schema=O;w.schemaPath=g+"["+q+"]";w.errSchemaPath=b+"/"+q;s+=" "+e.validate(w)+" ";w.baseId=A}else{s+=" var "+E+" = true; "}if(q){s+=" if ("+E+" && "+N+") { "+R+" = false; "+a+" = ["+a+", "+q+"]; } else { ";F+="}"}s+=" if ("+E+") { "+R+" = "+N+" = true; "+a+" = "+q+"; }"}}e.compositeRule=w.compositeRule=z;s+=""+F+"if (!"+R+") { var err = ";if(e.createErrors!==false){s+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { passingSchemas: "+a+" } ";if(e.opts.messages!==false){s+=" , message: 'should match exactly one schema in oneOf' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+="} else { errors = "+j+"; if (vErrors !== null) { if ("+j+") vErrors.length = "+j+"; else vErrors = null; }";if(e.opts.allErrors){s+=" } "}return s}},8099:e=>{"use strict";e.exports=function generate_pattern(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R=e.opts.$data&&r&&r.$data,j;if(R){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";j="schema"+l}else{j=r}var w=R?"(new RegExp("+j+"))":e.usePattern(r);s+="if ( ";if(R){s+=" ("+j+" !== undefined && typeof "+j+" != 'string') || "}s+=" !"+w+".test("+d+") ) { ";var F=F||[];F.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { pattern: ";if(R){s+=""+j}else{s+=""+e.util.toQuotedString(r)}s+=" } ";if(e.opts.messages!==false){s+=" , message: 'should match pattern \"";if(R){s+="' + "+j+" + '"}else{s+=""+e.util.escapeQuotes(r)}s+="\"' "}if(e.opts.verbose){s+=" , schema: ";if(R){s+="validate.schema"+g}else{s+=""+e.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var E=s;s=F.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+E+"]); "}else{s+=" validate.errors = ["+E+"]; return false; "}}else{s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(p){s+=" else { "}return s}},9438:e=>{"use strict";e.exports=function generate_properties(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="errs__"+l;var j=e.util.copy(e);var w="";j.level++;var F="valid"+j.level;var E="key"+l,A="idx"+l,N=j.dataLevel=e.dataLevel+1,a="data"+N,z="dataProperties"+l;var x=Object.keys(r||{}).filter(notProto),O=e.schema.patternProperties||{},q=Object.keys(O).filter(notProto),Q=e.schema.additionalProperties,U=x.length||q.length,I=Q===false,T=typeof Q=="object"&&Object.keys(Q).length,J=e.opts.removeAdditional,L=I||T||J,M=e.opts.ownProperties,C=e.baseId;var H=e.schema.required;if(H&&!(e.opts.$data&&H.$data)&&H.length8){s+=" || validate.schema"+g+".hasOwnProperty("+E+") "}else{var Y=x;if(Y){var W,X=-1,c=Y.length-1;while(X0||t===false:e.util.schemaHasRules(t,e.RULES.all)){var ee=e.util.getProperty(W),P=d+ee,ne=_&&t.default!==undefined;j.schema=t;j.schemaPath=g+ee;j.errSchemaPath=b+"/"+e.util.escapeFragment(W);j.errorPath=e.util.getPath(e.errorPath,W,e.opts.jsonPointers);j.dataPathArr[N]=e.util.toQuotedString(W);var i=e.validate(j);j.baseId=C;if(e.util.varOccurences(i,a)<2){i=e.util.varReplace(i,a,P);var fe=P}else{var fe=a;s+=" var "+a+" = "+P+"; "}if(ne){s+=" "+i+" "}else{if(G&&G[W]){s+=" if ( "+fe+" === undefined ";if(M){s+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(W)+"') "}s+=") { "+F+" = false; ";var K=e.errorPath,V=b,se=e.util.escapeQuotes(W);if(e.opts._errorDataPathProperty){e.errorPath=e.util.getPath(K,W,e.opts.jsonPointers)}b=e.errSchemaPath+"/required";var k=k||[];k.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { missingProperty: '"+se+"' } ";if(e.opts.messages!==false){s+=" , message: '";if(e.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+se+"\\'"}s+="' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var h=s;s=k.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+h+"]); "}else{s+=" validate.errors = ["+h+"]; return false; "}}else{s+=" var err = "+h+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}b=V;e.errorPath=K;s+=" } else { "}else{if(p){s+=" if ( "+fe+" === undefined ";if(M){s+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(W)+"') "}s+=") { "+F+" = true; } else { "}else{s+=" if ("+fe+" !== undefined ";if(M){s+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(W)+"') "}s+=" ) { "}}s+=" "+i+" } "}}if(p){s+=" if ("+F+") { ";w+="}"}}}}if(q.length){var le=q;if(le){var Z,ve=-1,re=le.length-1;while(ve0||t===false:e.util.schemaHasRules(t,e.RULES.all)){j.schema=t;j.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(Z);j.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(Z);if(M){s+=" "+z+" = "+z+" || Object.keys("+d+"); for (var "+A+"=0; "+A+"<"+z+".length; "+A+"++) { var "+E+" = "+z+"["+A+"]; "}else{s+=" for (var "+E+" in "+d+") { "}s+=" if ("+e.usePattern(Z)+".test("+E+")) { ";j.errorPath=e.util.getPathExpr(e.errorPath,E,e.opts.jsonPointers);var P=d+"["+E+"]";j.dataPathArr[N]=E;var i=e.validate(j);j.baseId=C;if(e.util.varOccurences(i,a)<2){s+=" "+e.util.varReplace(i,a,P)+" "}else{s+=" var "+a+" = "+P+"; "+i+" "}if(p){s+=" if (!"+F+") break; "}s+=" } ";if(p){s+=" else "+F+" = true; "}s+=" } ";if(p){s+=" if ("+F+") { ";w+="}"}}}}}if(p){s+=" "+w+" if ("+R+" == errors) {"}return s}},3466:e=>{"use strict";e.exports=function generate_propertyNames(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="errs__"+l;var j=e.util.copy(e);var w="";j.level++;var F="valid"+j.level;s+="var "+R+" = errors;";if(e.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:e.util.schemaHasRules(r,e.RULES.all)){j.schema=r;j.schemaPath=g;j.errSchemaPath=b;var E="key"+l,A="idx"+l,N="i"+l,a="' + "+E+" + '",z=j.dataLevel=e.dataLevel+1,x="data"+z,O="dataProperties"+l,q=e.opts.ownProperties,Q=e.baseId;if(q){s+=" var "+O+" = undefined; "}if(q){s+=" "+O+" = "+O+" || Object.keys("+d+"); for (var "+A+"=0; "+A+"<"+O+".length; "+A+"++) { var "+E+" = "+O+"["+A+"]; "}else{s+=" for (var "+E+" in "+d+") { "}s+=" var startErrs"+l+" = errors; ";var U=E;var I=e.compositeRule;e.compositeRule=j.compositeRule=true;var T=e.validate(j);j.baseId=Q;if(e.util.varOccurences(T,x)<2){s+=" "+e.util.varReplace(T,x,U)+" "}else{s+=" var "+x+" = "+U+"; "+T+" "}e.compositeRule=j.compositeRule=I;s+=" if (!"+F+") { for (var "+N+"=startErrs"+l+"; "+N+"{"use strict";e.exports=function generate_ref(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.errSchemaPath+"/"+n;var b=!e.opts.allErrors;var p="data"+(v||"");var d="valid"+l;var R,j;if(r=="#"||r=="#/"){if(e.isRoot){R=e.async;j="validate"}else{R=e.root.schema.$async===true;j="root.refVal[0]"}}else{var w=e.resolveRef(e.baseId,r,e.isRoot);if(w===undefined){var F=e.MissingRefError.message(e.baseId,r);if(e.opts.missingRefs=="fail"){e.logger.error(F);var E=E||[];E.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"$ref"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { ref: '"+e.util.escapeQuotes(r)+"' } ";if(e.opts.messages!==false){s+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(r)+"' "}if(e.opts.verbose){s+=" , schema: "+e.util.toQuotedString(r)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "}s+=" } "}else{s+=" {} "}var A=s;s=E.pop();if(!e.compositeRule&&b){if(e.async){s+=" throw new ValidationError(["+A+"]); "}else{s+=" validate.errors = ["+A+"]; return false; "}}else{s+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}if(b){s+=" if (false) { "}}else if(e.opts.missingRefs=="ignore"){e.logger.warn(F);if(b){s+=" if (true) { "}}else{throw new e.MissingRefError(e.baseId,r,F)}}else if(w.inline){var N=e.util.copy(e);N.level++;var a="valid"+N.level;N.schema=w.schema;N.schemaPath="";N.errSchemaPath=r;var z=e.validate(N).replace(/validate\.schema/g,w.code);s+=" "+z+" ";if(b){s+=" if ("+a+") { "}}else{R=w.$async===true||e.async&&w.$async!==false;j=w.code}}if(j){var E=E||[];E.push(s);s="";if(e.opts.passContext){s+=" "+j+".call(this, "}else{s+=" "+j+"( "}s+=" "+p+", (dataPath || '')";if(e.errorPath!='""'){s+=" + "+e.errorPath}var x=v?"data"+(v-1||""):"parentData",O=v?e.dataPathArr[v]:"parentDataProperty";s+=" , "+x+" , "+O+", rootData) ";var q=s;s=E.pop();if(R){if(!e.async)throw new Error("async schema referenced by sync schema");if(b){s+=" var "+d+"; "}s+=" try { await "+q+"; ";if(b){s+=" "+d+" = true; "}s+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";if(b){s+=" "+d+" = false; "}s+=" } ";if(b){s+=" if ("+d+") { "}}else{s+=" if (!"+q+") { if (vErrors === null) vErrors = "+j+".errors; else vErrors = vErrors.concat("+j+".errors); errors = vErrors.length; } ";if(b){s+=" else { "}}}return s}},8430:e=>{"use strict";e.exports=function generate_required(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}var F="schema"+l;if(!j){if(r.length0||x===false:e.util.schemaHasRules(x,e.RULES.all)))){E[E.length]=N}}}}else{var E=r}}if(j||E.length){var O=e.errorPath,q=j||E.length>=e.opts.loopRequired,Q=e.opts.ownProperties;if(p){s+=" var missing"+l+"; ";if(q){if(!j){s+=" var "+F+" = validate.schema"+g+"; "}var U="i"+l,I="schema"+l+"["+U+"]",T="' + "+I+" + '";if(e.opts._errorDataPathProperty){e.errorPath=e.util.getPathExpr(O,I,e.opts.jsonPointers)}s+=" var "+R+" = true; ";if(j){s+=" if (schema"+l+" === undefined) "+R+" = true; else if (!Array.isArray(schema"+l+")) "+R+" = false; else {"}s+=" for (var "+U+" = 0; "+U+" < "+F+".length; "+U+"++) { "+R+" = "+d+"["+F+"["+U+"]] !== undefined ";if(Q){s+=" && Object.prototype.hasOwnProperty.call("+d+", "+F+"["+U+"]) "}s+="; if (!"+R+") break; } ";if(j){s+=" } "}s+=" if (!"+R+") { ";var J=J||[];J.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { missingProperty: '"+T+"' } ";if(e.opts.messages!==false){s+=" , message: '";if(e.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+T+"\\'"}s+="' "}if(e.opts.verbose){s+=" , schema: validate.schema"+g+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var L=s;s=J.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+L+"]); "}else{s+=" validate.errors = ["+L+"]; return false; "}}else{s+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { "}else{s+=" if ( ";var M=E;if(M){var C,U=-1,H=M.length-1;while(U{"use strict";e.exports=function generate_uniqueItems(e,n,f){var s=" ";var l=e.level;var v=e.dataLevel;var r=e.schema[n];var g=e.schemaPath+e.util.getProperty(n);var b=e.errSchemaPath+"/"+n;var p=!e.opts.allErrors;var d="data"+(v||"");var R="valid"+l;var j=e.opts.$data&&r&&r.$data,w;if(j){s+=" var schema"+l+" = "+e.util.getData(r.$data,v,e.dataPathArr)+"; ";w="schema"+l}else{w=r}if((r||j)&&e.opts.uniqueItems!==false){if(j){s+=" var "+R+"; if ("+w+" === false || "+w+" === undefined) "+R+" = true; else if (typeof "+w+" != 'boolean') "+R+" = false; else { "}s+=" var i = "+d+".length , "+R+" = true , j; if (i > 1) { ";var F=e.schema.items&&e.schema.items.type,E=Array.isArray(F);if(!F||F=="object"||F=="array"||E&&(F.indexOf("object")>=0||F.indexOf("array")>=0)){s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+d+"[i], "+d+"[j])) { "+R+" = false; break outer; } } } "}else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+d+"[i]; ";var A="checkDataType"+(E?"s":"");s+=" if ("+e.util[A](F,"item",e.opts.strictNumbers,true)+") continue; ";if(E){s+=" if (typeof item == 'string') item = '\"' + item; "}s+=" if (typeof itemIndices[item] == 'number') { "+R+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ";if(j){s+=" } "}s+=" if (!"+R+") { ";var N=N||[];N.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+"uniqueItems"+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(b)+" , params: { i: i, j: j } ";if(e.opts.messages!==false){s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "}if(e.opts.verbose){s+=" , schema: ";if(j){s+="validate.schema"+g}else{s+=""+r}s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var a=s;s=N.pop();if(!e.compositeRule&&p){if(e.async){s+=" throw new ValidationError(["+a+"]); "}else{s+=" validate.errors = ["+a+"]; return false; "}}else{s+=" var err = "+a+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(p){s+=" else { "}}else{if(p){s+=" if (true) { "}}return s}},6131:e=>{"use strict";e.exports=function generate_validate(e,n,f){var s="";var l=e.schema.$async===true,v=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),r=e.self._getId(e.schema);if(e.opts.strictKeywords){var g=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(g){var b="unknown keyword: "+g;if(e.opts.strictKeywords==="log")e.logger.warn(b);else throw new Error(b)}}if(e.isTop){s+=" var validate = ";if(l){e.async=true;s+="async "}s+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";if(r&&(e.opts.sourceCode||e.opts.processCode)){s+=" "+("/*# sourceURL="+r+" */")+" "}}if(typeof e.schema=="boolean"||!(v||e.schema.$ref)){var n="false schema";var p=e.level;var d=e.dataLevel;var R=e.schema[n];var j=e.schemaPath+e.util.getProperty(n);var w=e.errSchemaPath+"/"+n;var F=!e.opts.allErrors;var E;var A="data"+(d||"");var N="valid"+p;if(e.schema===false){if(e.isTop){F=true}else{s+=" var "+N+" = false; "}var a=a||[];a.push(s);s="";if(e.createErrors!==false){s+=" { keyword: '"+(E||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(w)+" , params: {} ";if(e.opts.messages!==false){s+=" , message: 'boolean schema is false' "}if(e.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+A+" "}s+=" } "}else{s+=" {} "}var z=s;s=a.pop();if(!e.compositeRule&&F){if(e.async){s+=" throw new ValidationError(["+z+"]); "}else{s+=" validate.errors = ["+z+"]; return false; "}}else{s+=" var err = "+z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{if(e.isTop){if(l){s+=" return data; "}else{s+=" validate.errors = null; return true; "}}else{s+=" var "+N+" = true; "}}if(e.isTop){s+=" }; return validate; "}return s}if(e.isTop){var x=e.isTop,p=e.level=0,d=e.dataLevel=0,A="data";e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema));e.baseId=e.baseId||e.rootId;delete e.isTop;e.dataPathArr=[""];if(e.schema.default!==undefined&&e.opts.useDefaults&&e.opts.strictDefaults){var O="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(O);else throw new Error(O)}s+=" var vErrors = null; ";s+=" var errors = 0; ";s+=" if (rootData === undefined) rootData = data; "}else{var p=e.level,d=e.dataLevel,A="data"+(d||"");if(r)e.baseId=e.resolve.url(e.baseId,r);if(l&&!e.async)throw new Error("async schema in sync schema");s+=" var errs_"+p+" = errors;"}var N="valid"+p,F=!e.opts.allErrors,q="",Q="";var E;var U=e.schema.type,I=Array.isArray(U);if(U&&e.opts.nullable&&e.schema.nullable===true){if(I){if(U.indexOf("null")==-1)U=U.concat("null")}else if(U!="null"){U=[U,"null"];I=true}}if(I&&U.length==1){U=U[0];I=false}if(e.schema.$ref&&v){if(e.opts.extendRefs=="fail"){throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)')}else if(e.opts.extendRefs!==true){v=false;e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"')}}if(e.schema.$comment&&e.opts.$comment){s+=" "+e.RULES.all.$comment.code(e,"$comment")}if(U){if(e.opts.coerceTypes){var T=e.util.coerceToTypes(e.opts.coerceTypes,U)}var J=e.RULES.types[U];if(T||I||J===true||J&&!$shouldUseGroup(J)){var j=e.schemaPath+".type",w=e.errSchemaPath+"/type";var j=e.schemaPath+".type",w=e.errSchemaPath+"/type",L=I?"checkDataTypes":"checkDataType";s+=" if ("+e.util[L](U,A,e.opts.strictNumbers,true)+") { ";if(T){var M="dataType"+p,C="coerced"+p;s+=" var "+M+" = typeof "+A+"; var "+C+" = undefined; ";if(e.opts.coerceTypes=="array"){s+=" if ("+M+" == 'object' && Array.isArray("+A+") && "+A+".length == 1) { "+A+" = "+A+"[0]; "+M+" = typeof "+A+"; if ("+e.util.checkDataType(e.schema.type,A,e.opts.strictNumbers)+") "+C+" = "+A+"; } "}s+=" if ("+C+" !== undefined) ; ";var H=T;if(H){var G,Y=-1,W=H.length-1;while(Y{"use strict";var s=/^[a-z_$][a-z0-9_$-]*$/i;var l=f(7921);var v=f(5533);e.exports={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(e,n){var f=this.RULES;if(f.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!s.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(n){this.validateKeyword(n,true);var v=n.type;if(Array.isArray(v)){for(var r=0;r{"use strict";e.exports=function equal(e,n){if(e===n)return true;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return false;var f,s,l;if(Array.isArray(e)){f=e.length;if(f!=n.length)return false;for(s=f;s--!==0;)if(!equal(e[s],n[s]))return false;return true}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();l=Object.keys(e);f=l.length;if(f!==Object.keys(n).length)return false;for(s=f;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,l[s]))return false;for(s=f;s--!==0;){var v=l[s];if(!equal(e[v],n[v]))return false}return true}return e!==e&&n!==n}},3600:e=>{"use strict";e.exports=function(e,n){if(!n)n={};if(typeof n==="function")n={cmp:n};var f=typeof n.cycles==="boolean"?n.cycles:false;var s=n.cmp&&function(e){return function(n){return function(f,s){var l={key:f,value:n[f]};var v={key:s,value:n[s]};return e(l,v)}}}(n.cmp);var l=[];return function stringify(e){if(e&&e.toJSON&&typeof e.toJSON==="function"){e=e.toJSON()}if(e===undefined)return;if(typeof e=="number")return isFinite(e)?""+e:"null";if(typeof e!=="object")return JSON.stringify(e);var n,v;if(Array.isArray(e)){v="[";for(n=0;n{"use strict";var n=e.exports=function(e,n,f){if(typeof n=="function"){f=n;n={}}f=n.cb||f;var s=typeof f=="function"?f:f.pre||function(){};var l=f.post||function(){};_traverse(n,s,l,e,"",e)};n.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true};n.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};n.propsKeywords={definitions:true,properties:true,patternProperties:true,dependencies:true};n.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function _traverse(e,f,s,l,v,r,g,b,p,d){if(l&&typeof l=="object"&&!Array.isArray(l)){f(l,v,r,g,b,p,d);for(var R in l){var j=l[R];if(Array.isArray(j)){if(R in n.arrayKeywords){for(var w=0;w{"use strict";Object.defineProperty(n,"__esModule",{value:true});n.default=void 0;const{stringHints:s,numberHints:l}=f(4226);const v={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};function filterMax(e,n){const f=e.reduce((e,f)=>Math.max(e,n(f)),0);return e.filter(e=>n(e)===f)}function filterChildren(e){let n=e;n=filterMax(n,e=>e.dataPath?e.dataPath.length:0);n=filterMax(n,e=>v[e.keyword]||2);return n}function findAllChildren(e,n){let f=e.length-1;const s=n=>e[f].schemaPath.indexOf(n)!==0;while(f>-1&&!n.every(s)){if(e[f].keyword==="anyOf"||e[f].keyword==="oneOf"){const n=extractRefs(e[f]);const s=findAllChildren(e.slice(0,f),n.concat(e[f].schemaPath));f=s-1}else{f-=1}}return f+1}function extractRefs(e){const{schema:n}=e;if(!Array.isArray(n)){return[]}return n.map(({$ref:e})=>e).filter(e=>e)}function groupChildrenByFirstChild(e){const n=[];let f=e.length-1;while(f>0){const s=e[f];if(s.keyword==="anyOf"||s.keyword==="oneOf"){const l=extractRefs(s);const v=findAllChildren(e.slice(0,f),l.concat(s.schemaPath));if(v!==f){n.push(Object.assign({},s,{children:e.slice(v,f)}));f=v}else{n.push(s)}}else{n.push(s)}f-=1}if(f===0){n.push(e[f])}return n.reverse()}function indent(e,n){return e.replace(/\n(?!$)/g,`\n${n}`)}function hasNotInSchema(e){return!!e.not}function findFirstTypedSchema(e){if(hasNotInSchema(e)){return findFirstTypedSchema(e.not)}return e}function canApplyNot(e){const n=findFirstTypedSchema(e);return likeNumber(n)||likeInteger(n)||likeString(n)||likeNull(n)||likeBoolean(n)}function isObject(e){return typeof e==="object"&&e!==null}function likeNumber(e){return e.type==="number"||typeof e.minimum!=="undefined"||typeof e.exclusiveMinimum!=="undefined"||typeof e.maximum!=="undefined"||typeof e.exclusiveMaximum!=="undefined"||typeof e.multipleOf!=="undefined"}function likeInteger(e){return e.type==="integer"||typeof e.minimum!=="undefined"||typeof e.exclusiveMinimum!=="undefined"||typeof e.maximum!=="undefined"||typeof e.exclusiveMaximum!=="undefined"||typeof e.multipleOf!=="undefined"}function likeString(e){return e.type==="string"||typeof e.minLength!=="undefined"||typeof e.maxLength!=="undefined"||typeof e.pattern!=="undefined"||typeof e.format!=="undefined"||typeof e.formatMinimum!=="undefined"||typeof e.formatMaximum!=="undefined"}function likeBoolean(e){return e.type==="boolean"}function likeArray(e){return e.type==="array"||typeof e.minItems==="number"||typeof e.maxItems==="number"||typeof e.uniqueItems!=="undefined"||typeof e.items!=="undefined"||typeof e.additionalItems!=="undefined"||typeof e.contains!=="undefined"}function likeObject(e){return e.type==="object"||typeof e.minProperties!=="undefined"||typeof e.maxProperties!=="undefined"||typeof e.required!=="undefined"||typeof e.properties!=="undefined"||typeof e.patternProperties!=="undefined"||typeof e.additionalProperties!=="undefined"||typeof e.dependencies!=="undefined"||typeof e.propertyNames!=="undefined"||typeof e.patternRequired!=="undefined"}function likeNull(e){return e.type==="null"}function getArticle(e){if(/^[aeiou]/i.test(e)){return"an"}return"a"}function getSchemaNonTypes(e){if(!e){return""}if(!e.type){if(likeNumber(e)||likeInteger(e)){return" | should be any non-number"}if(likeString(e)){return" | should be any non-string"}if(likeArray(e)){return" | should be any non-array"}if(likeObject(e)){return" | should be any non-object"}}return""}function formatHints(e){return e.length>0?`(${e.join(", ")})`:""}function getHints(e,n){if(likeNumber(e)||likeInteger(e)){return l(e,n)}else if(likeString(e)){return s(e,n)}return[]}class ValidationError extends Error{constructor(e,n,f={}){super();this.name="ValidationError";this.errors=e;this.schema=n;let s;let l;if(n.title&&(!f.name||!f.baseDataPath)){const e=n.title.match(/^(.+) (.+)$/);if(e){if(!f.name){[,s]=e}if(!f.baseDataPath){[,,l]=e}}}this.headerName=f.name||s||"Object";this.baseDataPath=f.baseDataPath||l||"configuration";this.postFormatter=f.postFormatter||null;const v=`Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`;this.message=`${v}${this.formatValidationErrors(e)}`;Error.captureStackTrace(this,this.constructor)}getSchemaPart(e){const n=e.split("/");let f=this.schema;for(let e=1;e{if(!l){return this.formatSchema(n,s,f)}if(f.includes(n)){return"(recursive)"}return this.formatSchema(n,s,f.concat(e))};if(hasNotInSchema(e)&&!likeObject(e)){if(canApplyNot(e.not)){s=!n;return l(e.not)}const f=!e.not.not;const v=n?"":"non ";s=!n;return f?v+l(e.not):l(e.not)}if(e.instanceof){const{instanceof:n}=e;const f=!Array.isArray(n)?[n]:n;return f.map(e=>e==="Function"?"function":e).join(" | ")}if(e.enum){return e.enum.map(e=>JSON.stringify(e)).join(" | ")}if(typeof e.const!=="undefined"){return JSON.stringify(e.const)}if(e.oneOf){return e.oneOf.map(e=>l(e,true)).join(" | ")}if(e.anyOf){return e.anyOf.map(e=>l(e,true)).join(" | ")}if(e.allOf){return e.allOf.map(e=>l(e,true)).join(" & ")}if(e.if){const{if:n,then:f,else:s}=e;return`${n?`if ${l(n)}`:""}${f?` then ${l(f)}`:""}${s?` else ${l(s)}`:""}`}if(e.$ref){return l(this.getSchemaPart(e.$ref),true)}if(likeNumber(e)||likeInteger(e)){const[f,...s]=getHints(e,n);const l=`${f}${s.length>0?` ${formatHints(s)}`:""}`;return n?l:s.length>0?`non-${f} | ${l}`:`non-${f}`}if(likeString(e)){const[f,...s]=getHints(e,n);const l=`${f}${s.length>0?` ${formatHints(s)}`:""}`;return n?l:l==="string"?"non-string":`non-string | ${l}`}if(likeBoolean(e)){return`${n?"":"non-"}boolean`}if(likeArray(e)){s=true;const n=[];if(typeof e.minItems==="number"){n.push(`should not have fewer than ${e.minItems} item${e.minItems>1?"s":""}`)}if(typeof e.maxItems==="number"){n.push(`should not have more than ${e.maxItems} item${e.maxItems>1?"s":""}`)}if(e.uniqueItems){n.push("should not have duplicate items")}const f=typeof e.additionalItems==="undefined"||Boolean(e.additionalItems);let v="";if(e.items){if(Array.isArray(e.items)&&e.items.length>0){v=`${e.items.map(e=>l(e)).join(", ")}`;if(f){if(e.additionalItems&&isObject(e.additionalItems)&&Object.keys(e.additionalItems).length>0){n.push(`additional items should be ${l(e.additionalItems)}`)}}}else if(e.items&&Object.keys(e.items).length>0){v=`${l(e.items)}`}else{v="any"}}else{v="any"}if(e.contains&&Object.keys(e.contains).length>0){n.push(`should contains at least one ${this.formatSchema(e.contains)} item`)}return`[${v}${f?", ...":""}]${n.length>0?` (${n.join(", ")})`:""}`}if(likeObject(e)){s=true;const n=[];if(typeof e.minProperties==="number"){n.push(`should not have fewer than ${e.minProperties} ${e.minProperties>1?"properties":"property"}`)}if(typeof e.maxProperties==="number"){n.push(`should not have more than ${e.maxProperties} ${e.minProperties&&e.minProperties>1?"properties":"property"}`)}if(e.patternProperties&&Object.keys(e.patternProperties).length>0){const f=Object.keys(e.patternProperties);n.push(`additional property names should match pattern${f.length>1?"s":""} ${f.map(e=>JSON.stringify(e)).join(" | ")}`)}const f=e.properties?Object.keys(e.properties):[];const v=e.required?e.required:[];const r=[...new Set([].concat(v).concat(f))];const g=r.map(e=>{const n=v.includes(e);return`${e}${n?"":"?"}`}).concat(typeof e.additionalProperties==="undefined"||Boolean(e.additionalProperties)?e.additionalProperties&&isObject(e.additionalProperties)?[`: ${l(e.additionalProperties)}`]:["…"]:[]).join(", ");const{dependencies:b,propertyNames:p,patternRequired:d}=e;if(b){Object.keys(b).forEach(e=>{const f=b[e];if(Array.isArray(f)){n.push(`should have ${f.length>1?"properties":"property"} ${f.map(e=>`'${e}'`).join(", ")} when property '${e}' is present`)}else{n.push(`should be valid according to the schema ${l(f)} when property '${e}' is present`)}})}if(p&&Object.keys(p).length>0){n.push(`each property name should match format ${JSON.stringify(e.propertyNames.format)}`)}if(d&&d.length>0){n.push(`should have property matching pattern ${d.map(e=>JSON.stringify(e))}`)}return`object {${g?` ${g} `:""}}${n.length>0?` (${n.join(", ")})`:""}`}if(likeNull(e)){return`${n?"":"non-"}null`}if(Array.isArray(e.type)){return`${e.type.join(" | ")}`}return JSON.stringify(e,null,2)}getSchemaPartText(e,n,f=false,s=true){if(!e){return""}if(Array.isArray(n)){for(let f=0;f ${e.description}`}return l}getSchemaPartDescription(e){if(!e){return""}while(e.$ref){e=this.getSchemaPart(e.$ref)}if(e.description){return`\n-> ${e.description}`}return""}formatValidationError(e){const{keyword:n,dataPath:f}=e;const s=`${this.baseDataPath}${f}`;switch(n){case"type":{const{parentSchema:n,params:f}=e;switch(f.type){case"number":return`${s} should be a ${this.getSchemaPartText(n,false,true)}`;case"integer":return`${s} should be a ${this.getSchemaPartText(n,false,true)}`;case"string":return`${s} should be a ${this.getSchemaPartText(n,false,true)}`;case"boolean":return`${s} should be a ${this.getSchemaPartText(n,false,true)}`;case"array":return`${s} should be an array:\n${this.getSchemaPartText(n)}`;case"object":return`${s} should be an object:\n${this.getSchemaPartText(n)}`;case"null":return`${s} should be a ${this.getSchemaPartText(n,false,true)}`;default:return`${s} should be:\n${this.getSchemaPartText(n)}`}}case"instanceof":{const{parentSchema:n}=e;return`${s} should be an instance of ${this.getSchemaPartText(n,false,true)}`}case"pattern":{const{params:n,parentSchema:f}=e;const{pattern:l}=n;return`${s} should match pattern ${JSON.stringify(l)}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"format":{const{params:n,parentSchema:f}=e;const{format:l}=n;return`${s} should match format ${JSON.stringify(l)}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"formatMinimum":case"formatMaximum":{const{params:n,parentSchema:f}=e;const{comparison:l,limit:v}=n;return`${s} should be ${l} ${JSON.stringify(v)}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"minimum":case"maximum":case"exclusiveMinimum":case"exclusiveMaximum":{const{parentSchema:n,params:f}=e;const{comparison:l,limit:v}=f;const[,...r]=getHints(n,true);if(r.length===0){r.push(`should be ${l} ${v}`)}return`${s} ${r.join(" ")}${getSchemaNonTypes(n)}.${this.getSchemaPartDescription(n)}`}case"multipleOf":{const{params:n,parentSchema:f}=e;const{multipleOf:l}=n;return`${s} should be multiple of ${l}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"patternRequired":{const{params:n,parentSchema:f}=e;const{missingPattern:l}=n;return`${s} should have property matching pattern ${JSON.stringify(l)}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"minLength":{const{params:n,parentSchema:f}=e;const{limit:l}=n;if(l===1){return`${s} should be an non-empty string${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}const v=l-1;return`${s} should be longer than ${v} character${v>1?"s":""}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"minItems":{const{params:n,parentSchema:f}=e;const{limit:l}=n;if(l===1){return`${s} should be an non-empty array${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}return`${s} should not have fewer than ${l} items${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"minProperties":{const{params:n,parentSchema:f}=e;const{limit:l}=n;if(l===1){return`${s} should be an non-empty object${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}return`${s} should not have fewer than ${l} properties${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"maxLength":{const{params:n,parentSchema:f}=e;const{limit:l}=n;const v=l+1;return`${s} should be shorter than ${v} character${v>1?"s":""}${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"maxItems":{const{params:n,parentSchema:f}=e;const{limit:l}=n;return`${s} should not have more than ${l} items${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"maxProperties":{const{params:n,parentSchema:f}=e;const{limit:l}=n;return`${s} should not have more than ${l} properties${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"uniqueItems":{const{params:n,parentSchema:f}=e;const{i:l}=n;return`${s} should not contain the item '${e.data[l]}' twice${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"additionalItems":{const{params:n,parentSchema:f}=e;const{limit:l}=n;return`${s} should not have more than ${l} items${getSchemaNonTypes(f)}. These items are valid:\n${this.getSchemaPartText(f)}`}case"contains":{const{parentSchema:n}=e;return`${s} should contains at least one ${this.getSchemaPartText(n,["contains"])} item${getSchemaNonTypes(n)}.`}case"required":{const{parentSchema:n,params:f}=e;const l=f.missingProperty.replace(/^\./,"");const v=n&&Boolean(n.properties&&n.properties[l]);return`${s} misses the property '${l}'${getSchemaNonTypes(n)}.${v?` Should be:\n${this.getSchemaPartText(n,["properties",l])}`:this.getSchemaPartDescription(n)}`}case"additionalProperties":{const{params:n,parentSchema:f}=e;const{additionalProperty:l}=n;return`${s} has an unknown property '${l}'${getSchemaNonTypes(f)}. These properties are valid:\n${this.getSchemaPartText(f)}`}case"dependencies":{const{params:n,parentSchema:f}=e;const{property:l,deps:v}=n;const r=v.split(",").map(e=>`'${e.trim()}'`).join(", ");return`${s} should have properties ${r} when property '${l}' is present${getSchemaNonTypes(f)}.${this.getSchemaPartDescription(f)}`}case"propertyNames":{const{params:n,parentSchema:f,schema:l}=e;const{propertyName:v}=n;return`${s} property name '${v}' is invalid${getSchemaNonTypes(f)}. Property names should be match format ${JSON.stringify(l.format)}.${this.getSchemaPartDescription(f)}`}case"enum":{const{parentSchema:n}=e;if(n&&n.enum&&n.enum.length===1){return`${s} should be ${this.getSchemaPartText(n,false,true)}`}return`${s} should be one of these:\n${this.getSchemaPartText(n)}`}case"const":{const{parentSchema:n}=e;return`${s} should be equal to constant ${this.getSchemaPartText(n,false,true)}`}case"not":{const n=likeObject(e.parentSchema)?`\n${this.getSchemaPartText(e.parentSchema)}`:"";const f=this.getSchemaPartText(e.schema,false,false,false);if(canApplyNot(e.schema)){return`${s} should be any ${f}${n}.`}const{schema:l,parentSchema:v}=e;return`${s} should not be ${this.getSchemaPartText(l,false,true)}${v&&likeObject(v)?`\n${this.getSchemaPartText(v)}`:""}`}case"oneOf":case"anyOf":{const{parentSchema:n,children:f}=e;if(f&&f.length>0){if(e.schema.length===1){const e=f[f.length-1];const s=f.slice(0,f.length-1);return this.formatValidationError(Object.assign({},e,{children:s,parentSchema:Object.assign({},n,e.parentSchema)}))}let l=filterChildren(f);if(l.length===1){return this.formatValidationError(l[0])}l=groupChildrenByFirstChild(l);return`${s} should be one of these:\n${this.getSchemaPartText(n)}\nDetails:\n${l.map(e=>` * ${indent(this.formatValidationError(e)," ")}`).join("\n")}`}return`${s} should be one of these:\n${this.getSchemaPartText(n)}`}case"if":{const{params:n,parentSchema:f}=e;const{failingKeyword:l}=n;return`${s} should match "${l}" schema:\n${this.getSchemaPartText(f,[l])}`}case"absolutePath":{const{message:n,parentSchema:f}=e;return`${s}: ${n}${this.getSchemaPartDescription(f)}`}default:{const{message:n,parentSchema:f}=e;const l=JSON.stringify(e,null,2);return`${s} ${n} (${l}).\n${this.getSchemaPartText(f,false)}`}}}formatValidationErrors(e){return e.map(e=>{let n=this.formatValidationError(e);if(this.postFormatter){n=this.postFormatter(n,e)}return` - ${indent(n," ")}`}).join("\n")}}var r=ValidationError;n.default=r},9839:(e,n,f)=>{"use strict";const{validate:s,ValidationError:l}=f(1299);e.exports={validate:s,ValidationError:l}},9884:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:true});n.default=void 0;function errorMessage(e,n,f){return{dataPath:undefined,schemaPath:undefined,keyword:"absolutePath",params:{absolutePath:f},message:e,parentSchema:n}}function getErrorFor(e,n,f){const s=e?`The provided value ${JSON.stringify(f)} is not an absolute path!`:`A relative path is expected. However, the provided value ${JSON.stringify(f)} is an absolute path!`;return errorMessage(s,n,f)}function addAbsolutePathKeyword(e){e.addKeyword("absolutePath",{errors:true,type:"string",compile(e,n){const f=s=>{let l=true;const v=s.includes("!");if(v){f.errors=[errorMessage(`The provided value ${JSON.stringify(s)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`,n,s)];l=false}const r=e===/^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(s);if(!r){f.errors=[getErrorFor(e,n,s)];l=false}return l};f.errors=[];return f}});return e}var f=addAbsolutePathKeyword;n.default=f},2735:e=>{"use strict";class Range{static getOperator(e,n){if(e==="left"){return n?">":">="}return n?"<":"<="}static formatRight(e,n,f){if(n===false){return Range.formatLeft(e,!n,!f)}return`should be ${Range.getOperator("right",f)} ${e}`}static formatLeft(e,n,f){if(n===false){return Range.formatRight(e,!n,!f)}return`should be ${Range.getOperator("left",f)} ${e}`}static formatRange(e,n,f,s,l){let v="should be";v+=` ${Range.getOperator(l?"left":"right",l?f:!f)} ${e} `;v+=l?"and":"or";v+=` ${Range.getOperator(l?"right":"left",l?s:!s)} ${n}`;return v}static getRangeValue(e,n){let f=n?Infinity:-Infinity;let s=-1;const l=n?([e])=>e<=f:([e])=>e>=f;for(let n=0;n-1){return e[s]}return[Infinity,true]}constructor(){this._left=[];this._right=[]}left(e,n=false){this._left.push([e,n])}right(e,n=false){this._right.push([e,n])}format(e=true){const[n,f]=Range.getRangeValue(this._left,e);const[s,l]=Range.getRangeValue(this._right,!e);if(!Number.isFinite(n)&&!Number.isFinite(s)){return""}const v=f?n+1:n;const r=l?s-1:s;if(v===r){return`should be ${e?"":"!"}= ${v}`}if(Number.isFinite(n)&&!Number.isFinite(s)){return Range.formatLeft(n,e,f)}if(!Number.isFinite(n)&&Number.isFinite(s)){return Range.formatRight(s,e,l)}return Range.formatRange(n,s,f,l,e)}}e.exports=Range},4226:(e,n,f)=>{"use strict";const s=f(2735);e.exports.stringHints=function stringHints(e,n){const f=[];let s="string";const l={...e};if(!n){const e=l.minLength;const n=l.formatMinimum;const f=l.formatExclusiveMaximum;l.minLength=l.maxLength;l.maxLength=e;l.formatMinimum=l.formatMaximum;l.formatMaximum=n;l.formatExclusiveMaximum=!l.formatExclusiveMinimum;l.formatExclusiveMinimum=!f}if(typeof l.minLength==="number"){if(l.minLength===1){s="non-empty string"}else{const e=Math.max(l.minLength-1,0);f.push(`should be longer than ${e} character${e>1?"s":""}`)}}if(typeof l.maxLength==="number"){if(l.maxLength===0){s="empty string"}else{const e=l.maxLength+1;f.push(`should be shorter than ${e} character${e>1?"s":""}`)}}if(l.pattern){f.push(`should${n?"":" not"} match pattern ${JSON.stringify(l.pattern)}`)}if(l.format){f.push(`should${n?"":" not"} match format ${JSON.stringify(l.format)}`)}if(l.formatMinimum){f.push(`should be ${l.formatExclusiveMinimum?">":">="} ${JSON.stringify(l.formatMinimum)}`)}if(l.formatMaximum){f.push(`should be ${l.formatExclusiveMaximum?"<":"<="} ${JSON.stringify(l.formatMaximum)}`)}return[s].concat(f)};e.exports.numberHints=function numberHints(e,n){const f=[e.type==="integer"?"integer":"number"];const l=new s;if(typeof e.minimum==="number"){l.left(e.minimum)}if(typeof e.exclusiveMinimum==="number"){l.left(e.exclusiveMinimum,true)}if(typeof e.maximum==="number"){l.right(e.maximum)}if(typeof e.exclusiveMaximum==="number"){l.right(e.exclusiveMaximum,true)}const v=l.format(n);if(v){f.push(v)}if(typeof e.multipleOf==="number"){f.push(`should${n?"":" not"} be multiple of ${e.multipleOf}`)}return f}},1299:(e,n,f)=>{"use strict";Object.defineProperty(n,"__esModule",{value:true});n.validate=validate;Object.defineProperty(n,"ValidationError",{enumerable:true,get:function(){return l.default}});var s=_interopRequireDefault(f(9884));var l=_interopRequireDefault(f(3427));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const v=f(1414);const r=f(2133);const g=new v({allErrors:true,verbose:true,$data:true});r(g,["instanceof","formatMinimum","formatMaximum","patternRequired"]);(0,s.default)(g);function validate(e,n,f){let s=[];if(Array.isArray(n)){s=Array.from(n,n=>validateObject(e,n));s.forEach((e,n)=>{const f=e=>{e.dataPath=`[${n}]${e.dataPath}`;if(e.children){e.children.forEach(f)}};e.forEach(f)});s=s.reduce((e,n)=>{e.push(...n);return e},[])}else{s=validateObject(e,n)}if(s.length>0){throw new l.default(s,e,f)}}function validateObject(e,n){const f=g.compile(e);const s=f(n);if(s)return[];return f.errors?filterErrors(f.errors):[]}function filterErrors(e){let n=[];for(const f of e){const{dataPath:e}=f;let s=[];n=n.filter(n=>{if(n.dataPath.includes(e)){if(n.children){s=s.concat(n.children.slice(0))}n.children=undefined;s.push(n);return false}return true});if(s.length){f.children=s}n.push(f)}return n}},4007:function(e,n){(function(e,f){true?f(n):0})(this,function(e){"use strict";function merge(){for(var e=arguments.length,n=Array(e),f=0;f1){n[0]=n[0].slice(0,-1);var s=n.length-1;for(var l=1;l= 0x80 (not a basic code point)","invalid-input":"Invalid input"};var a=r-g;var z=Math.floor;var x=String.fromCharCode;function error$1(e){throw new RangeError(N[e])}function map(e,n){var f=[];var s=e.length;while(s--){f[s]=n(e[s])}return f}function mapDomain(e,n){var f=e.split("@");var s="";if(f.length>1){s=f[0]+"@";e=f[1]}e=e.replace(A,".");var l=e.split(".");var v=map(l,n).join(".");return s+v}function ucs2decode(e){var n=[];var f=0;var s=e.length;while(f=55296&&l<=56319&&f>1;e+=z(e/n);for(;e>a*b>>1;s+=r){e=z(e/a)}return z(s+(a+1)*e/(e+p))};var I=function decode(e){var n=[];var f=e.length;var s=0;var l=j;var p=R;var d=e.lastIndexOf(w);if(d<0){d=0}for(var F=0;F=128){error$1("not-basic")}n.push(e.charCodeAt(F))}for(var E=d>0?d+1:0;E=f){error$1("invalid-input")}var x=q(e.charCodeAt(E++));if(x>=r||x>z((v-s)/N)){error$1("overflow")}s+=x*N;var O=a<=p?g:a>=p+b?b:a-p;if(xz(v/Q)){error$1("overflow")}N*=Q}var I=n.length+1;p=U(s-A,I,A==0);if(z(s/I)>v-l){error$1("overflow")}l+=z(s/I);s%=I;n.splice(s++,0,l)}return String.fromCodePoint.apply(String,n)};var T=function encode(e){var n=[];e=ucs2decode(e);var f=e.length;var s=j;var l=0;var p=R;var d=true;var F=false;var E=undefined;try{for(var A=e[Symbol.iterator](),N;!(d=(N=A.next()).done);d=true){var a=N.value;if(a<128){n.push(x(a))}}}catch(e){F=true;E=e}finally{try{if(!d&&A.return){A.return()}}finally{if(F){throw E}}}var O=n.length;var q=O;if(O){n.push(w)}while(q=s&&Hz((v-l)/G)){error$1("overflow")}l+=(I-s)*G;s=I;var Y=true;var W=false;var X=undefined;try{for(var c=e[Symbol.iterator](),B;!(Y=(B=c.next()).done);Y=true){var Z=B.value;if(Zv){error$1("overflow")}if(Z==s){var y=l;for(var D=r;;D+=r){var K=D<=p?g:D>=p+b?b:D-p;if(y>6|192).toString(16).toUpperCase()+"%"+(n&63|128).toString(16).toUpperCase();else f="%"+(n>>12|224).toString(16).toUpperCase()+"%"+(n>>6&63|128).toString(16).toUpperCase()+"%"+(n&63|128).toString(16).toUpperCase();return f}function pctDecChars(e){var n="";var f=0;var s=e.length;while(f=194&&l<224){if(s-f>=6){var v=parseInt(e.substr(f+4,2),16);n+=String.fromCharCode((l&31)<<6|v&63)}else{n+=e.substr(f,6)}f+=6}else if(l>=224){if(s-f>=9){var r=parseInt(e.substr(f+4,2),16);var g=parseInt(e.substr(f+7,2),16);n+=String.fromCharCode((l&15)<<12|(r&63)<<6|g&63)}else{n+=e.substr(f,9)}f+=9}else{n+=e.substr(f,3);f+=3}}return n}function _normalizeComponentEncoding(e,n){function decodeUnreserved(e){var f=pctDecChars(e);return!f.match(n.UNRESERVED)?e:f}if(e.scheme)e.scheme=String(e.scheme).replace(n.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(n.NOT_SCHEME,"");if(e.userinfo!==undefined)e.userinfo=String(e.userinfo).replace(n.PCT_ENCODED,decodeUnreserved).replace(n.NOT_USERINFO,pctEncChar).replace(n.PCT_ENCODED,toUpperCase);if(e.host!==undefined)e.host=String(e.host).replace(n.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(n.NOT_HOST,pctEncChar).replace(n.PCT_ENCODED,toUpperCase);if(e.path!==undefined)e.path=String(e.path).replace(n.PCT_ENCODED,decodeUnreserved).replace(e.scheme?n.NOT_PATH:n.NOT_PATH_NOSCHEME,pctEncChar).replace(n.PCT_ENCODED,toUpperCase);if(e.query!==undefined)e.query=String(e.query).replace(n.PCT_ENCODED,decodeUnreserved).replace(n.NOT_QUERY,pctEncChar).replace(n.PCT_ENCODED,toUpperCase);if(e.fragment!==undefined)e.fragment=String(e.fragment).replace(n.PCT_ENCODED,decodeUnreserved).replace(n.NOT_FRAGMENT,pctEncChar).replace(n.PCT_ENCODED,toUpperCase);return e}function _stripLeadingZeros(e){return e.replace(/^0*(.*)/,"$1")||"0"}function _normalizeIPv4(e,n){var f=e.match(n.IPV4ADDRESS)||[];var l=s(f,2),v=l[1];if(v){return v.split(".").map(_stripLeadingZeros).join(".")}else{return e}}function _normalizeIPv6(e,n){var f=e.match(n.IPV6ADDRESS)||[];var l=s(f,3),v=l[1],r=l[2];if(v){var g=v.toLowerCase().split("::").reverse(),b=s(g,2),p=b[0],d=b[1];var R=d?d.split(":").map(_stripLeadingZeros):[];var j=p.split(":").map(_stripLeadingZeros);var w=n.IPV4ADDRESS.test(j[j.length-1]);var F=w?7:8;var E=j.length-F;var A=Array(F);for(var N=0;N1){var O=A.slice(0,z.index);var q=A.slice(z.index+z.length);x=O.join(":")+"::"+q.join(":")}else{x=A.join(":")}if(r){x+="%"+r}return x}else{return e}}var H=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;var G="".match(/(){0}/)[1]===undefined;function parse(e){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l={};var v=s.iri!==false?f:n;if(s.reference==="suffix")e=(s.scheme?s.scheme+":":"")+"//"+e;var r=e.match(H);if(r){if(G){l.scheme=r[1];l.userinfo=r[3];l.host=r[4];l.port=parseInt(r[5],10);l.path=r[6]||"";l.query=r[7];l.fragment=r[8];if(isNaN(l.port)){l.port=r[5]}}else{l.scheme=r[1]||undefined;l.userinfo=e.indexOf("@")!==-1?r[3]:undefined;l.host=e.indexOf("//")!==-1?r[4]:undefined;l.port=parseInt(r[5],10);l.path=r[6]||"";l.query=e.indexOf("?")!==-1?r[7]:undefined;l.fragment=e.indexOf("#")!==-1?r[8]:undefined;if(isNaN(l.port)){l.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?r[4]:undefined}}if(l.host){l.host=_normalizeIPv6(_normalizeIPv4(l.host,v),v)}if(l.scheme===undefined&&l.userinfo===undefined&&l.host===undefined&&l.port===undefined&&!l.path&&l.query===undefined){l.reference="same-document"}else if(l.scheme===undefined){l.reference="relative"}else if(l.fragment===undefined){l.reference="absolute"}else{l.reference="uri"}if(s.reference&&s.reference!=="suffix"&&s.reference!==l.reference){l.error=l.error||"URI is not a "+s.reference+" reference."}var g=C[(s.scheme||l.scheme||"").toLowerCase()];if(!s.unicodeSupport&&(!g||!g.unicodeSupport)){if(l.host&&(s.domainHost||g&&g.domainHost)){try{l.host=M.toASCII(l.host.replace(v.PCT_ENCODED,pctDecChars).toLowerCase())}catch(e){l.error=l.error||"Host's domain name can not be converted to ASCII via punycode: "+e}}_normalizeComponentEncoding(l,n)}else{_normalizeComponentEncoding(l,v)}if(g&&g.parse){g.parse(l,s)}}else{l.error=l.error||"URI can not be parsed."}return l}function _recomposeAuthority(e,s){var l=s.iri!==false?f:n;var v=[];if(e.userinfo!==undefined){v.push(e.userinfo);v.push("@")}if(e.host!==undefined){v.push(_normalizeIPv6(_normalizeIPv4(String(e.host),l),l).replace(l.IPV6ADDRESS,function(e,n,f){return"["+n+(f?"%25"+f:"")+"]"}))}if(typeof e.port==="number"){v.push(":");v.push(e.port.toString(10))}return v.length?v.join(""):undefined}var Y=/^\.\.?\//;var W=/^\/\.(\/|$)/;var X=/^\/\.\.(\/|$)/;var c=/^\/?(?:.|\n)*?(?=\/|$)/;function removeDotSegments(e){var n=[];while(e.length){if(e.match(Y)){e=e.replace(Y,"")}else if(e.match(W)){e=e.replace(W,"/")}else if(e.match(X)){e=e.replace(X,"/");n.pop()}else if(e==="."||e===".."){e=""}else{var f=e.match(c);if(f){var s=f[0];e=e.slice(s.length);n.push(s)}else{throw new Error("Unexpected dot segment condition")}}}return n.join("")}function serialize(e){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l=s.iri?f:n;var v=[];var r=C[(s.scheme||e.scheme||"").toLowerCase()];if(r&&r.serialize)r.serialize(e,s);if(e.host){if(l.IPV6ADDRESS.test(e.host)){}else if(s.domainHost||r&&r.domainHost){try{e.host=!s.iri?M.toASCII(e.host.replace(l.PCT_ENCODED,pctDecChars).toLowerCase()):M.toUnicode(e.host)}catch(n){e.error=e.error||"Host's domain name can not be converted to "+(!s.iri?"ASCII":"Unicode")+" via punycode: "+n}}}_normalizeComponentEncoding(e,l);if(s.reference!=="suffix"&&e.scheme){v.push(e.scheme);v.push(":")}var g=_recomposeAuthority(e,s);if(g!==undefined){if(s.reference!=="suffix"){v.push("//")}v.push(g);if(e.path&&e.path.charAt(0)!=="/"){v.push("/")}}if(e.path!==undefined){var b=e.path;if(!s.absolutePath&&(!r||!r.absolutePath)){b=removeDotSegments(b)}if(g===undefined){b=b.replace(/^\/\//,"/%2F")}v.push(b)}if(e.query!==undefined){v.push("?");v.push(e.query)}if(e.fragment!==undefined){v.push("#");v.push(e.fragment)}return v.join("")}function resolveComponents(e,n){var f=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var s=arguments[3];var l={};if(!s){e=parse(serialize(e,f),f);n=parse(serialize(n,f),f)}f=f||{};if(!f.tolerant&&n.scheme){l.scheme=n.scheme;l.userinfo=n.userinfo;l.host=n.host;l.port=n.port;l.path=removeDotSegments(n.path||"");l.query=n.query}else{if(n.userinfo!==undefined||n.host!==undefined||n.port!==undefined){l.userinfo=n.userinfo;l.host=n.host;l.port=n.port;l.path=removeDotSegments(n.path||"");l.query=n.query}else{if(!n.path){l.path=e.path;if(n.query!==undefined){l.query=n.query}else{l.query=e.query}}else{if(n.path.charAt(0)==="/"){l.path=removeDotSegments(n.path)}else{if((e.userinfo!==undefined||e.host!==undefined||e.port!==undefined)&&!e.path){l.path="/"+n.path}else if(!e.path){l.path=n.path}else{l.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+n.path}l.path=removeDotSegments(l.path)}l.query=n.query}l.userinfo=e.userinfo;l.host=e.host;l.port=e.port}l.scheme=e.scheme}l.fragment=n.fragment;return l}function resolve(e,n,f){var s=assign({scheme:"null"},f);return serialize(resolveComponents(parse(e,s),parse(n,s),s,true),s)}function normalize(e,n){if(typeof e==="string"){e=serialize(parse(e,n),n)}else if(typeOf(e)==="object"){e=parse(serialize(e,n),n)}return e}function equal(e,n,f){if(typeof e==="string"){e=serialize(parse(e,f),f)}else if(typeOf(e)==="object"){e=serialize(e,f)}if(typeof n==="string"){n=serialize(parse(n,f),f)}else if(typeOf(n)==="object"){n=serialize(n,f)}return e===n}function escapeComponent(e,s){return e&&e.toString().replace(!s||!s.iri?n.ESCAPE:f.ESCAPE,pctEncChar)}function unescapeComponent(e,s){return e&&e.toString().replace(!s||!s.iri?n.PCT_ENCODED:f.PCT_ENCODED,pctDecChars)}var B={scheme:"http",domainHost:true,parse:function parse(e,n){if(!e.host){e.error=e.error||"HTTP URIs must have a host."}return e},serialize:function serialize(e,n){if(e.port===(String(e.scheme).toLowerCase()!=="https"?80:443)||e.port===""){e.port=undefined}if(!e.path){e.path="/"}return e}};var Z={scheme:"https",domainHost:B.domainHost,parse:B.parse,serialize:B.serialize};var y={};var D=true;var K="[A-Za-z0-9\\-\\.\\_\\~"+(D?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]";var m="[0-9A-Fa-f]";var V=subexp(subexp("%[EFef]"+m+"%"+m+m+"%"+m+m)+"|"+subexp("%[89A-Fa-f]"+m+"%"+m+m)+"|"+subexp("%"+m+m));var k="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";var h="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";var S=merge(h,'[\\"\\\\]');var P="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";var i=new RegExp(K,"g");var _=new RegExp(V,"g");var u=new RegExp(merge("[^]",k,"[\\.]",'[\\"]',S),"g");var o=new RegExp(merge("[^]",K,P),"g");var $=o;function decodeUnreserved(e){var n=pctDecChars(e);return!n.match(i)?e:n}var t={scheme:"mailto",parse:function parse$$1(e,n){var f=e;var s=f.to=f.path?f.path.split(","):[];f.path=undefined;if(f.query){var l=false;var v={};var r=f.query.split("&");for(var g=0,b=r.length;g{var n={664:function(n,e){(function(n,f){"use strict";true?f(e):0})(this,function(n){"use strict";var e=function noop(){};var f=function throwError(){throw new Error("Callback was already called.")};var r=5;var t=0;var u="object";var a="function";var o=Array.isArray;var l=Object.keys;var i=Array.prototype.push;var s=typeof Symbol===a&&Symbol.iterator;var h,y,c;createImmediate();var v=createEach(arrayEach,baseEach,symbolEach);var I=createMap(arrayEachIndex,baseEachIndex,symbolEachIndex,true);var p=createMap(arrayEachIndex,baseEachKey,symbolEachKey,false);var d=createFilter(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue,true);var g=createFilterSeries(true);var m=createFilterLimit(true);var W=createFilter(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue,false);var C=createFilterSeries(false);var j=createFilterLimit(false);var b=createDetect(arrayEachValue,baseEachValue,symbolEachValue,true);var w=createDetectSeries(true);var K=createDetectLimit(true);var L=createEvery(arrayEachValue,baseEachValue,symbolEachValue);var _=createEverySeries();var A=createEveryLimit();var O=createPick(arrayEachIndexValue,baseEachKeyValue,symbolEachKeyValue,true);var S=createPickSeries(true);var B=createPickLimit(true);var V=createPick(arrayEachIndexValue,baseEachKeyValue,symbolEachKeyValue,false);var E=createPickSeries(false);var D=createPickLimit(false);var N=createTransform(arrayEachResult,baseEachResult,symbolEachResult);var R=createSortBy(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue);var q=createConcat(arrayEachIndex,baseEachIndex,symbolEachIndex);var F=createGroupBy(arrayEachValue,baseEachValue,symbolEachValue);var P=createParallel(arrayEachFunc,baseEachFunc);var x=createApplyEach(I);var Q=createApplyEach(mapSeries);var M=createLogger("log");var J=createLogger("dir");var $={VERSION:"2.6.2",each:v,eachSeries:eachSeries,eachLimit:eachLimit,forEach:v,forEachSeries:eachSeries,forEachLimit:eachLimit,eachOf:v,eachOfSeries:eachSeries,eachOfLimit:eachLimit,forEachOf:v,forEachOfSeries:eachSeries,forEachOfLimit:eachLimit,map:I,mapSeries:mapSeries,mapLimit:mapLimit,mapValues:p,mapValuesSeries:mapValuesSeries,mapValuesLimit:mapValuesLimit,filter:d,filterSeries:g,filterLimit:m,select:d,selectSeries:g,selectLimit:m,reject:W,rejectSeries:C,rejectLimit:j,detect:b,detectSeries:w,detectLimit:K,find:b,findSeries:w,findLimit:K,pick:O,pickSeries:S,pickLimit:B,omit:V,omitSeries:E,omitLimit:D,reduce:reduce,inject:reduce,foldl:reduce,reduceRight:reduceRight,foldr:reduceRight,transform:N,transformSeries:transformSeries,transformLimit:transformLimit,sortBy:R,sortBySeries:sortBySeries,sortByLimit:sortByLimit,some:some,someSeries:someSeries,someLimit:someLimit,any:some,anySeries:someSeries,anyLimit:someLimit,every:L,everySeries:_,everyLimit:A,all:L,allSeries:_,allLimit:A,concat:q,concatSeries:concatSeries,concatLimit:concatLimit,groupBy:F,groupBySeries:groupBySeries,groupByLimit:groupByLimit,parallel:P,series:series,parallelLimit:parallelLimit,tryEach:tryEach,waterfall:waterfall,angelFall:angelFall,angelfall:angelFall,whilst:whilst,doWhilst:doWhilst,until:until,doUntil:doUntil,during:during,doDuring:doDuring,forever:forever,compose:compose,seq:seq,applyEach:x,applyEachSeries:Q,queue:queue,priorityQueue:priorityQueue,cargo:cargo,auto:auto,autoInject:autoInject,retry:retry,retryable:retryable,iterator:iterator,times:times,timesSeries:timesSeries,timesLimit:timesLimit,race:race,apply:apply,nextTick:y,setImmediate:c,memoize:memoize,unmemoize:unmemoize,ensureAsync:ensureAsync,constant:constant,asyncify:asyncify,wrapSync:asyncify,log:M,dir:J,reflect:reflect,reflectAll:reflectAll,timeout:timeout,createLogger:createLogger,safe:safe,fast:fast};n["default"]=$;baseEachSync($,function(e,f){n[f]=e},l($));function createImmediate(n){var e=function delay(n){var e=slice(arguments,1);setTimeout(function(){n.apply(null,e)})};c=typeof setImmediate===a?setImmediate:e;if(typeof process===u&&typeof process.nextTick===a){h=/^v0.10/.test(process.version)?c:process.nextTick;y=/^v0/.test(process.version)?c:process.nextTick}else{y=h=c}if(n===false){h=function(n){n()}}}function createArray(n){var e=-1;var f=n.length;var r=Array(f);while(++e=e&&n[a]>=r){a--}if(u>a){break}swap(n,t,u++,a--)}return u}function swap(n,e,f,r){var t=n[f];n[f]=n[r];n[r]=t;var u=e[f];e[f]=e[r];e[r]=u}function quickSort(n,e,f,r){if(e===f){return}var t=e;while(++t<=f&&n[e]===n[t]){var u=t-1;if(r[u]>r[t]){var a=r[u];r[u]=r[t];r[t]=a}}if(t>f){return}var o=n[e]>n[t]?e:t;t=partition(n,e,f,n[o],r);quickSort(n,e,t-1,r);quickSort(n,t,f,r)}function makeConcatResult(n){var f=[];arrayEachSync(n,function(n){if(n===e){return}if(o(n)){i.apply(f,n)}else{f.push(n)}});return f}function arrayEach(n,e,f){var r=-1;var t=n.length;if(e.length===3){while(++ry?y:t,m);function arrayIterator(){c=j++;if(ci?i:r,d);function arrayIterator(){if(mi?i:r,g);function arrayIterator(){y=W++;if(yi?i:r,d);function arrayIterator(){y=W++;if(yy?y:t,m);function arrayIterator(){c=C++;if(cy?y:t,m);function arrayIterator(){c=j++;if(ci?i:f,d);function arrayIterator(){y=W++;if(yi?i:r,W);function arrayIterator(){if(j=2){i.apply(g,slice(arguments,1))}if(n){t(n,g)}else if(++m===a){p=f;t(null,g)}else if(d){h(p)}else{d=true;p()}d=false}}function concatLimit(n,r,t,a){a=a||e;var i,y,c,v,I,p;var d=false;var g=0;var m=0;if(o(n)){i=n.length;I=t.length===3?arrayIteratorWithIndex:arrayIterator}else if(!n){}else if(s&&n[s]){i=Infinity;p=[];c=n[s]();I=t.length===3?symbolIteratorWithKey:symbolIterator}else if(typeof n===u){var W=l(n);i=W.length;I=t.length===3?objectIteratorWithKey:objectIterator}if(!i||isNaN(r)||r<1){return a(null,[])}p=p||Array(i);timesSync(r>i?i:r,I);function arrayIterator(){if(gi?i:r,g);function arrayIterator(){if(Wa?a:r,v);function arrayIterator(){i=p++;if(i1){var t=slice(arguments,1);return r.apply(this,t)}else{return r}}}function DLL(){this.head=null;this.tail=null;this.length=0}DLL.prototype._removeLink=function(n){var e=n.prev;var f=n.next;if(e){e.next=f}else{this.head=f}if(f){f.prev=e}else{this.tail=e}n.prev=null;n.next=null;this.length--;return n};DLL.prototype.empty=DLL;DLL.prototype._setInitial=function(n){this.length=1;this.head=this.tail=n};DLL.prototype.insertBefore=function(n,e){e.prev=n.prev;e.next=n;if(n.prev){n.prev.next=e}else{this.head=e}n.prev=e;this.length++};DLL.prototype.unshift=function(n){if(this.head){this.insertBefore(this.head,n)}else{this._setInitial(n)}};DLL.prototype.push=function(n){var e=this.tail;if(e){n.prev=e;n.next=e.next;this.tail=n;e.next=n;this.length++}else{this._setInitial(n)}};DLL.prototype.shift=function(){return this.head&&this._removeLink(this.head)};DLL.prototype.splice=function(n){var e;var f=[];while(n--&&(e=this.shift())){f.push(e)}return f};DLL.prototype.remove=function(n){var e=this.head;while(e){if(n(e)){this._removeLink(e)}e=e.next}return this};function baseQueue(n,r,t,u){if(t===undefined){t=1}else if(isNaN(t)||t<1){throw new Error("Concurrency must not be zero")}var a=0;var l=[];var s,y;var c={_tasks:new DLL,concurrency:t,payload:u,saturated:e,unsaturated:e,buffer:t/4,empty:e,drain:e,error:e,started:false,paused:false,push:push,kill:kill,unshift:unshift,remove:remove,process:n?runQueue:runCargo,length:getLength,running:running,workersList:getWorkersList,idle:idle,pause:pause,resume:resume,_worker:r};return c;function push(n,e){_insert(n,e)}function unshift(n,e){_insert(n,e,true)}function _exec(n){var e={data:n,callback:s};if(y){c._tasks.unshift(e)}else{c._tasks.push(e)}h(c.process)}function _insert(n,f,r){if(f==null){f=e}else if(typeof f!=="function"){throw new Error("task callback must be a function")}c.started=true;var t=o(n)?n:[n];if(n===undefined||!t.length){if(c.idle()){h(c.drain)}return}y=r;s=f;arrayEachSync(t,_exec);s=undefined}function kill(){c.drain=e;c._tasks.empty()}function _next(n,e){var r=false;return function done(t,u){if(r){f()}r=true;a--;var o;var i=-1;var s=l.length;var h=-1;var y=e.length;var c=arguments.length>2;var v=c&&createArray(arguments);while(++h=i.priority){i=i.next}while(l--){var s={data:u[l],priority:f,callback:t};if(i){r._tasks.insertBefore(i,s)}else{r._tasks.push(s)}h(r.process)}}}function cargo(n,e){return baseQueue(false,n,1,e)}function auto(n,r,t){if(typeof r===a){t=r;r=null}var u=l(n);var i=u.length;var s={};if(i===0){return t(null,s)}var h=0;var y=new DLL;var c=Object.create(null);t=onlyOnce(t||e);r=r||i;baseEachSync(n,iterator,u);proceedQueue();function iterator(n,r){var a,l;if(!o(n)){a=n;l=0;y.push([a,l,done]);return}var v=n.length-1;a=n[v];l=v;if(v===0){y.push([a,l,done]);return}var I=-1;while(++I=n){t(null,u);t=f}else if(a){h(iterate)}else{a=true;iterate()}a=false}}function timesLimit(n,r,t,u){u=u||e;n=+n;if(isNaN(n)||n<1||isNaN(r)||r<1){return u(null,[])}var a=Array(n);var o=false;var l=0;var i=0;timesSync(r>n?n:r,iterate);function iterate(){var e=l++;if(e=n){u(null,a);u=f}else if(o){h(iterate)}else{o=true;iterate()}o=false}}}function race(n,f){f=once(f||e);var r,t;var a=-1;if(o(n)){r=n.length;while(++a2){f=slice(arguments,1)}e(null,{value:f})}}}function reflectAll(n){var e,f;if(o(n)){e=Array(n.length);arrayEachSync(n,iterate)}else if(n&&typeof n===u){f=l(n);e={};baseEachSync(n,iterate,f)}return e;function iterate(n,f){e[f]=reflect(n)}}function createLogger(n){return function(n){var e=slice(arguments,1);e.push(done);n.apply(null,e)};function done(e){if(typeof console===u){if(e){if(console.error){console.error(e)}return}if(console[n]){var f=slice(arguments,1);arrayEachSync(f,function(e){console[n](e)})}}}}function safe(){createImmediate();return n}function fast(){createImmediate(false);return n}})},536:(n,e,f)=>{"use strict";n.exports=f(664).queue},111:(n,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:true});e.default=readBuffer;function readBuffer(n,e,f){if(e===0){f(null,Buffer.alloc(0));return}let r=e;const t=[];const u=()=>{const u=a=>{let o=a;let l;if(o.length>r){l=o.slice(r);o=o.slice(0,r);r=0}else{r-=o.length}t.push(o);if(r===0){n.removeListener("data",u);n.pause();if(l){n.unshift(l)}f(null,Buffer.concat(t,e))}};n.on("data",u);n.resume()};u()}},745:(n,e,f)=>{"use strict";var r=f(747);var t=_interopRequireDefault(r);var u=f(282);var a=_interopRequireDefault(u);var o=f(811);var l=_interopRequireDefault(o);var i=f(536);var s=_interopRequireDefault(i);var h=f(111);var y=_interopRequireDefault(h);function _interopRequireDefault(n){return n&&n.__esModule?n:{default:n}}const c=t.default.createWriteStream(null,{fd:3});const v=t.default.createReadStream(null,{fd:4});c.on("finish",onTerminateWrite);v.on("end",onTerminateRead);c.on("close",onTerminateWrite);v.on("close",onTerminateRead);v.on("error",onError);c.on("error",onError);const I=+process.argv[2]||20;let p=false;let d=0;const g=Object.create(null);function onError(n){console.error(n)}function onTerminateRead(){terminateRead()}function onTerminateWrite(){terminateWrite()}function writePipeWrite(...n){if(!p){c.write(...n)}}function writePipeCork(){if(!p){c.cork()}}function writePipeUncork(){if(!p){c.uncork()}}function terminateRead(){p=true;v.removeAllListeners()}function terminateWrite(){p=true;c.removeAllListeners()}function terminate(){terminateRead();terminateWrite()}function toErrorObj(n){return{message:n.message,details:n.details,stack:n.stack,hideStack:n.hideStack}}function toNativeError(n){if(!n)return null;const e=new Error(n.message);e.details=n.details;e.missing=n.missing;return e}function writeJson(n){writePipeCork();process.nextTick(()=>{writePipeUncork()});const e=Buffer.alloc(4);const f=Buffer.from(JSON.stringify(n),"utf-8");e.writeInt32BE(f.length,0);writePipeWrite(e);writePipeWrite(f)}const m=(0,s.default)(({id:n,data:e},f)=>{try{l.default.runLoaders({loaders:e.loaders,resource:e.resource,readResource:t.default.readFile.bind(t.default),context:{version:2,resolve:(e,f,r)=>{g[d]=r;writeJson({type:"resolve",id:n,questionId:d,context:e,request:f});d+=1},emitWarning:e=>{writeJson({type:"emitWarning",id:n,data:toErrorObj(e)})},emitError:e=>{writeJson({type:"emitError",id:n,data:toErrorObj(e)})},exec:(n,e)=>{const f=new a.default(e,undefined);f.paths=a.default._nodeModulePaths(undefined.context);f.filename=e;f._compile(n,e);return f.exports},options:{context:e.optionsContext},webpack:true,"thread-loader":true,sourceMap:e.sourceMap,target:e.target,minimize:e.minimize,resourceQuery:e.resourceQuery}},(e,r)=>{const{result:t,cacheable:u,fileDependencies:a,contextDependencies:o}=r;const l=[];const i=Array.isArray(t)&&t.map(n=>{const e=Buffer.isBuffer(n);if(e){l.push(n);return{buffer:true}}if(typeof n==="string"){const e=Buffer.from(n,"utf-8");l.push(e);return{buffer:true,string:true}}return{data:n}});writeJson({type:"job",id:n,error:e&&toErrorObj(e),result:{result:i,cacheable:u,fileDependencies:a,contextDependencies:o},data:l.map(n=>n.length)});l.forEach(n=>{writePipeWrite(n)});setImmediate(f)})}catch(e){writeJson({type:"job",id:n,error:toErrorObj(e)});f()}},I);function dispose(){terminate();m.kill();process.exit(0)}function onMessage(n){try{const{type:e,id:f}=n;switch(e){case"job":{m.push(n);break}case"result":{const{error:e,result:r}=n;const t=g[f];if(t){const n=toNativeError(e);t(n,r)}else{console.error(`Worker got unexpected result id ${f}`)}delete g[f];break}case"warmup":{const{requires:e}=n;e.forEach(n=>require(n));break}default:{console.error(`Worker got unexpected job type ${e}`);break}}}catch(n){console.error(`Error in worker ${n}`)}}function readNextMessage(){(0,y.default)(v,4,(n,e)=>{if(n){console.error(`Failed to communicate with main process (read length) ${n}`);return}const f=e.length&&e.readInt32BE(0);if(f===0){dispose();return}(0,y.default)(v,f,(n,e)=>{if(p){return}if(n){console.error(`Failed to communicate with main process (read message) ${n}`);return}const f=e.toString("utf-8");const r=JSON.parse(f);onMessage(r);setImmediate(()=>readNextMessage())})})}readNextMessage()},747:n=>{"use strict";n.exports=require("fs")},811:n=>{"use strict";n.exports=require("loader-runner")},282:n=>{"use strict";n.exports=require("module")}};var e={};function __webpack_require__(f){if(e[f]){return e[f].exports}var r=e[f]={exports:{}};var t=true;try{n[f].call(r.exports,r,r.exports,__webpack_require__);t=false}finally{if(t)delete e[f]}return r.exports}__webpack_require__.ab=__dirname+"/";return __webpack_require__(745)})(); \ No newline at end of file +module.exports=(()=>{var e={736:e=>{"use strict";class LoadingLoaderError extends Error{constructor(e){super(e);this.name="LoaderRunnerError";Error.captureStackTrace(this,this.constructor)}}e.exports=LoadingLoaderError},278:(e,n,r)=>{var t=r(747);var f=t.readFile.bind(t);var u=r(384);function utf8BufferToString(e){var n=e.toString("utf-8");if(n.charCodeAt(0)===65279){return n.substr(1)}else{return n}}function splitQuery(e){var n=e.indexOf("?");if(n<0)return[e,""];return[e.substr(0,n),e.substr(n)]}function dirname(e){if(e==="/")return"/";var n=e.lastIndexOf("/");var r=e.lastIndexOf("\\");var t=e.indexOf("/");var f=e.indexOf("\\");var u=n>r?n:r;var a=n>r?t:f;if(u<0)return e;if(u===a)return e.substr(0,u+1);return e.substr(0,u)}function createLoaderObject(e){var n={path:null,query:null,options:null,ident:null,normal:null,pitch:null,raw:null,data:null,pitchExecuted:false,normalExecuted:false};Object.defineProperty(n,"request",{enumerable:true,get:function(){return n.path+n.query},set:function(e){if(typeof e==="string"){var r=splitQuery(e);n.path=r[0];n.query=r[1];n.options=undefined;n.ident=undefined}else{if(!e.loader)throw new Error("request should be a string or object with loader and object ("+JSON.stringify(e)+")");n.path=e.loader;n.options=e.options;n.ident=e.ident;if(n.options===null)n.query="";else if(n.options===undefined)n.query="";else if(typeof n.options==="string")n.query="?"+n.options;else if(n.ident)n.query="??"+n.ident;else if(typeof n.options==="object"&&n.options.ident)n.query="??"+n.options.ident;else n.query="?"+JSON.stringify(n.options)}}});n.request=e;if(Object.preventExtensions){Object.preventExtensions(n)}return n}function runSyncOrAsync(e,n,r,t){var f=true;var u=false;var a=false;var o=false;n.async=function async(){if(u){if(o)return;throw new Error("async(): The callback was already called.")}f=false;return i};var i=n.callback=function(){if(u){if(o)return;throw new Error("callback(): The callback was already called.")}u=true;f=false;try{t.apply(null,arguments)}catch(e){a=true;throw e}};try{var l=function LOADER_EXECUTION(){return e.apply(n,r)}();if(f){u=true;if(l===undefined)return t();if(l&&typeof l==="object"&&typeof l.then==="function"){return l.then(function(e){t(null,e)},t)}return t(null,l)}}catch(e){if(a)throw e;if(u){if(typeof e==="object"&&e.stack)console.error(e.stack);else console.error(e);return}u=true;o=true;t(e)}}function convertArgs(e,n){if(!n&&Buffer.isBuffer(e[0]))e[0]=utf8BufferToString(e[0]);else if(n&&typeof e[0]==="string")e[0]=new Buffer(e[0],"utf-8")}function iteratePitchingLoaders(e,n,r){if(n.loaderIndex>=n.loaders.length)return processResource(e,n,r);var t=n.loaders[n.loaderIndex];if(t.pitchExecuted){n.loaderIndex++;return iteratePitchingLoaders(e,n,r)}u(t,function(f){if(f){n.cacheable(false);return r(f)}var u=t.pitch;t.pitchExecuted=true;if(!u)return iteratePitchingLoaders(e,n,r);runSyncOrAsync(u,n,[n.remainingRequest,n.previousRequest,t.data={}],function(t){if(t)return r(t);var f=Array.prototype.slice.call(arguments,1);if(f.length>0){n.loaderIndex--;iterateNormalLoaders(e,n,f,r)}else{iteratePitchingLoaders(e,n,r)}})})}function processResource(e,n,r){n.loaderIndex=n.loaders.length-1;var t=n.resourcePath;if(t){n.addDependency(t);e.readResource(t,function(t,f){if(t)return r(t);e.resourceBuffer=f;iterateNormalLoaders(e,n,[f],r)})}else{iterateNormalLoaders(e,n,[null],r)}}function iterateNormalLoaders(e,n,r,t){if(n.loaderIndex<0)return t(null,r);var f=n.loaders[n.loaderIndex];if(f.normalExecuted){n.loaderIndex--;return iterateNormalLoaders(e,n,r,t)}var u=f.normal;f.normalExecuted=true;if(!u){return iterateNormalLoaders(e,n,r,t)}convertArgs(r,f.raw);runSyncOrAsync(u,n,r,function(r){if(r)return t(r);var f=Array.prototype.slice.call(arguments,1);iterateNormalLoaders(e,n,f,t)})}n.getContext=function getContext(e){var n=splitQuery(e);return dirname(n[0])};n.runLoaders=function runLoaders(e,n){var r=e.resource||"";var t=e.loaders||[];var u=e.context||{};var a=e.readResource||f;var o=r&&splitQuery(r);var i=o?o[0]:undefined;var l=o?o[1]:undefined;var s=i?dirname(i):null;var c=true;var h=[];var y=[];t=t.map(createLoaderObject);u.context=s;u.loaderIndex=0;u.loaders=t;u.resourcePath=i;u.resourceQuery=l;u.async=null;u.callback=null;u.cacheable=function cacheable(e){if(e===false){c=false}};u.dependency=u.addDependency=function addDependency(e){h.push(e)};u.addContextDependency=function addContextDependency(e){y.push(e)};u.getDependencies=function getDependencies(){return h.slice()};u.getContextDependencies=function getContextDependencies(){return y.slice()};u.clearDependencies=function clearDependencies(){h.length=0;y.length=0;c=true};Object.defineProperty(u,"resource",{enumerable:true,get:function(){if(u.resourcePath===undefined)return undefined;return u.resourcePath+u.resourceQuery},set:function(e){var n=e&&splitQuery(e);u.resourcePath=n?n[0]:undefined;u.resourceQuery=n?n[1]:undefined}});Object.defineProperty(u,"request",{enumerable:true,get:function(){return u.loaders.map(function(e){return e.request}).concat(u.resource||"").join("!")}});Object.defineProperty(u,"remainingRequest",{enumerable:true,get:function(){if(u.loaderIndex>=u.loaders.length-1&&!u.resource)return"";return u.loaders.slice(u.loaderIndex+1).map(function(e){return e.request}).concat(u.resource||"").join("!")}});Object.defineProperty(u,"currentRequest",{enumerable:true,get:function(){return u.loaders.slice(u.loaderIndex).map(function(e){return e.request}).concat(u.resource||"").join("!")}});Object.defineProperty(u,"previousRequest",{enumerable:true,get:function(){return u.loaders.slice(0,u.loaderIndex).map(function(e){return e.request}).join("!")}});Object.defineProperty(u,"query",{enumerable:true,get:function(){var e=u.loaders[u.loaderIndex];return e.options&&typeof e.options==="object"?e.options:e.query}});Object.defineProperty(u,"data",{enumerable:true,get:function(){return u.loaders[u.loaderIndex].data}});if(Object.preventExtensions){Object.preventExtensions(u)}var d={resourceBuffer:null,readResource:a};iteratePitchingLoaders(d,u,function(e,r){if(e){return n(e,{cacheable:c,fileDependencies:h,contextDependencies:y})}n(null,{result:r,resourceBuffer:d.resourceBuffer,cacheable:c,fileDependencies:h,contextDependencies:y})})}},384:(e,n,r)=>{var t=r(736);e.exports=function loadLoader(e,n){if(typeof System==="object"&&typeof System.import==="function"){System.import(e.path).catch(n).then(function(r){e.normal=typeof r==="function"?r:r.default;e.pitch=r.pitch;e.raw=r.raw;if(typeof e.normal!=="function"&&typeof e.pitch!=="function"){return n(new t("Module '"+e.path+"' is not a loader (must have normal or pitch function)"))}n()})}else{try{var r=require(e.path)}catch(r){if(r instanceof Error&&r.code==="EMFILE"){var f=loadLoader.bind(null,e,n);if(typeof setImmediate==="function"){return setImmediate(f)}else{return process.nextTick(f)}}return n(r)}if(typeof r!=="function"&&typeof r!=="object"){return n(new t("Module '"+e.path+"' is not a loader (export function or es6 module)"))}e.normal=typeof r==="function"?r:r.default;e.pitch=r.pitch;e.raw=r.raw;if(typeof e.normal!=="function"&&typeof e.pitch!=="function"){return n(new t("Module '"+e.path+"' is not a loader (must have normal or pitch function)"))}n()}}},664:function(e,n){(function(e,r){"use strict";true?r(n):0})(this,function(e){"use strict";var n=function noop(){};var r=function throwError(){throw new Error("Callback was already called.")};var t=5;var f=0;var u="object";var a="function";var o=Array.isArray;var i=Object.keys;var l=Array.prototype.push;var s=typeof Symbol===a&&Symbol.iterator;var c,h,y;createImmediate();var d=createEach(arrayEach,baseEach,symbolEach);var v=createMap(arrayEachIndex,baseEachIndex,symbolEachIndex,true);var p=createMap(arrayEachIndex,baseEachKey,symbolEachKey,false);var I=createFilter(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue,true);var g=createFilterSeries(true);var m=createFilterLimit(true);var W=createFilter(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue,false);var C=createFilterSeries(false);var j=createFilterLimit(false);var w=createDetect(arrayEachValue,baseEachValue,symbolEachValue,true);var b=createDetectSeries(true);var L=createDetectLimit(true);var K=createEvery(arrayEachValue,baseEachValue,symbolEachValue);var O=createEverySeries();var A=createEveryLimit();var _=createPick(arrayEachIndexValue,baseEachKeyValue,symbolEachKeyValue,true);var S=createPickSeries(true);var E=createPickLimit(true);var x=createPick(arrayEachIndexValue,baseEachKeyValue,symbolEachKeyValue,false);var B=createPickSeries(false);var D=createPickLimit(false);var q=createTransform(arrayEachResult,baseEachResult,symbolEachResult);var N=createSortBy(arrayEachIndexValue,baseEachIndexValue,symbolEachIndexValue);var V=createConcat(arrayEachIndex,baseEachIndex,symbolEachIndex);var R=createGroupBy(arrayEachValue,baseEachValue,symbolEachValue);var P=createParallel(arrayEachFunc,baseEachFunc);var F=createApplyEach(v);var Q=createApplyEach(mapSeries);var M=createLogger("log");var J=createLogger("dir");var $={VERSION:"2.6.2",each:d,eachSeries:eachSeries,eachLimit:eachLimit,forEach:d,forEachSeries:eachSeries,forEachLimit:eachLimit,eachOf:d,eachOfSeries:eachSeries,eachOfLimit:eachLimit,forEachOf:d,forEachOfSeries:eachSeries,forEachOfLimit:eachLimit,map:v,mapSeries:mapSeries,mapLimit:mapLimit,mapValues:p,mapValuesSeries:mapValuesSeries,mapValuesLimit:mapValuesLimit,filter:I,filterSeries:g,filterLimit:m,select:I,selectSeries:g,selectLimit:m,reject:W,rejectSeries:C,rejectLimit:j,detect:w,detectSeries:b,detectLimit:L,find:w,findSeries:b,findLimit:L,pick:_,pickSeries:S,pickLimit:E,omit:x,omitSeries:B,omitLimit:D,reduce:reduce,inject:reduce,foldl:reduce,reduceRight:reduceRight,foldr:reduceRight,transform:q,transformSeries:transformSeries,transformLimit:transformLimit,sortBy:N,sortBySeries:sortBySeries,sortByLimit:sortByLimit,some:some,someSeries:someSeries,someLimit:someLimit,any:some,anySeries:someSeries,anyLimit:someLimit,every:K,everySeries:O,everyLimit:A,all:K,allSeries:O,allLimit:A,concat:V,concatSeries:concatSeries,concatLimit:concatLimit,groupBy:R,groupBySeries:groupBySeries,groupByLimit:groupByLimit,parallel:P,series:series,parallelLimit:parallelLimit,tryEach:tryEach,waterfall:waterfall,angelFall:angelFall,angelfall:angelFall,whilst:whilst,doWhilst:doWhilst,until:until,doUntil:doUntil,during:during,doDuring:doDuring,forever:forever,compose:compose,seq:seq,applyEach:F,applyEachSeries:Q,queue:queue,priorityQueue:priorityQueue,cargo:cargo,auto:auto,autoInject:autoInject,retry:retry,retryable:retryable,iterator:iterator,times:times,timesSeries:timesSeries,timesLimit:timesLimit,race:race,apply:apply,nextTick:h,setImmediate:y,memoize:memoize,unmemoize:unmemoize,ensureAsync:ensureAsync,constant:constant,asyncify:asyncify,wrapSync:asyncify,log:M,dir:J,reflect:reflect,reflectAll:reflectAll,timeout:timeout,createLogger:createLogger,safe:safe,fast:fast};e["default"]=$;baseEachSync($,function(n,r){e[r]=n},i($));function createImmediate(e){var n=function delay(e){var n=slice(arguments,1);setTimeout(function(){e.apply(null,n)})};y=typeof setImmediate===a?setImmediate:n;if(typeof process===u&&typeof process.nextTick===a){c=/^v0.10/.test(process.version)?y:process.nextTick;h=/^v0/.test(process.version)?y:process.nextTick}else{h=c=y}if(e===false){c=function(e){e()}}}function createArray(e){var n=-1;var r=e.length;var t=Array(r);while(++n=n&&e[a]>=t){a--}if(u>a){break}swap(e,f,u++,a--)}return u}function swap(e,n,r,t){var f=e[r];e[r]=e[t];e[t]=f;var u=n[r];n[r]=n[t];n[t]=u}function quickSort(e,n,r,t){if(n===r){return}var f=n;while(++f<=r&&e[n]===e[f]){var u=f-1;if(t[u]>t[f]){var a=t[u];t[u]=t[f];t[f]=a}}if(f>r){return}var o=e[n]>e[f]?n:f;f=partition(e,n,r,e[o],t);quickSort(e,n,f-1,t);quickSort(e,f,r,t)}function makeConcatResult(e){var r=[];arrayEachSync(e,function(e){if(e===n){return}if(o(e)){l.apply(r,e)}else{r.push(e)}});return r}function arrayEach(e,n,r){var t=-1;var f=e.length;if(n.length===3){while(++th?h:f,m);function arrayIterator(){y=j++;if(yl?l:t,I);function arrayIterator(){if(ml?l:t,g);function arrayIterator(){h=W++;if(hl?l:t,I);function arrayIterator(){h=W++;if(hh?h:f,m);function arrayIterator(){y=C++;if(yh?h:f,m);function arrayIterator(){y=j++;if(yl?l:r,I);function arrayIterator(){h=W++;if(hl?l:t,W);function arrayIterator(){if(j=2){l.apply(g,slice(arguments,1))}if(e){f(e,g)}else if(++m===a){p=r;f(null,g)}else if(I){c(p)}else{I=true;p()}I=false}}function concatLimit(e,t,f,a){a=a||n;var l,h,y,d,v,p;var I=false;var g=0;var m=0;if(o(e)){l=e.length;v=f.length===3?arrayIteratorWithIndex:arrayIterator}else if(!e){}else if(s&&e[s]){l=Infinity;p=[];y=e[s]();v=f.length===3?symbolIteratorWithKey:symbolIterator}else if(typeof e===u){var W=i(e);l=W.length;v=f.length===3?objectIteratorWithKey:objectIterator}if(!l||isNaN(t)||t<1){return a(null,[])}p=p||Array(l);timesSync(t>l?l:t,v);function arrayIterator(){if(gl?l:t,g);function arrayIterator(){if(Wa?a:t,d);function arrayIterator(){l=p++;if(l1){var f=slice(arguments,1);return t.apply(this,f)}else{return t}}}function DLL(){this.head=null;this.tail=null;this.length=0}DLL.prototype._removeLink=function(e){var n=e.prev;var r=e.next;if(n){n.next=r}else{this.head=r}if(r){r.prev=n}else{this.tail=n}e.prev=null;e.next=null;this.length--;return e};DLL.prototype.empty=DLL;DLL.prototype._setInitial=function(e){this.length=1;this.head=this.tail=e};DLL.prototype.insertBefore=function(e,n){n.prev=e.prev;n.next=e;if(e.prev){e.prev.next=n}else{this.head=n}e.prev=n;this.length++};DLL.prototype.unshift=function(e){if(this.head){this.insertBefore(this.head,e)}else{this._setInitial(e)}};DLL.prototype.push=function(e){var n=this.tail;if(n){e.prev=n;e.next=n.next;this.tail=e;n.next=e;this.length++}else{this._setInitial(e)}};DLL.prototype.shift=function(){return this.head&&this._removeLink(this.head)};DLL.prototype.splice=function(e){var n;var r=[];while(e--&&(n=this.shift())){r.push(n)}return r};DLL.prototype.remove=function(e){var n=this.head;while(n){if(e(n)){this._removeLink(n)}n=n.next}return this};function baseQueue(e,t,f,u){if(f===undefined){f=1}else if(isNaN(f)||f<1){throw new Error("Concurrency must not be zero")}var a=0;var i=[];var s,h;var y={_tasks:new DLL,concurrency:f,payload:u,saturated:n,unsaturated:n,buffer:f/4,empty:n,drain:n,error:n,started:false,paused:false,push:push,kill:kill,unshift:unshift,remove:remove,process:e?runQueue:runCargo,length:getLength,running:running,workersList:getWorkersList,idle:idle,pause:pause,resume:resume,_worker:t};return y;function push(e,n){_insert(e,n)}function unshift(e,n){_insert(e,n,true)}function _exec(e){var n={data:e,callback:s};if(h){y._tasks.unshift(n)}else{y._tasks.push(n)}c(y.process)}function _insert(e,r,t){if(r==null){r=n}else if(typeof r!=="function"){throw new Error("task callback must be a function")}y.started=true;var f=o(e)?e:[e];if(e===undefined||!f.length){if(y.idle()){c(y.drain)}return}h=t;s=r;arrayEachSync(f,_exec);s=undefined}function kill(){y.drain=n;y._tasks.empty()}function _next(e,n){var t=false;return function done(f,u){if(t){r()}t=true;a--;var o;var l=-1;var s=i.length;var c=-1;var h=n.length;var y=arguments.length>2;var d=y&&createArray(arguments);while(++c=l.priority){l=l.next}while(i--){var s={data:u[i],priority:r,callback:f};if(l){t._tasks.insertBefore(l,s)}else{t._tasks.push(s)}c(t.process)}}}function cargo(e,n){return baseQueue(false,e,1,n)}function auto(e,t,f){if(typeof t===a){f=t;t=null}var u=i(e);var l=u.length;var s={};if(l===0){return f(null,s)}var c=0;var h=new DLL;var y=Object.create(null);f=onlyOnce(f||n);t=t||l;baseEachSync(e,iterator,u);proceedQueue();function iterator(e,t){var a,i;if(!o(e)){a=e;i=0;h.push([a,i,done]);return}var d=e.length-1;a=e[d];i=d;if(d===0){h.push([a,i,done]);return}var v=-1;while(++v=e){f(null,u);f=r}else if(a){c(iterate)}else{a=true;iterate()}a=false}}function timesLimit(e,t,f,u){u=u||n;e=+e;if(isNaN(e)||e<1||isNaN(t)||t<1){return u(null,[])}var a=Array(e);var o=false;var i=0;var l=0;timesSync(t>e?e:t,iterate);function iterate(){var n=i++;if(n=e){u(null,a);u=r}else if(o){c(iterate)}else{o=true;iterate()}o=false}}}function race(e,r){r=once(r||n);var t,f;var a=-1;if(o(e)){t=e.length;while(++a2){r=slice(arguments,1)}n(null,{value:r})}}}function reflectAll(e){var n,r;if(o(e)){n=Array(e.length);arrayEachSync(e,iterate)}else if(e&&typeof e===u){r=i(e);n={};baseEachSync(e,iterate,r)}return n;function iterate(e,r){n[r]=reflect(e)}}function createLogger(e){return function(e){var n=slice(arguments,1);n.push(done);e.apply(null,n)};function done(n){if(typeof console===u){if(n){if(console.error){console.error(n)}return}if(console[e]){var r=slice(arguments,1);arrayEachSync(r,function(n){console[e](n)})}}}}function safe(){createImmediate();return e}function fast(){createImmediate(false);return e}})},536:(e,n,r)=>{"use strict";e.exports=r(664).queue},111:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:true});n.default=readBuffer;function readBuffer(e,n,r){if(n===0){r(null,Buffer.alloc(0));return}let t=n;const f=[];const u=()=>{const u=a=>{let o=a;let i;if(o.length>t){i=o.slice(t);o=o.slice(0,t);t=0}else{t-=o.length}f.push(o);if(t===0){e.removeListener("data",u);e.pause();if(i){e.unshift(i)}r(null,Buffer.concat(f,n))}};e.on("data",u);e.resume()};u()}},745:(e,n,r)=>{"use strict";var t=r(747);var f=_interopRequireDefault(t);var u=r(282);var a=_interopRequireDefault(u);var o=r(278);var i=_interopRequireDefault(o);var l=r(536);var s=_interopRequireDefault(l);var c=r(111);var h=_interopRequireDefault(c);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const y=f.default.createWriteStream(null,{fd:3});const d=f.default.createReadStream(null,{fd:4});y.on("finish",onTerminateWrite);d.on("end",onTerminateRead);y.on("close",onTerminateWrite);d.on("close",onTerminateRead);d.on("error",onError);y.on("error",onError);const v=+process.argv[2]||20;let p=false;let I=0;const g=Object.create(null);function onError(e){console.error(e)}function onTerminateRead(){terminateRead()}function onTerminateWrite(){terminateWrite()}function writePipeWrite(...e){if(!p){y.write(...e)}}function writePipeCork(){if(!p){y.cork()}}function writePipeUncork(){if(!p){y.uncork()}}function terminateRead(){p=true;d.removeAllListeners()}function terminateWrite(){p=true;y.removeAllListeners()}function terminate(){terminateRead();terminateWrite()}function toErrorObj(e){return{message:e.message,details:e.details,stack:e.stack,hideStack:e.hideStack}}function toNativeError(e){if(!e)return null;const n=new Error(e.message);n.details=e.details;n.missing=e.missing;return n}function writeJson(e){writePipeCork();process.nextTick(()=>{writePipeUncork()});const n=Buffer.alloc(4);const r=Buffer.from(JSON.stringify(e),"utf-8");n.writeInt32BE(r.length,0);writePipeWrite(n);writePipeWrite(r)}const m=(0,s.default)(({id:e,data:n},r)=>{try{i.default.runLoaders({loaders:n.loaders,resource:n.resource,readResource:f.default.readFile.bind(f.default),context:{version:2,resolve:(n,r,t)=>{g[I]=t;writeJson({type:"resolve",id:e,questionId:I,context:n,request:r});I+=1},emitWarning:n=>{writeJson({type:"emitWarning",id:e,data:toErrorObj(n)})},emitError:n=>{writeJson({type:"emitError",id:e,data:toErrorObj(n)})},exec:(e,n)=>{const r=new a.default(n,undefined);r.paths=a.default._nodeModulePaths(undefined.context);r.filename=n;r._compile(e,n);return r.exports},options:{context:n.optionsContext},webpack:true,"thread-loader":true,sourceMap:n.sourceMap,target:n.target,minimize:n.minimize,resourceQuery:n.resourceQuery}},(n,t)=>{const{result:f,cacheable:u,fileDependencies:a,contextDependencies:o}=t;const i=[];const l=Array.isArray(f)&&f.map(e=>{const n=Buffer.isBuffer(e);if(n){i.push(e);return{buffer:true}}if(typeof e==="string"){const n=Buffer.from(e,"utf-8");i.push(n);return{buffer:true,string:true}}return{data:e}});writeJson({type:"job",id:e,error:n&&toErrorObj(n),result:{result:l,cacheable:u,fileDependencies:a,contextDependencies:o},data:i.map(e=>e.length)});i.forEach(e=>{writePipeWrite(e)});setImmediate(r)})}catch(n){writeJson({type:"job",id:e,error:toErrorObj(n)});r()}},v);function dispose(){terminate();m.kill();process.exit(0)}function onMessage(e){try{const{type:n,id:r}=e;switch(n){case"job":{m.push(e);break}case"result":{const{error:n,result:t}=e;const f=g[r];if(f){const e=toNativeError(n);f(e,t)}else{console.error(`Worker got unexpected result id ${r}`)}delete g[r];break}case"warmup":{const{requires:n}=e;n.forEach(e=>require(e));break}default:{console.error(`Worker got unexpected job type ${n}`);break}}}catch(e){console.error(`Error in worker ${e}`)}}function readNextMessage(){(0,h.default)(d,4,(e,n)=>{if(e){console.error(`Failed to communicate with main process (read length) ${e}`);return}const r=n.length&&n.readInt32BE(0);if(r===0){dispose();return}(0,h.default)(d,r,(e,n)=>{if(p){return}if(e){console.error(`Failed to communicate with main process (read message) ${e}`);return}const r=n.toString("utf-8");const t=JSON.parse(r);onMessage(t);setImmediate(()=>readNextMessage())})})}readNextMessage()},747:e=>{"use strict";e.exports=require("fs")},282:e=>{"use strict";e.exports=require("module")}};var n={};function __webpack_require__(r){if(n[r]){return n[r].exports}var t=n[r]={exports:{}};var f=true;try{e[r].call(t.exports,t,t.exports,__webpack_require__);f=false}finally{if(f)delete n[r]}return t.exports}__webpack_require__.ab=__dirname+"/";return __webpack_require__(745)})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack-sources/LICENSE b/packages/next/compiled/webpack-sources/LICENSE new file mode 100644 index 000000000000000..7c6f8955dc016fb --- /dev/null +++ b/packages/next/compiled/webpack-sources/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/next/compiled/webpack-sources/index.js b/packages/next/compiled/webpack-sources/index.js new file mode 100644 index 000000000000000..36f65201c2a93da --- /dev/null +++ b/packages/next/compiled/webpack-sources/index.js @@ -0,0 +1 @@ +module.exports=(()=>{var e={667:(e,t,r)=>{"use strict";const n=r(495).y;const s=r(495).P;class CodeNode{constructor(e){this.generatedCode=e}clone(){return new CodeNode(this.generatedCode)}getGeneratedCode(){return this.generatedCode}getMappings(e){const t=n(this.generatedCode);const r=Array(t+1).join(";");if(t>0){e.unfinishedGeneratedLine=s(this.generatedCode);if(e.unfinishedGeneratedLine>0){return r+"A"}else{return r}}else{const t=e.unfinishedGeneratedLine;e.unfinishedGeneratedLine+=s(this.generatedCode);if(t===0&&e.unfinishedGeneratedLine>0){return"A"}else{return""}}}addGeneratedCode(e){this.generatedCode+=e}mapGeneratedCode(e){const t=e(this.generatedCode);return new CodeNode(t)}getNormalizedNodes(){return[this]}merge(e){if(e instanceof CodeNode){this.generatedCode+=e.generatedCode;return this}return false}}e.exports=CodeNode},432:e=>{"use strict";class MappingsContext{constructor(){this.sourcesIndices=new Map;this.sourcesContent=new Map;this.hasSourceContent=false;this.currentOriginalLine=1;this.currentSource=0;this.unfinishedGeneratedLine=false}ensureSource(e,t){let r=this.sourcesIndices.get(e);if(typeof r==="number"){return r}r=this.sourcesIndices.size;this.sourcesIndices.set(e,r);this.sourcesContent.set(e,t);if(typeof t==="string")this.hasSourceContent=true;return r}getArrays(){const e=[];const t=[];for(const r of this.sourcesContent){e.push(r[0]);t.push(r[1])}return{sources:e,sourcesContent:t}}}e.exports=MappingsContext},664:(e,t,r)=>{"use strict";const n=r(430);const s=r(495).y;const i=r(495).P;const o=";AAAA";class SingleLineNode{constructor(e,t,r,n){this.generatedCode=e;this.originalSource=r;this.source=t;this.line=n||1;this._numberOfLines=s(this.generatedCode);this._endsWithNewLine=e[e.length-1]==="\n"}clone(){return new SingleLineNode(this.generatedCode,this.source,this.originalSource,this.line)}getGeneratedCode(){return this.generatedCode}getMappings(e){if(!this.generatedCode)return"";const t=this._numberOfLines;const r=e.ensureSource(this.source,this.originalSource);let s="A";if(e.unfinishedGeneratedLine)s=","+n.encode(e.unfinishedGeneratedLine);s+=n.encode(r-e.currentSource);s+=n.encode(this.line-e.currentOriginalLine);s+="A";e.currentSource=r;e.currentOriginalLine=this.line;const u=e.unfinishedGeneratedLine=i(this.generatedCode);s+=Array(t).join(o);if(u===0){s+=";"}else{if(t!==0)s+=o}return s}getNormalizedNodes(){return[this]}mapGeneratedCode(e){const t=e(this.generatedCode);return new SingleLineNode(t,this.source,this.originalSource,this.line)}merge(e){if(e instanceof SingleLineNode){return this.mergeSingleLineNode(e)}return false}mergeSingleLineNode(e){if(this.source===e.source&&this.originalSource===e.originalSource){if(this.line===e.line){this.generatedCode+=e.generatedCode;this._numberOfLines+=e._numberOfLines;this._endsWithNewLine=e._endsWithNewLine;return this}else if(this.line+1===e.line&&this._endsWithNewLine&&this._numberOfLines===1&&e._numberOfLines<=1){return new u(this.generatedCode+e.generatedCode,this.source,this.originalSource,this.line)}}return false}}e.exports=SingleLineNode;const u=r(176)},361:(e,t,r)=>{"use strict";const n=r(667);const s=r(176);const i=r(432);const o=r(495).y;class SourceListMap{constructor(e,t,r){if(Array.isArray(e)){this.children=e}else{this.children=[];if(e||t)this.add(e,t,r)}}add(e,t,r){if(typeof e==="string"){if(t){this.children.push(new s(e,t,r))}else if(this.children.length>0&&this.children[this.children.length-1]instanceof n){this.children[this.children.length-1].addGeneratedCode(e)}else{this.children.push(new n(e))}}else if(e.getMappings&&e.getGeneratedCode){this.children.push(e)}else if(e.children){e.children.forEach(function(e){this.children.push(e)},this)}else{throw new Error("Invalid arguments to SourceListMap.protfotype.add: Expected string, Node or SourceListMap")}}preprend(e,t,r){if(typeof e==="string"){if(t){this.children.unshift(new s(e,t,r))}else if(this.children.length>0&&this.children[this.children.length-1].preprendGeneratedCode){this.children[this.children.length-1].preprendGeneratedCode(e)}else{this.children.unshift(new n(e))}}else if(e.getMappings&&e.getGeneratedCode){this.children.unshift(e)}else if(e.children){e.children.slice().reverse().forEach(function(e){this.children.unshift(e)},this)}else{throw new Error("Invalid arguments to SourceListMap.protfotype.prerend: Expected string, Node or SourceListMap")}}mapGeneratedCode(e){const t=[];this.children.forEach(function(e){e.getNormalizedNodes().forEach(function(e){t.push(e)})});const r=[];t.forEach(function(t){t=t.mapGeneratedCode(e);if(r.length===0){r.push(t)}else{const e=r[r.length-1];const n=e.merge(t);if(n){r[r.length-1]=n}else{r.push(t)}}});return new SourceListMap(r)}toString(){return this.children.map(function(e){return e.getGeneratedCode()}).join("")}toStringWithSourceMap(e){const t=new i;const r=this.children.map(function(e){return e.getGeneratedCode()}).join("");const n=this.children.map(function(e){return e.getMappings(t)}).join("");const s=t.getArrays();return{source:r,map:{version:3,file:e&&e.file,sources:s.sources,sourcesContent:t.hasSourceContent?s.sourcesContent:undefined,mappings:n}}}}e.exports=SourceListMap},176:(e,t,r)=>{"use strict";const n=r(430);const s=r(495).y;const i=r(495).P;const o=";AACA";class SourceNode{constructor(e,t,r,n){this.generatedCode=e;this.originalSource=r;this.source=t;this.startingLine=n||1;this._numberOfLines=s(this.generatedCode);this._endsWithNewLine=e[e.length-1]==="\n"}clone(){return new SourceNode(this.generatedCode,this.source,this.originalSource,this.startingLine)}getGeneratedCode(){return this.generatedCode}addGeneratedCode(e){this.generatedCode+=e;this._numberOfLines+=s(e);this._endsWithNewLine=e[e.length-1]==="\n"}getMappings(e){if(!this.generatedCode)return"";const t=this._numberOfLines;const r=e.ensureSource(this.source,this.originalSource);let s="A";if(e.unfinishedGeneratedLine)s=","+n.encode(e.unfinishedGeneratedLine);s+=n.encode(r-e.currentSource);s+=n.encode(this.startingLine-e.currentOriginalLine);s+="A";e.currentSource=r;e.currentOriginalLine=this.startingLine+t-1;const u=e.unfinishedGeneratedLine=i(this.generatedCode);s+=Array(t).join(o);if(u===0){s+=";"}else{if(t!==0){s+=o}e.currentOriginalLine++}return s}mapGeneratedCode(e){throw new Error("Cannot map generated code on a SourceMap. Normalize to SingleLineNode first.")}getNormalizedNodes(){var e=[];var t=this.startingLine;var r=this.generatedCode;var n=0;var s=r.length;while(n{var r={};var n={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(e,t){r[e]=t;n[t]=e});var s={};s.encode=function base64_encode(e){if(e in n){return n[e]}throw new TypeError("Must be between 0 and 63: "+e)};s.decode=function base64_decode(e){if(e in r){return r[e]}throw new TypeError("Not a valid base 64 digit: "+e)};var i=5;var o=1<>1;return t?-r:r}t.encode=function base64VLQ_encode(e){var t="";var r;var n=toVLQSigned(e);do{r=n&u;n>>>=i;if(n>0){r|=a}t+=s.encode(r)}while(n>0);return t};t.decode=function base64VLQ_decode(e,t){var r=0;var n=e.length;var o=0;var c=0;var h,l;do{if(r>=n){throw new Error("Expected more digits in base 64 VLQ value.")}l=s.decode(e.charAt(r++));h=!!(l&a);l&=u;o=o+(l<{"use strict";const n=r(430);const s=r(176);const i=r(667);const o=r(361);e.exports=function fromStringWithSourceMap(e,t){const r=t.sources;const u=t.sourcesContent;const a=t.mappings.split(";");const c=e.split("\n");const h=[];let l=null;let f=1;let d=0;let p;function addCode(e){if(l&&l instanceof i){l.addGeneratedCode(e)}else if(l&&l instanceof s&&!e.trim()){l.addGeneratedCode(e);p++}else{l=new i(e);h.push(l)}}function addSource(e,t,r,n){if(l&&l instanceof s&&l.source===t&&p===n){l.addGeneratedCode(e);p++}else{l=new s(e,t,r,n);p=n+1;h.push(l)}}a.forEach(function(e,t){let r=c[t];if(typeof r==="undefined")return;if(t!==c.length-1)r+="\n";if(!e)return addCode(r);e={value:0,rest:e};let n=false;while(e.rest)n=processMapping(e,r,n)||n;if(!n)addCode(r)});if(a.length{"use strict";t.y=function getNumberOfLines(e){let t=-1;let r=-1;do{t++;r=e.indexOf("\n",r+1)}while(r>=0);return t};t.P=function getUnfinishedLine(e){const t=e.lastIndexOf("\n");if(t===-1)return e.length;else return e.length-t-1}},524:(e,t,r)=>{t.SourceListMap=r(361);r(176);r(664);r(667);r(432);t.fromStringWithSourceMap=r(444)},411:(e,t,r)=>{"use strict";const n=r(781);class CachedSource extends n{constructor(e){super();this._source=e;this._cachedSource=undefined;this._cachedSize=undefined;this._cachedMaps={};if(e.node)this.node=function(e){return this._source.node(e)};if(e.listMap)this.listMap=function(e){return this._source.listMap(e)}}source(){if(typeof this._cachedSource!=="undefined")return this._cachedSource;return this._cachedSource=this._source.source()}size(){if(typeof this._cachedSize!=="undefined")return this._cachedSize;if(typeof this._cachedSource!=="undefined"){if(Buffer.from.length===1)return new Buffer(this._cachedSource).length;return this._cachedSize=Buffer.byteLength(this._cachedSource)}return this._cachedSize=this._source.size()}sourceAndMap(e){const t=JSON.stringify(e);if(typeof this._cachedSource!=="undefined"&&t in this._cachedMaps)return{source:this._cachedSource,map:this._cachedMaps[t]};else if(typeof this._cachedSource!=="undefined"){return{source:this._cachedSource,map:this._cachedMaps[t]=this._source.map(e)}}else if(t in this._cachedMaps){return{source:this._cachedSource=this._source.source(),map:this._cachedMaps[t]}}const r=this._source.sourceAndMap(e);this._cachedSource=r.source;this._cachedMaps[t]=r.map;return{source:this._cachedSource,map:this._cachedMaps[t]}}map(e){if(!e)e={};const t=JSON.stringify(e);if(t in this._cachedMaps)return this._cachedMaps[t];return this._cachedMaps[t]=this._source.map()}updateHash(e){this._source.updateHash(e)}}e.exports=CachedSource},744:(e,t,r)=>{"use strict";const n=r(241).SourceNode;const s=r(524).SourceListMap;const i=r(781);class ConcatSource extends i{constructor(){super();this.children=[];for(var e=0;e{"use strict";var n=r(241).SourceNode;var s=r(241).SourceMapConsumer;var i=r(524).SourceListMap;var o=r(781);class LineToLineMappedSource extends o{constructor(e,t,r){super();this._value=e;this._name=t;this._originalSource=r}source(){return this._value}node(e){var t=this._value;var r=this._name;var s=t.split("\n");var i=new n(null,null,null,s.map(function(e,t){return new n(t+1,0,r,e+(t!=s.length-1?"\n":""))}));i.setSourceContent(r,this._originalSource);return i}listMap(e){return new i(this._value,this._name,this._originalSource)}updateHash(e){e.update(this._value);e.update(this._originalSource)}}r(733)(LineToLineMappedSource.prototype);e.exports=LineToLineMappedSource},221:(e,t,r)=>{"use strict";var n=r(241).SourceNode;var s=r(241).SourceMapConsumer;var i=r(524).SourceListMap;var o=r(781);var u=/(?!$)[^\n\r;{}]*[\n\r;{}]*/g;function _splitCode(e){return e.match(u)||[]}class OriginalSource extends o{constructor(e,t){super();this._value=e;this._name=t}source(){return this._value}node(e){e=e||{};var t=this._sourceMap;var r=this._value;var s=this._name;var i=r.split("\n");var o=new n(null,null,null,i.map(function(t,r){var o=0;if(e.columns===false){var u=t+(r!=i.length-1?"\n":"");return new n(r+1,0,s,u)}return new n(null,null,null,_splitCode(t+(r!=i.length-1?"\n":"")).map(function(e){if(/^\s*$/.test(e)){o+=e.length;return e}var t=new n(r+1,o,s,e);o+=e.length;return t}))}));o.setSourceContent(s,r);return o}listMap(e){return new i(this._value,this._name,this._value)}updateHash(e){e.update(this._value)}}r(733)(OriginalSource.prototype);e.exports=OriginalSource},141:(e,t,r)=>{"use strict";var n=r(781);var s=r(241).SourceNode;var i=/\n(?=.|\s)/g;function cloneAndPrefix(e,t,r){if(typeof e==="string"){var n=e.replace(i,"\n"+t);if(r.length>0)n=r.pop()+n;if(/\n$/.test(e))r.push(t);return n}else{var o=new s(e.line,e.column,e.source,e.children.map(function(e){return cloneAndPrefix(e,t,r)}),e.name);o.sourceContents=e.sourceContents;return o}}class PrefixSource extends n{constructor(e,t){super();this._source=t;this._prefix=e}source(){var e=typeof this._source==="string"?this._source:this._source.source();var t=this._prefix;return t+e.replace(i,"\n"+t)}node(e){var t=this._source.node(e);var r=this._prefix;var n=[];var i=new s;t.walkSourceContents(function(e,t){i.setSourceContent(e,t)});var o=true;t.walk(function(e,t){var i=e.split(/(\n)/);for(var u=0;u{"use strict";var n=r(781);var s=r(241).SourceNode;var i=r(524).SourceListMap;class RawSource extends n{constructor(e){super();this._value=e}source(){return this._value}map(e){return null}node(e){return new s(null,null,null,this._value)}listMap(e){return new i(this._value)}updateHash(e){e.update(this._value)}}e.exports=RawSource},22:(e,t,r)=>{"use strict";var n=r(781);var s=r(241).SourceNode;class Replacement{constructor(e,t,r,n,s){this.start=e;this.end=t;this.content=r;this.insertIndex=n;this.name=s}}class ReplaceSource extends n{constructor(e,t){super();this._source=e;this._name=t;this.replacements=[]}replace(e,t,r,n){if(typeof r!=="string")throw new Error("insertion must be a string, but is a "+typeof r);this.replacements.push(new Replacement(e,t,r,this.replacements.length,n))}insert(e,t,r){if(typeof t!=="string")throw new Error("insertion must be a string, but is a "+typeof t+": "+t);this.replacements.push(new Replacement(e,e-1,t,this.replacements.length,r))}source(e){return this._replaceString(this._source.source())}original(){return this._source}_sortReplacements(){this.replacements.sort(function(e,t){var r=t.end-e.end;if(r!==0)return r;r=t.start-e.start;if(r!==0)return r;return t.insertIndex-e.insertIndex})}_replaceString(e){if(typeof e!=="string")throw new Error("str must be a string, but is a "+typeof e+": "+e);this._sortReplacements();var t=[e];this.replacements.forEach(function(e){var r=t.pop();var n=this._splitString(r,Math.floor(e.end+1));var s=this._splitString(n[0],Math.floor(e.start));t.push(n[1],e.content,s[0])},this);let r="";for(let e=t.length-1;e>=0;--e){r+=t[e]}return r}node(e){var t=this._source.node(e);if(this.replacements.length===0){return t}this._sortReplacements();var r=new ReplacementEnumerator(this.replacements);var n=[];var i=0;var o=Object.create(null);var u=Object.create(null);var a=new s;t.walkSourceContents(function(e,t){a.setSourceContent(e,t);o["$"+e]=t});var c=this._replaceInStringNode.bind(this,n,r,function getOriginalSource(e){var t="$"+e.source;var r=u[t];if(!r){var n=o[t];if(!n)return null;r=n.split("\n").map(function(e){return e+"\n"});u[t]=r}if(e.line>r.length)return null;var s=r[e.line-1];return s.substr(e.column)});t.walk(function(e,t){i=c(e,i,t)});var h=r.footer();if(h){n.push(h)}a.add(n);return a}listMap(e){this._sortReplacements();var t=this._source.listMap(e);var r=0;var n=this.replacements;var s=n.length-1;var i=0;t=t.mapGeneratedCode(function(e){var t=r+e.length;if(i>e.length){i-=e.length;e=""}else{if(i>0){e=e.substr(i);r+=i;i=0}var o="";while(s>=0&&n[s].start=0){o+=n[s].content;s--}if(o){t.add(o)}return t}_splitString(e,t){return t<=0?["",e]:[e.substr(0,t),e.substr(t)]}_replaceInStringNode(e,t,r,n,i,o){var u=undefined;do{var a=t.position-i;if(a<0){a=0}if(a>=n.length||t.done){if(t.emit){var c=new s(o.line,o.column,o.source,n,o.name);e.push(c)}return i+n.length}var h=o.column;var l;if(a>0){l=n.slice(0,a);if(u===undefined){u=r(o)}if(u&&u.length>=a&&u.startsWith(l)){o.column+=a;u=u.substr(a)}}var f=t.next();if(!f){if(a>0){var d=new s(o.line,h,o.source,l,o.name);e.push(d)}if(t.value){e.push(new s(o.line,o.column,o.source,t.value,o.name||t.name))}}n=n.substr(a);i+=a}while(true)}}class ReplacementEnumerator{constructor(e){this.replacements=e||[];this.index=this.replacements.length;this.done=false;this.emit=false;this.next()}next(){if(this.done)return true;if(this.emit){var e=this.replacements[this.index];var t=Math.floor(e.end+1);this.position=t;this.value=e.content;this.name=e.name}else{this.index--;if(this.index<0){this.done=true}else{var r=this.replacements[this.index];var n=Math.floor(r.start);this.position=n}}if(this.position<0)this.position=0;this.emit=!this.emit;return this.emit}footer(){if(!this.done&&!this.emit)this.next();if(this.done){return[]}else{var e="";for(var t=this.index;t>=0;t--){var r=this.replacements[t];e+=r.content}return e}}}r(733)(ReplaceSource.prototype);e.exports=ReplaceSource},781:(e,t,r)=>{"use strict";var n=r(241).SourceNode;var s=r(241).SourceMapConsumer;class Source{source(){throw new Error("Abstract")}size(){if(Buffer.from.length===1)return new Buffer(this.source()).length;return Buffer.byteLength(this.source())}map(e){return null}sourceAndMap(e){return{source:this.source(),map:this.map()}}node(){throw new Error("Abstract")}listNode(){throw new Error("Abstract")}updateHash(e){var t=this.source();e.update(t||"")}}e.exports=Source},733:e=>{"use strict";e.exports=function mixinSourceAndMap(e){e.map=function(e){e=e||{};if(e.columns===false){return this.listMap(e).toStringWithSourceMap({file:"x"}).map}return this.node(e).toStringWithSourceMap({file:"x"}).map.toJSON()};e.sourceAndMap=function(e){e=e||{};if(e.columns===false){return this.listMap(e).toStringWithSourceMap({file:"x"})}var t=this.node(e).toStringWithSourceMap({file:"x"});return{source:t.code,map:t.map.toJSON()}}}},203:(e,t,r)=>{"use strict";var n=r(241).SourceNode;var s=r(241).SourceMapConsumer;var i=r(241).SourceMapGenerator;var o=r(524).SourceListMap;var u=r(524).fromStringWithSourceMap;var a=r(781);var c=r(540);class SourceMapSource extends a{constructor(e,t,r,n,s,i){super();this._value=e;this._name=t;this._sourceMap=r;this._originalSource=n;this._innerSourceMap=s;this._removeOriginalSource=i}source(){return this._value}node(e){var t=this._sourceMap;var r=n.fromStringWithSourceMap(this._value,new s(t));r.setSourceContent(this._name,this._originalSource);var i=this._innerSourceMap;if(i){r=c(r,new s(i),this._name,this._removeOriginalSource)}return r}listMap(e){e=e||{};if(e.module===false)return new o(this._value,this._name,this._value);return u(this._value,typeof this._sourceMap==="string"?JSON.parse(this._sourceMap):this._sourceMap)}updateHash(e){e.update(this._value);if(this._originalSource)e.update(this._originalSource)}}r(733)(SourceMapSource.prototype);e.exports=SourceMapSource},540:(e,t,r)=>{"use strict";var n=r(241).SourceNode;var s=r(241).SourceMapConsumer;var i=function(e,t,r,i){var o=new n;var u=[];var a={};var c={};var h={};var l={};t.eachMapping(function(e){(c[e.generatedLine]=c[e.generatedLine]||[]).push(e)},null,s.GENERATED_ORDER);e.walkSourceContents(function(e,t){a["$"+e]=t});var f=a["$"+r];var d=f?f.split("\n"):undefined;e.walk(function(e,s){var f;if(s.source===r&&s.line&&c[s.line]){var p;var v=c[s.line];for(var _=0;_0){var C=S.slice(p.generatedColumn,s.column);var b=L.slice(p.originalColumn,p.originalColumn+x);if(C===b){p=Object.assign({},p,{originalColumn:p.originalColumn+x,generatedColumn:s.column})}}if(!p.name&&s.name){g=L.slice(p.originalColumn,p.originalColumn+s.name.length)===s.name}}}f=p.source;u.push(new n(p.originalLine,p.originalColumn,f,e,g?s.name:p.name));if(!("$"+f in h)){h["$"+f]=true;var y=t.sourceContentFor(f,true);if(y){o.setSourceContent(f,y)}}return}}if(i&&s.source===r||!s.source){u.push(e);return}f=s.source;u.push(new n(s.line,s.column,f,e,s.name));if("$"+f in a){if(!("$"+f in h)){o.setSourceContent(f,a["$"+f]);delete a["$"+f]}}});o.add(u);return o};e.exports=i},368:(e,t,r)=>{t.Source=r(781);t.RawSource=r(76);t.OriginalSource=r(221);t.SourceMapSource=r(203);t.LineToLineMappedSource=r(820);t.CachedSource=r(411);t.ConcatSource=r(744);t.ReplaceSource=r(22);t.PrefixSource=r(141)},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __webpack_require__(r){if(t[r]){return t[r].exports}var n=t[r]={exports:{}};var s=true;try{e[r](n,n.exports,__webpack_require__);s=false}finally{if(s)delete t[r]}return n.exports}__webpack_require__.ab=__dirname+"/";return __webpack_require__(368)})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack-sources/package.json b/packages/next/compiled/webpack-sources/package.json new file mode 100644 index 000000000000000..acd3193c9f72756 --- /dev/null +++ b/packages/next/compiled/webpack-sources/package.json @@ -0,0 +1 @@ +{"name":"webpack-sources","main":"index.js","author":"Tobias Koppers @sokra","license":"MIT"} diff --git a/packages/next/compiled/webpack-sources2/LICENSE b/packages/next/compiled/webpack-sources2/LICENSE new file mode 100644 index 000000000000000..7c6f8955dc016fb --- /dev/null +++ b/packages/next/compiled/webpack-sources2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/next/compiled/webpack-sources2/index.js b/packages/next/compiled/webpack-sources2/index.js new file mode 100644 index 000000000000000..39b4321d5679230 --- /dev/null +++ b/packages/next/compiled/webpack-sources2/index.js @@ -0,0 +1 @@ +module.exports=(()=>{var e={667:(e,t,s)=>{"use strict";const n=s(495).y;const i=s(495).P;class CodeNode{constructor(e){this.generatedCode=e}clone(){return new CodeNode(this.generatedCode)}getGeneratedCode(){return this.generatedCode}getMappings(e){const t=n(this.generatedCode);const s=Array(t+1).join(";");if(t>0){e.unfinishedGeneratedLine=i(this.generatedCode);if(e.unfinishedGeneratedLine>0){return s+"A"}else{return s}}else{const t=e.unfinishedGeneratedLine;e.unfinishedGeneratedLine+=i(this.generatedCode);if(t===0&&e.unfinishedGeneratedLine>0){return"A"}else{return""}}}addGeneratedCode(e){this.generatedCode+=e}mapGeneratedCode(e){const t=e(this.generatedCode);return new CodeNode(t)}getNormalizedNodes(){return[this]}merge(e){if(e instanceof CodeNode){this.generatedCode+=e.generatedCode;return this}return false}}e.exports=CodeNode},432:e=>{"use strict";class MappingsContext{constructor(){this.sourcesIndices=new Map;this.sourcesContent=new Map;this.hasSourceContent=false;this.currentOriginalLine=1;this.currentSource=0;this.unfinishedGeneratedLine=false}ensureSource(e,t){let s=this.sourcesIndices.get(e);if(typeof s==="number"){return s}s=this.sourcesIndices.size;this.sourcesIndices.set(e,s);this.sourcesContent.set(e,t);if(typeof t==="string")this.hasSourceContent=true;return s}getArrays(){const e=[];const t=[];for(const s of this.sourcesContent){e.push(s[0]);t.push(s[1])}return{sources:e,sourcesContent:t}}}e.exports=MappingsContext},664:(e,t,s)=>{"use strict";const n=s(430);const i=s(495).y;const r=s(495).P;const u=";AAAA";class SingleLineNode{constructor(e,t,s,n){this.generatedCode=e;this.originalSource=s;this.source=t;this.line=n||1;this._numberOfLines=i(this.generatedCode);this._endsWithNewLine=e[e.length-1]==="\n"}clone(){return new SingleLineNode(this.generatedCode,this.source,this.originalSource,this.line)}getGeneratedCode(){return this.generatedCode}getMappings(e){if(!this.generatedCode)return"";const t=this._numberOfLines;const s=e.ensureSource(this.source,this.originalSource);let i="A";if(e.unfinishedGeneratedLine)i=","+n.encode(e.unfinishedGeneratedLine);i+=n.encode(s-e.currentSource);i+=n.encode(this.line-e.currentOriginalLine);i+="A";e.currentSource=s;e.currentOriginalLine=this.line;const o=e.unfinishedGeneratedLine=r(this.generatedCode);i+=Array(t).join(u);if(o===0){i+=";"}else{if(t!==0)i+=u}return i}getNormalizedNodes(){return[this]}mapGeneratedCode(e){const t=e(this.generatedCode);return new SingleLineNode(t,this.source,this.originalSource,this.line)}merge(e){if(e instanceof SingleLineNode){return this.mergeSingleLineNode(e)}return false}mergeSingleLineNode(e){if(this.source===e.source&&this.originalSource===e.originalSource){if(this.line===e.line){this.generatedCode+=e.generatedCode;this._numberOfLines+=e._numberOfLines;this._endsWithNewLine=e._endsWithNewLine;return this}else if(this.line+1===e.line&&this._endsWithNewLine&&this._numberOfLines===1&&e._numberOfLines<=1){return new o(this.generatedCode+e.generatedCode,this.source,this.originalSource,this.line)}}return false}}e.exports=SingleLineNode;const o=s(176)},361:(e,t,s)=>{"use strict";const n=s(667);const i=s(176);const r=s(432);const u=s(495).y;class SourceListMap{constructor(e,t,s){if(Array.isArray(e)){this.children=e}else{this.children=[];if(e||t)this.add(e,t,s)}}add(e,t,s){if(typeof e==="string"){if(t){this.children.push(new i(e,t,s))}else if(this.children.length>0&&this.children[this.children.length-1]instanceof n){this.children[this.children.length-1].addGeneratedCode(e)}else{this.children.push(new n(e))}}else if(e.getMappings&&e.getGeneratedCode){this.children.push(e)}else if(e.children){e.children.forEach(function(e){this.children.push(e)},this)}else{throw new Error("Invalid arguments to SourceListMap.protfotype.add: Expected string, Node or SourceListMap")}}preprend(e,t,s){if(typeof e==="string"){if(t){this.children.unshift(new i(e,t,s))}else if(this.children.length>0&&this.children[this.children.length-1].preprendGeneratedCode){this.children[this.children.length-1].preprendGeneratedCode(e)}else{this.children.unshift(new n(e))}}else if(e.getMappings&&e.getGeneratedCode){this.children.unshift(e)}else if(e.children){e.children.slice().reverse().forEach(function(e){this.children.unshift(e)},this)}else{throw new Error("Invalid arguments to SourceListMap.protfotype.prerend: Expected string, Node or SourceListMap")}}mapGeneratedCode(e){const t=[];this.children.forEach(function(e){e.getNormalizedNodes().forEach(function(e){t.push(e)})});const s=[];t.forEach(function(t){t=t.mapGeneratedCode(e);if(s.length===0){s.push(t)}else{const e=s[s.length-1];const n=e.merge(t);if(n){s[s.length-1]=n}else{s.push(t)}}});return new SourceListMap(s)}toString(){return this.children.map(function(e){return e.getGeneratedCode()}).join("")}toStringWithSourceMap(e){const t=new r;const s=this.children.map(function(e){return e.getGeneratedCode()}).join("");const n=this.children.map(function(e){return e.getMappings(t)}).join("");const i=t.getArrays();return{source:s,map:{version:3,file:e&&e.file,sources:i.sources,sourcesContent:t.hasSourceContent?i.sourcesContent:undefined,mappings:n}}}}e.exports=SourceListMap},176:(e,t,s)=>{"use strict";const n=s(430);const i=s(495).y;const r=s(495).P;const u=";AACA";class SourceNode{constructor(e,t,s,n){this.generatedCode=e;this.originalSource=s;this.source=t;this.startingLine=n||1;this._numberOfLines=i(this.generatedCode);this._endsWithNewLine=e[e.length-1]==="\n"}clone(){return new SourceNode(this.generatedCode,this.source,this.originalSource,this.startingLine)}getGeneratedCode(){return this.generatedCode}addGeneratedCode(e){this.generatedCode+=e;this._numberOfLines+=i(e);this._endsWithNewLine=e[e.length-1]==="\n"}getMappings(e){if(!this.generatedCode)return"";const t=this._numberOfLines;const s=e.ensureSource(this.source,this.originalSource);let i="A";if(e.unfinishedGeneratedLine)i=","+n.encode(e.unfinishedGeneratedLine);i+=n.encode(s-e.currentSource);i+=n.encode(this.startingLine-e.currentOriginalLine);i+="A";e.currentSource=s;e.currentOriginalLine=this.startingLine+t-1;const o=e.unfinishedGeneratedLine=r(this.generatedCode);i+=Array(t).join(u);if(o===0){i+=";"}else{if(t!==0){i+=u}e.currentOriginalLine++}return i}mapGeneratedCode(e){throw new Error("Cannot map generated code on a SourceMap. Normalize to SingleLineNode first.")}getNormalizedNodes(){var e=[];var t=this.startingLine;var s=this.generatedCode;var n=0;var i=s.length;while(n{var s={};var n={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(e,t){s[e]=t;n[t]=e});var i={};i.encode=function base64_encode(e){if(e in n){return n[e]}throw new TypeError("Must be between 0 and 63: "+e)};i.decode=function base64_decode(e){if(e in s){return s[e]}throw new TypeError("Not a valid base 64 digit: "+e)};var r=5;var u=1<>1;return t?-s:s}t.encode=function base64VLQ_encode(e){var t="";var s;var n=toVLQSigned(e);do{s=n&o;n>>>=r;if(n>0){s|=f}t+=i.encode(s)}while(n>0);return t};t.decode=function base64VLQ_decode(e,t){var s=0;var n=e.length;var u=0;var c=0;var h,a;do{if(s>=n){throw new Error("Expected more digits in base 64 VLQ value.")}a=i.decode(e.charAt(s++));h=!!(a&f);a&=o;u=u+(a<{"use strict";const n=s(430);const i=s(176);const r=s(667);const u=s(361);e.exports=function fromStringWithSourceMap(e,t){const s=t.sources;const o=t.sourcesContent;const f=t.mappings.split(";");const c=e.split("\n");const h=[];let a=null;let l=1;let d=0;let p;function addCode(e){if(a&&a instanceof r){a.addGeneratedCode(e)}else if(a&&a instanceof i&&!e.trim()){a.addGeneratedCode(e);p++}else{a=new r(e);h.push(a)}}function addSource(e,t,s,n){if(a&&a instanceof i&&a.source===t&&p===n){a.addGeneratedCode(e);p++}else{a=new i(e,t,s,n);p=n+1;h.push(a)}}f.forEach(function(e,t){let s=c[t];if(typeof s==="undefined")return;if(t!==c.length-1)s+="\n";if(!e)return addCode(s);e={value:0,rest:e};let n=false;while(e.rest)n=processMapping(e,s,n)||n;if(!n)addCode(s)});if(f.length{"use strict";t.y=function getNumberOfLines(e){let t=-1;let s=-1;do{t++;s=e.indexOf("\n",s+1)}while(s>=0);return t};t.P=function getUnfinishedLine(e){const t=e.lastIndexOf("\n");if(t===-1)return e.length;else return e.length-t-1}},524:(e,t,s)=>{t.SourceListMap=s(361);t.SourceNode=s(176);t.SingleLineNode=s(664);t.CodeNode=s(667);t.MappingsContext=s(432);t.fromStringWithSourceMap=s(444)},979:(e,t,s)=>{"use strict";const n=s(604);const i=e=>{if(typeof e!=="object"||!e)return e;const t=Object.assign({},e);if(e.mappings){t.mappings=Buffer.from(e.mappings,"utf-8")}if(e.sourcesContent){t.sourcesContent=e.sourcesContent.map(e=>e&&Buffer.from(e,"utf-8"))}return t};const r=e=>{if(typeof e!=="object"||!e)return e;const t=Object.assign({},e);if(e.mappings){t.mappings=e.mappings.toString("utf-8")}if(e.sourcesContent){t.sourcesContent=e.sourcesContent.map(e=>e&&e.toString("utf-8"))}return t};class CachedSource extends n{constructor(e,t){super();this._source=e;this._cachedSourceType=t?t.source:undefined;this._cachedSource=undefined;this._cachedBuffer=t?t.buffer:undefined;this._cachedSize=t?t.size:undefined;this._cachedMaps=t?t.maps:new Map;this._cachedHashUpdate=t?t.hash:undefined}getCachedData(){if(this._cachedSource){this.buffer()}const e=new Map;for(const t of this._cachedMaps){if(t[1].bufferedMap===undefined){t[1].bufferedMap=i(t[1].map)}e.set(t[0],{map:undefined,bufferedMap:t[1].bufferedMap})}return{buffer:this._cachedBuffer,source:this._cachedSourceType!==undefined?this._cachedSourceType:typeof this._cachedSource==="string"?true:Buffer.isBuffer(this._cachedSource)?false:undefined,size:this._cachedSize,maps:e,hash:this._cachedHashUpdate}}originalLazy(){return this._source}original(){if(typeof this._source==="function")this._source=this._source();return this._source}source(){if(this._cachedSource!==undefined)return this._cachedSource;if(this._cachedBuffer&&this._cachedSourceType!==undefined){return this._cachedSource=this._cachedSourceType?this._cachedBuffer.toString("utf-8"):this._cachedBuffer}else{return this._cachedSource=this.original().source()}}buffer(){if(typeof this._cachedBuffer!=="undefined")return this._cachedBuffer;if(typeof this._cachedSource!=="undefined"){if(Buffer.isBuffer(this._cachedSource)){return this._cachedBuffer=this._cachedSource}return this._cachedBuffer=Buffer.from(this._cachedSource,"utf-8")}if(typeof this.original().buffer==="function"){return this._cachedBuffer=this.original().buffer()}const e=this.source();if(Buffer.isBuffer(e)){return this._cachedBuffer=e}return this._cachedBuffer=Buffer.from(e,"utf-8")}size(){if(typeof this._cachedSize!=="undefined")return this._cachedSize;if(typeof this._cachedSource!=="undefined"){return this._cachedSize=Buffer.byteLength(this._cachedSource)}if(typeof this._cachedBuffer!=="undefined"){return this._cachedSize=this._cachedBuffer.length}return this._cachedSize=this.original().size()}sourceAndMap(e){const t=e?JSON.stringify(e):"{}";let s=this._cachedMaps.get(t);if(s&&s.map===undefined){s.map=r(s.bufferedMap)}if(typeof this._cachedSource!=="undefined"){if(s===undefined){const s=this.original().map(e);this._cachedMaps.set(t,{map:s,bufferedMap:undefined});return{source:this._cachedSource,map:s}}else{return{source:this._cachedSource,map:s.map}}}else if(s!==undefined){return{source:this._cachedSource=this.original().source(),map:s.map}}else{const s=this.original().sourceAndMap(e);this._cachedSource=s.source;this._cachedMaps.set(t,{map:s.map,bufferedMap:undefined});return s}}map(e){const t=e?JSON.stringify(e):"{}";let s=this._cachedMaps.get(t);if(s!==undefined){if(s.map===undefined){s.map=r(s.bufferedMap)}return s.map}const n=this.original().map(e);this._cachedMaps.set(t,{map:n,bufferedMap:undefined});return n}updateHash(e){if(this._cachedHashUpdate!==undefined){for(const t of this._cachedHashUpdate)e.update(t);return}const t=[];let s=undefined;const n={update:e=>{if(typeof e==="string"&&e.length<10240){if(s===undefined){s=e}else{s+=e;if(s>102400){t.push(Buffer.from(s));s=undefined}}}else{if(s!==undefined){t.push(Buffer.from(s));s=undefined}t.push(e)}}};this.original().updateHash(n);if(s!==undefined){t.push(Buffer.from(s))}for(const s of t)e.update(s);this._cachedHashUpdate=t}}e.exports=CachedSource},32:(e,t,s)=>{"use strict";const n=s(604);class CompatSource extends n{static from(e){return e instanceof n?e:new CompatSource(e)}constructor(e){super();this._sourceLike=e}source(){return this._sourceLike.source()}buffer(){if(typeof this._sourceLike.buffer==="function"){return this._sourceLike.buffer()}return super.buffer()}size(){if(typeof this._sourceLike.size==="function"){return this._sourceLike.size()}return super.size()}map(e){if(typeof this._sourceLike.map==="function"){return this._sourceLike.map(e)}return super.map(e)}sourceAndMap(e){if(typeof this._sourceLike.sourceAndMap==="function"){return this._sourceLike.sourceAndMap(e)}return super.sourceAndMap(e)}updateHash(e){if(typeof this._sourceLike.updateHash==="function"){return this._sourceLike.updateHash(e)}if(typeof this._sourceLike.map==="function"){throw new Error("A Source-like object with a 'map' method must also provide an 'updateHash' method")}e.update(this.buffer())}}e.exports=CompatSource},147:(e,t,s)=>{"use strict";const n=s(604);const i=s(73);const{SourceNode:r,SourceMapConsumer:u}=s(241);const{SourceListMap:o,fromStringWithSourceMap:f}=s(524);const{getSourceAndMap:c,getMap:h}=s(904);const a=new WeakSet;class ConcatSource extends n{constructor(){super();this._children=[];for(let e=0;e{if(s===undefined){s=e}else if(Array.isArray(s)){s.push(e)}else{s=[typeof s==="string"?s:s.source(),e]}};const r=e=>{if(s===undefined){s=e}else if(Array.isArray(s)){s.push(e.source())}else{s=[typeof s==="string"?s:s.source(),e.source()]}};const u=()=>{if(Array.isArray(s)){const t=new i(s.join(""));a.add(t);e.push(t)}else if(typeof s==="string"){const t=new i(s);a.add(t);e.push(t)}else{e.push(s)}};for(const i of this._children){if(typeof i==="string"){if(t===undefined){t=i}else{t+=i}}else{if(t!==undefined){n(t);t=undefined}if(a.has(i)){r(i)}else{if(s!==undefined){u();s=undefined}e.push(i)}}}if(t!==undefined){n(t)}if(s!==undefined){u()}this._children=e;this._isOptimized=true}}e.exports=ConcatSource},470:(e,t,s)=>{"use strict";const n=s(604);const{SourceNode:i}=s(241);const{SourceListMap:r}=s(524);const{getSourceAndMap:u,getMap:o}=s(904);const f=/(?!$)[^\n\r;{}]*[\n\r;{}]*/g;function _splitCode(e){return e.match(f)||[]}class OriginalSource extends n{constructor(e,t){super();const s=Buffer.isBuffer(e);this._value=s?undefined:e;this._valueAsBuffer=s?e:undefined;this._name=t}getName(){return this._name}source(){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}return this._value}buffer(){if(this._valueAsBuffer===undefined){this._valueAsBuffer=Buffer.from(this._value,"utf-8")}return this._valueAsBuffer}map(e){return o(this,e)}sourceAndMap(e){return u(this,e)}node(e){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}const t=this._value;const s=this._name;const n=t.split("\n");const r=new i(null,null,null,n.map(function(t,r){let u=0;if(e&&e.columns===false){const e=t+(r!==n.length-1?"\n":"");return new i(r+1,0,s,e)}return new i(null,null,null,_splitCode(t+(r!==n.length-1?"\n":"")).map(function(e){if(/^\s*$/.test(e)){u+=e.length;return e}const t=new i(r+1,u,s,e);u+=e.length;return t}))}));r.setSourceContent(s,t);return r}listMap(e){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}return new r(this._value,this._name,this._value)}updateHash(e){if(this._valueAsBuffer===undefined){this._valueAsBuffer=Buffer.from(this._value,"utf-8")}e.update("OriginalSource");e.update(this._valueAsBuffer);e.update(this._name||"")}}e.exports=OriginalSource},478:(e,t,s)=>{"use strict";const n=s(604);const i=s(73);const{SourceNode:r}=s(241);const{getSourceAndMap:u,getMap:o}=s(904);const f=/\n(?=.|\s)/g;class PrefixSource extends n{constructor(e,t){super();this._source=typeof t==="string"||Buffer.isBuffer(t)?new i(t,true):t;this._prefix=e}getPrefix(){return this._prefix}original(){return this._source}source(){const e=this._source.source();const t=this._prefix;return t+e.replace(f,"\n"+t)}map(e){return o(this,e)}sourceAndMap(e){return u(this,e)}node(e){const t=this._source.node(e);const s=this._prefix;const n=[];const i=new r;t.walkSourceContents(function(e,t){i.setSourceContent(e,t)});let u=true;t.walk(function(e,t){const i=e.split(/(\n)/);for(let e=0;e{"use strict";const n=s(604);const{SourceNode:i}=s(241);const{SourceListMap:r}=s(524);class RawSource extends n{constructor(e,t=false){super();const s=Buffer.isBuffer(e);if(!s&&typeof e!=="string"){throw new TypeError("argument 'value' must be either string of Buffer")}this._valueIsBuffer=!t&&s;this._value=t&&s?undefined:e;this._valueAsBuffer=s?e:undefined}isBuffer(){return this._valueIsBuffer}source(){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}return this._value}buffer(){if(this._valueAsBuffer===undefined){this._valueAsBuffer=Buffer.from(this._value,"utf-8")}return this._valueAsBuffer}map(e){return null}node(e){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}return new i(null,null,null,this._value)}listMap(e){if(this._value===undefined){this._value=this._valueAsBuffer.toString("utf-8")}return new r(this._value)}updateHash(e){if(this._valueAsBuffer===undefined){this._valueAsBuffer=Buffer.from(this._value,"utf-8")}e.update("RawSource");e.update(this._valueAsBuffer)}}e.exports=RawSource},190:(e,t,s)=>{"use strict";const n=s(604);const{SourceNode:i}=s(241);const{getSourceAndMap:r,getMap:u,getNode:o,getListMap:f}=s(904);class Replacement{constructor(e,t,s,n,i){this.start=e;this.end=t;this.content=s;this.insertIndex=n;this.name=i}}class ReplaceSource extends n{constructor(e,t){super();this._source=e;this._name=t;this._replacements=[];this._isSorted=true}getName(){return this._name}getReplacements(){const e=Array.from(this._replacements);e.sort((e,t)=>{return e.insertIndex-t.insertIndex});return e}replace(e,t,s,n){if(typeof s!=="string")throw new Error("insertion must be a string, but is a "+typeof s);this._replacements.push(new Replacement(e,t,s,this._replacements.length,n));this._isSorted=false}insert(e,t,s){if(typeof t!=="string")throw new Error("insertion must be a string, but is a "+typeof t+": "+t);this._replacements.push(new Replacement(e,e-1,t,this._replacements.length,s));this._isSorted=false}source(){return this._replaceString(this._source.source())}map(e){if(this._replacements.length===0){return this._source.map(e)}return u(this,e)}sourceAndMap(e){if(this._replacements.length===0){return this._source.sourceAndMap(e)}return r(this,e)}original(){return this._source}_sortReplacements(){if(this._isSorted)return;this._replacements.sort(function(e,t){const s=t.end-e.end;if(s!==0)return s;const n=t.start-e.start;if(n!==0)return n;return t.insertIndex-e.insertIndex});this._isSorted=true}_replaceString(e){if(typeof e!=="string")throw new Error("str must be a string, but is a "+typeof e+": "+e);this._sortReplacements();const t=[e];this._replacements.forEach(function(e){const s=t.pop();const n=this._splitString(s,Math.floor(e.end+1));const i=this._splitString(n[0],Math.floor(e.start));t.push(n[1],e.content,i[0])},this);let s="";for(let e=t.length-1;e>=0;--e){s+=t[e]}return s}node(e){const t=o(this._source,e);if(this._replacements.length===0){return t}this._sortReplacements();const s=new ReplacementEnumerator(this._replacements);const n=[];let r=0;const u=Object.create(null);const f=Object.create(null);const c=new i;t.walkSourceContents(function(e,t){c.setSourceContent(e,t);u["$"+e]=t});const h=this._replaceInStringNode.bind(this,n,s,function getOriginalSource(e){const t="$"+e.source;let s=f[t];if(!s){const e=u[t];if(!e)return null;s=e.split("\n").map(function(e){return e+"\n"});f[t]=s}if(e.line>s.length)return null;const n=s[e.line-1];return n.substr(e.column)});t.walk(function(e,t){r=h(e,r,t)});const a=s.footer();if(a){n.push(a)}c.add(n);return c}listMap(e){let t=f(this._source,e);this._sortReplacements();let s=0;const n=this._replacements;let i=n.length-1;let r=0;t=t.mapGeneratedCode(function(e){const t=s+e.length;if(r>e.length){r-=e.length;e=""}else{if(r>0){e=e.substr(r);s+=r;r=0}let u="";while(i>=0&&n[i].start=0){u+=n[i].content;i--}if(u){t.add(u)}return t}_splitString(e,t){return t<=0?["",e]:[e.substr(0,t),e.substr(t)]}_replaceInStringNode(e,t,s,n,r,u){let o=undefined;do{let f=t.position-r;if(f<0){f=0}if(f>=n.length||t.done){if(t.emit){const t=new i(u.line,u.column,u.source,n,u.name);e.push(t)}return r+n.length}const c=u.column;let h;if(f>0){h=n.slice(0,f);if(o===undefined){o=s(u)}if(o&&o.length>=f&&o.startsWith(h)){u.column+=f;o=o.substr(f)}}const a=t.next();if(!a){if(f>0){const t=new i(u.line,c,u.source,h,u.name);e.push(t)}if(t.value){e.push(new i(u.line,u.column,u.source,t.value,u.name||t.name))}}n=n.substr(f);r+=f}while(true)}updateHash(e){this._sortReplacements();e.update("ReplaceSource");this._source.updateHash(e);e.update(this._name||"");for(const t of this._replacements){e.update(`${t.start}`);e.update(`${t.end}`);e.update(`${t.content}`);e.update(`${t.insertIndex}`);e.update(`${t.name}`)}}}class ReplacementEnumerator{constructor(e){this.replacements=e||[];this.index=this.replacements.length;this.done=false;this.emit=false;this.next()}next(){if(this.done)return true;if(this.emit){const e=this.replacements[this.index];const t=Math.floor(e.end+1);this.position=t;this.value=e.content;this.name=e.name}else{this.index--;if(this.index<0){this.done=true}else{const e=this.replacements[this.index];const t=Math.floor(e.start);this.position=t}}if(this.position<0)this.position=0;this.emit=!this.emit;return this.emit}footer(){if(!this.done&&!this.emit)this.next();if(this.done){return[]}else{let e="";for(let t=this.index;t>=0;t--){const s=this.replacements[t];e+=s.content}return e}}}e.exports=ReplaceSource},646:(e,t,s)=>{"use strict";const n=s(604);class SizeOnlySource extends n{constructor(e){super();this._size=e}_error(){return new Error("Content and Map of this Source is not available (only size() is supported)")}size(){return this._size}source(){throw this._error()}buffer(){throw this._error()}map(e){throw this._error()}updateHash(){throw this._error()}}e.exports=SizeOnlySource},604:e=>{"use strict";class Source{source(){throw new Error("Abstract")}buffer(){const e=this.source();if(Buffer.isBuffer(e))return e;return Buffer.from(e,"utf-8")}size(){return this.buffer().length}map(e){return null}sourceAndMap(e){return{source:this.source(),map:this.map(e)}}updateHash(e){throw new Error("Abstract")}}e.exports=Source},383:(e,t,s)=>{"use strict";const n=s(604);const{SourceNode:i,SourceMapConsumer:r}=s(241);const{SourceListMap:u,fromStringWithSourceMap:o}=s(524);const{getSourceAndMap:f,getMap:c}=s(904);const h=s(776);class SourceMapSource extends n{constructor(e,t,s,n,i,r){super();const u=Buffer.isBuffer(e);this._valueAsString=u?undefined:e;this._valueAsBuffer=u?e:undefined;this._name=t;this._hasSourceMap=!!s;const o=Buffer.isBuffer(s);const f=typeof s==="string";this._sourceMapAsObject=o||f?undefined:s;this._sourceMapAsString=f?s:undefined;this._sourceMapAsBuffer=o?s:undefined;this._hasOriginalSource=!!n;const c=Buffer.isBuffer(n);this._originalSourceAsString=c?undefined:n;this._originalSourceAsBuffer=c?n:undefined;this._hasInnerSourceMap=!!i;const h=Buffer.isBuffer(i);const a=typeof i==="string";this._innerSourceMapAsObject=h||a?undefined:i;this._innerSourceMapAsString=a?i:undefined;this._innerSourceMapAsBuffer=h?i:undefined;this._removeOriginalSource=r}_ensureValueBuffer(){if(this._valueAsBuffer===undefined){this._valueAsBuffer=Buffer.from(this._valueAsString,"utf-8")}}_ensureValueString(){if(this._valueAsString===undefined){this._valueAsString=this._valueAsBuffer.toString("utf-8")}}_ensureOriginalSourceBuffer(){if(this._originalSourceAsBuffer===undefined&&this._hasOriginalSource){this._originalSourceAsBuffer=Buffer.from(this._originalSourceAsString,"utf-8")}}_ensureOriginalSourceString(){if(this._originalSourceAsString===undefined&&this._hasOriginalSource){this._originalSourceAsString=this._originalSourceAsBuffer.toString("utf-8")}}_ensureInnerSourceMapObject(){if(this._innerSourceMapAsObject===undefined&&this._hasInnerSourceMap){this._ensureInnerSourceMapString();this._innerSourceMapAsObject=JSON.parse(this._innerSourceMapAsString)}}_ensureInnerSourceMapBuffer(){if(this._innerSourceMapAsBuffer===undefined&&this._hasInnerSourceMap){this._ensureInnerSourceMapString();this._innerSourceMapAsBuffer=Buffer.from(this._innerSourceMapAsString,"utf-8")}}_ensureInnerSourceMapString(){if(this._innerSourceMapAsString===undefined&&this._hasInnerSourceMap){if(this._innerSourceMapAsBuffer!==undefined){this._innerSourceMapAsString=this._innerSourceMapAsBuffer.toString("utf-8")}else{this._innerSourceMapAsString=JSON.stringify(this._innerSourceMapAsObject)}}}_ensureSourceMapObject(){if(this._sourceMapAsObject===undefined){this._ensureSourceMapString();this._sourceMapAsObject=JSON.parse(this._sourceMapAsString)}}_ensureSourceMapBuffer(){if(this._sourceMapAsBuffer===undefined){this._ensureSourceMapString();this._sourceMapAsBuffer=Buffer.from(this._sourceMapAsString,"utf-8")}}_ensureSourceMapString(){if(this._sourceMapAsString===undefined){if(this._sourceMapAsBuffer!==undefined){this._sourceMapAsString=this._sourceMapAsBuffer.toString("utf-8")}else{this._sourceMapAsString=JSON.stringify(this._sourceMapAsObject)}}}getArgsAsBuffers(){this._ensureValueBuffer();this._ensureSourceMapBuffer();this._ensureOriginalSourceBuffer();this._ensureInnerSourceMapBuffer();return[this._valueAsBuffer,this._name,this._sourceMapAsBuffer,this._originalSourceAsBuffer,this._innerSourceMapAsBuffer,this._removeOriginalSource]}source(){this._ensureValueString();return this._valueAsString}map(e){if(!this._hasInnerSourceMap){this._ensureSourceMapObject();return this._sourceMapAsObject}return c(this,e)}sourceAndMap(e){if(!this._hasInnerSourceMap){this._ensureValueString();this._ensureSourceMapObject();return{source:this._valueAsString,map:this._sourceMapAsObject}}return f(this,e)}node(e){this._ensureValueString();this._ensureSourceMapObject();this._ensureOriginalSourceString();let t=i.fromStringWithSourceMap(this._valueAsString,new r(this._sourceMapAsObject));t.setSourceContent(this._name,this._originalSourceAsString);if(this._hasInnerSourceMap){this._ensureInnerSourceMapObject();t=h(t,new r(this._innerSourceMapAsObject),this._name,this._removeOriginalSource)}return t}listMap(e){this._ensureValueString();this._ensureSourceMapObject();e=e||{};if(e.module===false)return new u(this._valueAsString,this._name,this._valueAsString);return o(this._valueAsString,this._sourceMapAsObject)}updateHash(e){this._ensureValueBuffer();this._ensureSourceMapBuffer();this._ensureOriginalSourceBuffer();this._ensureInnerSourceMapBuffer();e.update("SourceMapSource");e.update(this._valueAsBuffer);e.update(this._sourceMapAsBuffer);if(this._hasOriginalSource){e.update(this._originalSourceAsBuffer)}if(this._hasInnerSourceMap){e.update(this._innerSourceMapAsBuffer)}e.update(this._removeOriginalSource?"true":"false")}}e.exports=SourceMapSource},776:(e,t,s)=>{"use strict";const n=s(241).SourceNode;const i=s(241).SourceMapConsumer;const r=function(e,t,s,r){const u=new n;const o=[];const f={};const c={};const h={};const a={};t.eachMapping(function(e){(c[e.generatedLine]=c[e.generatedLine]||[]).push(e)},null,i.GENERATED_ORDER);const l=(e,t)=>{const s=c[e];let n=0;let i=s.length;while(n>1;if(s[e].generatedColumn<=t){n=e+1}else{i=e}}if(n===0)return undefined;return s[n-1]};e.walkSourceContents(function(e,t){f["$"+e]=t});const d=f["$"+s];const p=d?d.split("\n"):undefined;e.walk(function(e,i){if(i.source===s&&i.line&&c[i.line]){let s=l(i.line,i.column);if(s){let r=false;let f;let c;let l;const d=s.source;if(p&&d&&(f=p[s.generatedLine-1])&&((l=a[d])||(c=t.sourceContentFor(d,true)))){if(!l){l=a[d]=c.split("\n")}const e=l[s.originalLine-1];if(e){const t=i.column-s.generatedColumn;if(t>0){const n=f.slice(s.generatedColumn,i.column);const r=e.slice(s.originalColumn,s.originalColumn+t);if(n===r){s=Object.assign({},s,{originalColumn:s.originalColumn+t,generatedColumn:i.column,name:undefined})}}if(!s.name&&i.name){r=e.slice(s.originalColumn,s.originalColumn+i.name.length)===i.name}}}let _=s.source;if(_&&_!=="."){o.push(new n(s.originalLine,s.originalColumn,_,e,r?i.name:s.name));if(!("$"+_ in h)){h["$"+_]=true;const e=t.sourceContentFor(_,true);if(e){u.setSourceContent(_,e)}}return}}}if(r&&i.source===s||!i.source){o.push(e);return}const d=i.source;o.push(new n(i.line,i.column,d,e,i.name));if("$"+d in f){if(!("$"+d in h)){u.setSourceContent(d,f["$"+d]);delete f["$"+d]}}});u.add(o);return u};e.exports=r},904:(e,t,s)=>{"use strict";const{SourceNode:n,SourceMapConsumer:i}=s(241);const{SourceListMap:r,fromStringWithSourceMap:u}=s(524);t.getSourceAndMap=((e,t)=>{let s;let n;if(t&&t.columns===false){const i=e.listMap(t).toStringWithSourceMap({file:"x"});s=i.source;n=i.map}else{const i=e.node(t).toStringWithSourceMap({file:"x"});s=i.code;n=i.map.toJSON()}if(!n||!n.sources||n.sources.length===0)n=null;return{source:s,map:n}});t.getMap=((e,t)=>{let s;if(t&&t.columns===false){s=e.listMap(t).toStringWithSourceMap({file:"x"}).map}else{s=e.node(t).toStringWithSourceMap({file:"x"}).map.toJSON()}if(!s||!s.sources||s.sources.length===0)return null;return s});t.getNode=((e,t)=>{if(typeof e.node==="function"){return e.node(t)}else{const s=e.sourceAndMap(t);if(s.map){return n.fromStringWithSourceMap(s.source,new i(s.map))}else{return new n(null,null,null,s.source)}}});t.getListMap=((e,t)=>{if(typeof e.listMap==="function"){return e.listMap(t)}else{const s=e.sourceAndMap(t);if(s.map){return u(s.source,s.map)}else{return new r(s.source)}}})},890:(e,t,s)=>{const n=(e,s)=>{let n;Object.defineProperty(t,e,{get:()=>{if(s!==undefined){n=s();s=undefined}return n},configurable:true})};n("Source",()=>s(604));n("RawSource",()=>s(73));n("OriginalSource",()=>s(470));n("SourceMapSource",()=>s(383));n("CachedSource",()=>s(979));n("ConcatSource",()=>s(147));n("ReplaceSource",()=>s(190));n("PrefixSource",()=>s(478));n("SizeOnlySource",()=>s(646));n("CompatSource",()=>s(32))},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __webpack_require__(s){if(t[s]){return t[s].exports}var n=t[s]={exports:{}};var i=true;try{e[s](n,n.exports,__webpack_require__);i=false}finally{if(i)delete t[s]}return n.exports}__webpack_require__.ab=__dirname+"/";return __webpack_require__(890)})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack-sources2/package.json b/packages/next/compiled/webpack-sources2/package.json new file mode 100644 index 000000000000000..acd3193c9f72756 --- /dev/null +++ b/packages/next/compiled/webpack-sources2/package.json @@ -0,0 +1 @@ +{"name":"webpack-sources","main":"index.js","author":"Tobias Koppers @sokra","license":"MIT"} diff --git a/packages/next/compiled/webpack/LICENSE b/packages/next/compiled/webpack/LICENSE new file mode 100644 index 000000000000000..8c11fc7289b7546 --- /dev/null +++ b/packages/next/compiled/webpack/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/next/compiled/webpack/amd-define.js b/packages/next/compiled/webpack/amd-define.js new file mode 100644 index 000000000000000..344031058284d7b --- /dev/null +++ b/packages/next/compiled/webpack/amd-define.js @@ -0,0 +1,55 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 441: +/***/ ((module) => { + +module.exports = function() { + throw new Error("define cannot be used indirect"); +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(441); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/amd-options.js b/packages/next/compiled/webpack/amd-options.js new file mode 100644 index 000000000000000..d76e0b5881b747e --- /dev/null +++ b/packages/next/compiled/webpack/amd-options.js @@ -0,0 +1,54 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 929: +/***/ ((module) => { + +/* globals __webpack_amd_options__ */ +module.exports = __webpack_amd_options__; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(929); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/assert.js b/packages/next/compiled/webpack/assert.js new file mode 100644 index 000000000000000..432a19c8581b5b9 --- /dev/null +++ b/packages/next/compiled/webpack/assert.js @@ -0,0 +1,1276 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 992: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var objectAssign = __webpack_require__(594); + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: +// NB: The URL to the CommonJS spec is kept just for tradition. +// node-assert has evolved a lot since then, both in API and behavior. + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS 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. + +var util = __webpack_require__(353); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +// Expose a strict only variant of assert +function strict(value, message) { + if (!value) fail(value, true, message, '==', strict); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + + +/***/ }), + +/***/ 756: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(669).inherits + + +/***/ }), + +/***/ 262: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg instanceof Buffer; +} + + +/***/ }), + +/***/ 353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(262); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(756); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + + +/***/ }), + +/***/ 594: +/***/ ((module) => { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(992); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/browser.js b/packages/next/compiled/webpack/browser.js new file mode 100644 index 000000000000000..4d9bd93f84a5b44 --- /dev/null +++ b/packages/next/compiled/webpack/browser.js @@ -0,0 +1,101 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 713: +/***/ ((__unused_webpack_module, exports) => { + +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +exports.homedir = function () { + return '/' +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(713); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/browser1.js b/packages/next/compiled/webpack/browser1.js new file mode 100644 index 000000000000000..fd3502f8bd41e29 --- /dev/null +++ b/packages/next/compiled/webpack/browser1.js @@ -0,0 +1,236 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 940: +/***/ ((module) => { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(940); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/bundle4.js b/packages/next/compiled/webpack/bundle4.js new file mode 100644 index 000000000000000..5e3c4e6450b1136 --- /dev/null +++ b/packages/next/compiled/webpack/bundle4.js @@ -0,0 +1,106014 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 90601: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"$id\":\"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\"description\":\"Meta-schema for $data reference (JSON Schema extension proposal)\",\"type\":\"object\",\"required\":[\"$data\"],\"properties\":{\"$data\":{\"type\":\"string\",\"anyOf\":[{\"format\":\"relative-json-pointer\"},{\"format\":\"json-pointer\"}]}},\"additionalProperties\":false}"); + +/***/ }), + +/***/ 98938: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"$id\":\"http://json-schema.org/draft-07/schema#\",\"title\":\"Core schema meta-schema\",\"definitions\":{\"schemaArray\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#\"}},\"nonNegativeInteger\":{\"type\":\"integer\",\"minimum\":0},\"nonNegativeIntegerDefault0\":{\"allOf\":[{\"$ref\":\"#/definitions/nonNegativeInteger\"},{\"default\":0}]},\"simpleTypes\":{\"enum\":[\"array\",\"boolean\",\"integer\",\"null\",\"number\",\"object\",\"string\"]},\"stringArray\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"uniqueItems\":true,\"default\":[]}},\"type\":[\"object\",\"boolean\"],\"properties\":{\"$id\":{\"type\":\"string\",\"format\":\"uri-reference\"},\"$schema\":{\"type\":\"string\",\"format\":\"uri\"},\"$ref\":{\"type\":\"string\",\"format\":\"uri-reference\"},\"$comment\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"default\":true,\"readOnly\":{\"type\":\"boolean\",\"default\":false},\"examples\":{\"type\":\"array\",\"items\":true},\"multipleOf\":{\"type\":\"number\",\"exclusiveMinimum\":0},\"maximum\":{\"type\":\"number\"},\"exclusiveMaximum\":{\"type\":\"number\"},\"minimum\":{\"type\":\"number\"},\"exclusiveMinimum\":{\"type\":\"number\"},\"maxLength\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minLength\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"pattern\":{\"type\":\"string\",\"format\":\"regex\"},\"additionalItems\":{\"$ref\":\"#\"},\"items\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/schemaArray\"}],\"default\":true},\"maxItems\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minItems\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"uniqueItems\":{\"type\":\"boolean\",\"default\":false},\"contains\":{\"$ref\":\"#\"},\"maxProperties\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minProperties\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"required\":{\"$ref\":\"#/definitions/stringArray\"},\"additionalProperties\":{\"$ref\":\"#\"},\"definitions\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"properties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"patternProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"propertyNames\":{\"format\":\"regex\"},\"default\":{}},\"dependencies\":{\"type\":\"object\",\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/stringArray\"}]}},\"propertyNames\":{\"$ref\":\"#\"},\"const\":true,\"enum\":{\"type\":\"array\",\"items\":true,\"minItems\":1,\"uniqueItems\":true},\"type\":{\"anyOf\":[{\"$ref\":\"#/definitions/simpleTypes\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/simpleTypes\"},\"minItems\":1,\"uniqueItems\":true}]},\"format\":{\"type\":\"string\"},\"contentMediaType\":{\"type\":\"string\"},\"contentEncoding\":{\"type\":\"string\"},\"if\":{\"$ref\":\"#\"},\"then\":{\"$ref\":\"#\"},\"else\":{\"$ref\":\"#\"},\"allOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"anyOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"oneOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"not\":{\"$ref\":\"#\"}},\"default\":true}"); + +/***/ }), + +/***/ 25916: +/***/ ((module) => { + +"use strict"; +module.exports = {"version":"4.2.1"}; + +/***/ }), + +/***/ 35464: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"4.3.0"}; + +/***/ }), + +/***/ 11840: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"additionalProperties\":false,\"definitions\":{\"file-conditions\":{\"anyOf\":[{\"instanceof\":\"RegExp\"},{\"type\":\"string\"}]}},\"properties\":{\"test\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"},{\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"}]},\"type\":\"array\"}]},\"include\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"},{\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"}]},\"type\":\"array\"}]},\"exclude\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"},{\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/file-conditions\"}]},\"type\":\"array\"}]},\"chunkFilter\":{\"instanceof\":\"Function\"},\"cache\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"string\"}]},\"cacheKeys\":{\"instanceof\":\"Function\"},\"parallel\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"integer\"}]},\"sourceMap\":{\"type\":\"boolean\"},\"minify\":{\"instanceof\":\"Function\"},\"terserOptions\":{\"additionalProperties\":true,\"type\":\"object\"},\"extractComments\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"string\"},{\"instanceof\":\"RegExp\"},{\"instanceof\":\"Function\"},{\"additionalProperties\":false,\"properties\":{\"condition\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"string\"},{\"instanceof\":\"RegExp\"},{\"instanceof\":\"Function\"}]},\"filename\":{\"anyOf\":[{\"type\":\"string\"},{\"instanceof\":\"Function\"}]},\"banner\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"string\"},{\"instanceof\":\"Function\"}]}},\"type\":\"object\"}]},\"warningsFilter\":{\"instanceof\":\"Function\"}},\"type\":\"object\"}"); + +/***/ }), + +/***/ 92203: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"name\":\"terser\",\"description\":\"JavaScript parser, mangler/compressor and beautifier toolkit for ES6+\",\"homepage\":\"https://terser.org\",\"author\":\"Mihai Bazon (http://lisperator.net/)\",\"license\":\"BSD-2-Clause\",\"version\":\"4.8.0\",\"engines\":{\"node\":\">=6.0.0\"},\"maintainers\":[\"Fábio Santos \"],\"repository\":\"https://github.com/terser/terser\",\"main\":\"dist/bundle.min.js\",\"types\":\"tools/terser.d.ts\",\"bin\":{\"terser\":\"bin/terser\"},\"files\":[\"bin\",\"dist\",\"tools\",\"LICENSE\",\"README.md\",\"CHANGELOG.md\",\"PATRONS.md\"],\"dependencies\":{\"commander\":\"^2.20.0\",\"source-map\":\"~0.6.1\",\"source-map-support\":\"~0.5.12\"},\"devDependencies\":{\"acorn\":\"^7.1.1\",\"astring\":\"^1.4.1\",\"eslint\":\"^6.3.0\",\"eslump\":\"^2.0.0\",\"mocha\":\"^7.1.2\",\"mochallel\":\"^2.0.0\",\"pre-commit\":\"^1.2.2\",\"rimraf\":\"^3.0.0\",\"rollup\":\"2.0.6\",\"rollup-plugin-terser\":\"5.3.0\",\"semver\":\"^7.1.3\"},\"scripts\":{\"test\":\"npm run build -- --configTest && node test/run-tests.js\",\"test:compress\":\"npm run build -- --configTest && node test/compress.js\",\"test:mocha\":\"npm run build -- --configTest && node test/mocha.js\",\"lint\":\"eslint lib\",\"lint-fix\":\"eslint --fix lib\",\"build\":\"rimraf dist/* && rollup --config --silent\",\"prepare\":\"npm run build\",\"postversion\":\"echo 'Remember to update the changelog!'\"},\"keywords\":[\"uglify\",\"terser\",\"uglify-es\",\"uglify-js\",\"minify\",\"minifier\",\"javascript\",\"ecmascript\",\"es5\",\"es6\",\"es7\",\"es8\",\"es2015\",\"es2016\",\"es2017\",\"async\",\"await\"],\"eslintConfig\":{\"parserOptions\":{\"sourceType\":\"module\"},\"env\":{\"es6\":true},\"globals\":{\"describe\":false,\"it\":false,\"require\":false,\"global\":false,\"process\":false},\"rules\":{\"brace-style\":[\"error\",\"1tbs\",{\"allowSingleLine\":true}],\"quotes\":[\"error\",\"double\",\"avoid-escape\"],\"no-debugger\":\"error\",\"no-undef\":\"error\",\"no-unused-vars\":[\"error\",{\"varsIgnorePattern\":\"^_$\"}],\"no-tabs\":\"error\",\"semi\":[\"error\",\"always\"],\"no-extra-semi\":\"error\",\"no-irregular-whitespace\":\"error\",\"space-before-blocks\":[\"error\",\"always\"]}},\"pre-commit\":[\"lint-fix\",\"test\"]}"); + +/***/ }), + +/***/ 9122: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"1.4.4"}; + +/***/ }), + +/***/ 11335: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"4.0.3"}; + +/***/ }), + +/***/ 71618: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"4.44.1"}; + +/***/ }), + +/***/ 37863: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"definitions\":{\"ArrayOfStringOrStringArrayValues\":{\"type\":\"array\",\"items\":{\"description\":\"string or array of strings\",\"anyOf\":[{\"type\":\"string\",\"minLength\":1},{\"type\":\"array\",\"items\":{\"description\":\"A non-empty string\",\"type\":\"string\",\"minLength\":1}}]}},\"ArrayOfStringValues\":{\"type\":\"array\",\"items\":{\"description\":\"A non-empty string\",\"type\":\"string\",\"minLength\":1}},\"Entry\":{\"anyOf\":[{\"$ref\":\"#/definitions/EntryDynamic\"},{\"$ref\":\"#/definitions/EntryStatic\"}]},\"EntryDynamic\":{\"description\":\"A Function returning an entry object, an entry string, an entry array or a promise to these things.\",\"instanceof\":\"Function\",\"tsType\":\"(() => EntryStatic | Promise)\"},\"EntryItem\":{\"oneOf\":[{\"description\":\"An entry point without name. The string is resolved to a module which is loaded upon startup.\",\"type\":\"string\",\"minLength\":1},{\"description\":\"An entry point without name. All modules are loaded upon startup. The last one is exported.\",\"anyOf\":[{\"$ref\":\"#/definitions/NonEmptyArrayOfUniqueStringValues\"}]}]},\"EntryObject\":{\"description\":\"Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.\",\"type\":\"object\",\"additionalProperties\":{\"description\":\"An entry point with name\",\"oneOf\":[{\"description\":\"The string is resolved to a module which is loaded upon startup.\",\"type\":\"string\",\"minLength\":1},{\"description\":\"All modules are loaded upon startup. The last one is exported.\",\"anyOf\":[{\"$ref\":\"#/definitions/NonEmptyArrayOfUniqueStringValues\"}]}]},\"minProperties\":1},\"EntryStatic\":{\"oneOf\":[{\"$ref\":\"#/definitions/EntryObject\"},{\"$ref\":\"#/definitions/EntryItem\"}]},\"ExternalItem\":{\"anyOf\":[{\"description\":\"An exact matched dependency becomes external. The same string is used as external dependency.\",\"type\":\"string\"},{\"description\":\"If an dependency matches exactly a property of the object, the property value is used as dependency.\",\"type\":\"object\",\"additionalProperties\":{\"description\":\"The dependency used for the external\",\"anyOf\":[{\"type\":\"string\"},{\"type\":\"object\"},{\"$ref\":\"#/definitions/ArrayOfStringValues\"},{\"type\":\"boolean\"}]}},{\"description\":\"Every matched dependency becomes external.\",\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]},\"Externals\":{\"anyOf\":[{\"description\":\"`function(context, request, callback(err, result))` The function is called on each dependency.\",\"instanceof\":\"Function\",\"tsType\":\"((context: string, request: string, callback: (err?: Error, result?: string) => void) => void)\"},{\"$ref\":\"#/definitions/ExternalItem\"},{\"type\":\"array\",\"items\":{\"description\":\"External configuration\",\"anyOf\":[{\"description\":\"`function(context, request, callback(err, result))` The function is called on each dependency.\",\"instanceof\":\"Function\",\"tsType\":\"((context: string, request: string, callback: (err?: Error, result?: string) => void) => void)\"},{\"$ref\":\"#/definitions/ExternalItem\"}]}}]},\"FilterItemTypes\":{\"anyOf\":[{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"string\"},{\"instanceof\":\"Function\",\"tsType\":\"((value: string) => boolean)\"}]},\"FilterTypes\":{\"anyOf\":[{\"$ref\":\"#/definitions/FilterItemTypes\"},{\"type\":\"array\",\"items\":{\"description\":\"Rule to filter\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterItemTypes\"}]}}]},\"LibraryCustomUmdObject\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"amd\":{\"description\":\"Name of the exposed AMD library in the UMD\",\"type\":\"string\"},\"commonjs\":{\"description\":\"Name of the exposed commonjs export in the UMD\",\"type\":\"string\"},\"root\":{\"description\":\"Name of the property exposed globally by a UMD library\",\"anyOf\":[{\"type\":\"string\"},{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]}}},\"ModuleOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"defaultRules\":{\"description\":\"An array of rules applied by default for modules.\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetRules\"}]},\"exprContextCritical\":{\"description\":\"Enable warnings for full dynamic dependencies\",\"type\":\"boolean\"},\"exprContextRecursive\":{\"description\":\"Enable recursive directory lookup for full dynamic dependencies\",\"type\":\"boolean\"},\"exprContextRegExp\":{\"description\":\"Sets the default regular expression for full dynamic dependencies\",\"anyOf\":[{\"type\":\"boolean\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]},\"exprContextRequest\":{\"description\":\"Set the default request for full dynamic dependencies\",\"type\":\"string\"},\"noParse\":{\"description\":\"Don't parse files matching. It's matched against the full resolved request.\",\"anyOf\":[{\"type\":\"array\",\"items\":{\"description\":\"A regular expression, when matched the module is not parsed\",\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},\"minItems\":1},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"array\",\"items\":{\"description\":\"An absolute path, when the module starts with this path it is not parsed\",\"type\":\"string\",\"absolutePath\":true},\"minItems\":1},{\"type\":\"string\",\"absolutePath\":true}]},\"rules\":{\"description\":\"An array of rules applied for modules.\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetRules\"}]},\"strictExportPresence\":{\"description\":\"Emit errors instead of warnings when imported names don't exist in imported module\",\"type\":\"boolean\"},\"strictThisContextOnImports\":{\"description\":\"Handle the this context correctly according to the spec for namespace objects\",\"type\":\"boolean\"},\"unknownContextCritical\":{\"description\":\"Enable warnings when using the require function in a not statically analyse-able way\",\"type\":\"boolean\"},\"unknownContextRecursive\":{\"description\":\"Enable recursive directory lookup when using the require function in a not statically analyse-able way\",\"type\":\"boolean\"},\"unknownContextRegExp\":{\"description\":\"Sets the regular expression when using the require function in a not statically analyse-able way\",\"anyOf\":[{\"type\":\"boolean\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]},\"unknownContextRequest\":{\"description\":\"Sets the request when using the require function in a not statically analyse-able way\",\"type\":\"string\"},\"unsafeCache\":{\"description\":\"Cache the resolving of module requests\",\"anyOf\":[{\"type\":\"boolean\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"wrappedContextCritical\":{\"description\":\"Enable warnings for partial dynamic dependencies\",\"type\":\"boolean\"},\"wrappedContextRecursive\":{\"description\":\"Enable recursive directory lookup for partial dynamic dependencies\",\"type\":\"boolean\"},\"wrappedContextRegExp\":{\"description\":\"Set the inner regular expression for partial dynamic dependencies\",\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}}},\"NodeOptions\":{\"type\":\"object\",\"additionalProperties\":{\"description\":\"Include a polyfill for the node.js module\",\"enum\":[false,true,\"mock\",\"empty\"]},\"properties\":{\"Buffer\":{\"description\":\"Include a polyfill for the 'Buffer' variable\",\"enum\":[false,true,\"mock\"]},\"__dirname\":{\"description\":\"Include a polyfill for the '__dirname' variable\",\"enum\":[false,true,\"mock\"]},\"__filename\":{\"description\":\"Include a polyfill for the '__filename' variable\",\"enum\":[false,true,\"mock\"]},\"console\":{\"description\":\"Include a polyfill for the 'console' variable\",\"enum\":[false,true,\"mock\"]},\"global\":{\"description\":\"Include a polyfill for the 'global' variable\",\"type\":\"boolean\"},\"process\":{\"description\":\"Include a polyfill for the 'process' variable\",\"enum\":[false,true,\"mock\"]}}},\"NonEmptyArrayOfUniqueStringValues\":{\"description\":\"A non-empty array of non-empty strings\",\"type\":\"array\",\"items\":{\"description\":\"A non-empty string\",\"type\":\"string\",\"minLength\":1},\"minItems\":1,\"uniqueItems\":true},\"OptimizationOptions\":{\"description\":\"Enables/Disables integrated optimizations\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"checkWasmTypes\":{\"description\":\"Check for incompatible wasm types when importing/exporting from/to ESM\",\"type\":\"boolean\"},\"chunkIds\":{\"description\":\"Define the algorithm to choose chunk ids (named: readable ids for better debugging, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin)\",\"enum\":[\"natural\",\"named\",\"size\",\"total-size\",false]},\"concatenateModules\":{\"description\":\"Concatenate modules when possible to generate less modules, more efficient code and enable more optimizations by the minimizer\",\"type\":\"boolean\"},\"flagIncludedChunks\":{\"description\":\"Also flag chunks as loaded which contain a subset of the modules\",\"type\":\"boolean\"},\"hashedModuleIds\":{\"description\":\"Use hashed module id instead module identifiers for better long term caching (deprecated, used moduleIds: hashed instead)\",\"type\":\"boolean\"},\"mangleWasmImports\":{\"description\":\"Reduce size of WASM by changing imports to shorter strings.\",\"type\":\"boolean\"},\"mergeDuplicateChunks\":{\"description\":\"Merge chunks which contain the same modules\",\"type\":\"boolean\"},\"minimize\":{\"description\":\"Enable minimizing the output. Uses optimization.minimizer.\",\"type\":\"boolean\"},\"minimizer\":{\"description\":\"Minimizer(s) to use for minimizing the output\",\"type\":\"array\",\"items\":{\"description\":\"Plugin of type object or instanceof Function\",\"anyOf\":[{\"$ref\":\"#/definitions/WebpackPluginInstance\"},{\"$ref\":\"#/definitions/WebpackPluginFunction\"}]}},\"moduleIds\":{\"description\":\"Define the algorithm to choose module ids (natural: numeric ids in order of usage, named: readable ids for better debugging, hashed: short hashes as ids for better long term caching, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin)\",\"enum\":[\"natural\",\"named\",\"hashed\",\"size\",\"total-size\",false]},\"namedChunks\":{\"description\":\"Use readable chunk identifiers for better debugging (deprecated, used chunkIds: named instead)\",\"type\":\"boolean\"},\"namedModules\":{\"description\":\"Use readable module identifiers for better debugging (deprecated, used moduleIds: named instead)\",\"type\":\"boolean\"},\"noEmitOnErrors\":{\"description\":\"Avoid emitting assets when errors occur\",\"type\":\"boolean\"},\"nodeEnv\":{\"description\":\"Set process.env.NODE_ENV to a specific value\",\"anyOf\":[{\"enum\":[false]},{\"type\":\"string\"}]},\"occurrenceOrder\":{\"description\":\"Figure out a order of modules which results in the smallest initial bundle\",\"type\":\"boolean\"},\"portableRecords\":{\"description\":\"Generate records with relative paths to be able to move the context folder\",\"type\":\"boolean\"},\"providedExports\":{\"description\":\"Figure out which exports are provided by modules to generate more efficient code\",\"type\":\"boolean\"},\"removeAvailableModules\":{\"description\":\"Removes modules from chunks when these modules are already included in all parents\",\"type\":\"boolean\"},\"removeEmptyChunks\":{\"description\":\"Remove chunks which are empty\",\"type\":\"boolean\"},\"runtimeChunk\":{\"description\":\"Create an additional chunk which contains only the webpack runtime and chunk hash maps\",\"oneOf\":[{\"type\":\"boolean\"},{\"enum\":[\"single\",\"multiple\"]},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"name\":{\"description\":\"The name or name factory for the runtime chunks\",\"oneOf\":[{\"type\":\"string\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]}}}]},\"sideEffects\":{\"description\":\"Skip over modules which are flagged to contain no side effects when exports are not used\",\"type\":\"boolean\"},\"splitChunks\":{\"description\":\"Optimize duplication and caching by splitting chunks by shared modules and cache group\",\"oneOf\":[{\"enum\":[false]},{\"$ref\":\"#/definitions/OptimizationSplitChunksOptions\"}]},\"usedExports\":{\"description\":\"Figure out which exports are used by modules to mangle export names, omit unused exports and generate more efficient code\",\"type\":\"boolean\"}}},\"OptimizationSplitChunksOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"automaticNameDelimiter\":{\"description\":\"Sets the name delimiter for created chunks\",\"type\":\"string\",\"minLength\":1},\"automaticNameMaxLength\":{\"description\":\"Sets the max length for the name of a created chunk\",\"type\":\"number\",\"minimum\":1},\"cacheGroups\":{\"description\":\"Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks)\",\"type\":\"object\",\"additionalProperties\":{\"description\":\"Configuration for a cache group\",\"anyOf\":[{\"enum\":[false]},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"automaticNameDelimiter\":{\"description\":\"Sets the name delimiter for created chunks\",\"type\":\"string\",\"minLength\":1},\"automaticNameMaxLength\":{\"description\":\"Sets the max length for the name of a created chunk\",\"type\":\"number\",\"minimum\":1},\"automaticNamePrefix\":{\"description\":\"Sets the name prefix for created chunks\",\"type\":\"string\"},\"chunks\":{\"description\":\"Select chunks for determining cache group content (defaults to \\\"initial\\\", \\\"initial\\\" and \\\"all\\\" requires adding these chunks to the HTML)\",\"oneOf\":[{\"enum\":[\"initial\",\"async\",\"all\"]},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"enforce\":{\"description\":\"Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group\",\"type\":\"boolean\"},\"enforceSizeThreshold\":{\"description\":\"Size threshold at which splitting is enforced and other restrictions (maxAsyncRequests, maxInitialRequests) are ignored.\",\"type\":\"number\"},\"filename\":{\"description\":\"Sets the template for the filename for created chunks (Only works for initial chunks)\",\"type\":\"string\",\"minLength\":1},\"maxAsyncRequests\":{\"description\":\"Maximum number of requests which are accepted for on-demand loading\",\"type\":\"number\",\"minimum\":1},\"maxInitialRequests\":{\"description\":\"Maximum number of initial chunks which are accepted for an entry point\",\"type\":\"number\",\"minimum\":1},\"maxSize\":{\"description\":\"Maximal size hint for the created chunks\",\"type\":\"number\",\"minimum\":0},\"minChunks\":{\"description\":\"Minimum number of times a module has to be duplicated until it's considered for splitting\",\"type\":\"number\",\"minimum\":1},\"minSize\":{\"description\":\"Minimal size for the created chunk\",\"type\":\"number\",\"minimum\":0},\"name\":{\"description\":\"Give chunks for this cache group a name (chunks with equal name are merged)\",\"oneOf\":[{\"type\":\"boolean\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\"}]},\"priority\":{\"description\":\"Priority of this cache group\",\"type\":\"number\"},\"reuseExistingChunk\":{\"description\":\"Try to reuse existing chunk (with name) when it has matching modules\",\"type\":\"boolean\"},\"test\":{\"description\":\"Assign modules to a cache group\",\"oneOf\":[{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]}}}]},\"not\":{\"description\":\"Using the cacheGroup shorthand syntax with a cache group named 'test' is a potential config error\\nDid you intent to define a cache group with a test instead?\\ncacheGroups: {\\n : {\\n test: ...\\n }\\n}\",\"type\":\"object\",\"additionalProperties\":true,\"properties\":{\"test\":{\"description\":\"The test property is a cache group name, but using the test option of the cache group could be intended instead\",\"anyOf\":[{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]}},\"required\":[\"test\"]}},\"chunks\":{\"description\":\"Select chunks for determining shared modules (defaults to \\\"async\\\", \\\"initial\\\" and \\\"all\\\" requires adding these chunks to the HTML)\",\"oneOf\":[{\"enum\":[\"initial\",\"async\",\"all\"]},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"enforceSizeThreshold\":{\"description\":\"Size threshold at which splitting is enforced and other restrictions (maxAsyncRequests, maxInitialRequests) are ignored.\",\"type\":\"number\"},\"fallbackCacheGroup\":{\"description\":\"Options for modules not selected by any other cache group\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"automaticNameDelimiter\":{\"description\":\"Sets the name delimiter for created chunks\",\"type\":\"string\",\"minLength\":1},\"maxSize\":{\"description\":\"Maximal size hint for the created chunks\",\"type\":\"number\",\"minimum\":0},\"minSize\":{\"description\":\"Minimal size for the created chunk\",\"type\":\"number\",\"minimum\":0}}},\"filename\":{\"description\":\"Sets the template for the filename for created chunks (Only works for initial chunks)\",\"type\":\"string\",\"minLength\":1},\"hidePathInfo\":{\"description\":\"Prevents exposing path info when creating names for parts splitted by maxSize\",\"type\":\"boolean\"},\"maxAsyncRequests\":{\"description\":\"Maximum number of requests which are accepted for on-demand loading\",\"type\":\"number\",\"minimum\":1},\"maxInitialRequests\":{\"description\":\"Maximum number of initial chunks which are accepted for an entry point\",\"type\":\"number\",\"minimum\":1},\"maxSize\":{\"description\":\"Maximal size hint for the created chunks\",\"type\":\"number\",\"minimum\":0},\"minChunks\":{\"description\":\"Minimum number of times a module has to be duplicated until it's considered for splitting\",\"type\":\"number\",\"minimum\":1},\"minSize\":{\"description\":\"Minimal size for the created chunks\",\"type\":\"number\",\"minimum\":0},\"name\":{\"description\":\"Give chunks created a name (chunks with equal name are merged)\",\"oneOf\":[{\"type\":\"boolean\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\"}]}}},\"OutputOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"auxiliaryComment\":{\"description\":\"Add a comment in the UMD wrapper.\",\"anyOf\":[{\"description\":\"Append the same comment above each import style.\",\"type\":\"string\"},{\"description\":\"Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"amd\":{\"description\":\"Set comment for `amd` section in UMD\",\"type\":\"string\"},\"commonjs\":{\"description\":\"Set comment for `commonjs` (exports) section in UMD\",\"type\":\"string\"},\"commonjs2\":{\"description\":\"Set comment for `commonjs2` (module.exports) section in UMD\",\"type\":\"string\"},\"root\":{\"description\":\"Set comment for `root` (global variable) section in UMD\",\"type\":\"string\"}}}]},\"chunkCallbackName\":{\"description\":\"The callback function name used by webpack for loading of chunks in WebWorkers.\",\"type\":\"string\"},\"chunkFilename\":{\"description\":\"The filename of non-entry chunks as relative path inside the `output.path` directory.\",\"type\":\"string\",\"absolutePath\":false},\"chunkLoadTimeout\":{\"description\":\"Number of milliseconds before chunk request expires\",\"type\":\"number\"},\"crossOriginLoading\":{\"description\":\"This option enables cross-origin loading of chunks.\",\"enum\":[false,\"anonymous\",\"use-credentials\"]},\"devtoolFallbackModuleFilenameTemplate\":{\"description\":\"Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.\",\"anyOf\":[{\"type\":\"string\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"devtoolLineToLine\":{\"description\":\"Enable line to line mapped mode for all/specified modules. Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. It’s a performance optimization. Only use it if your performance need to be better and you are sure that input lines match which generated lines.\",\"anyOf\":[{\"description\":\"`true` enables it for all modules (not recommended)\",\"type\":\"boolean\"},{\"description\":\"An object similar to `module.loaders` enables it for specific files.\",\"type\":\"object\"}]},\"devtoolModuleFilenameTemplate\":{\"description\":\"Filename template string of function for the sources array in a generated SourceMap.\",\"anyOf\":[{\"type\":\"string\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"devtoolNamespace\":{\"description\":\"Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.\",\"type\":\"string\"},\"filename\":{\"description\":\"Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.\",\"anyOf\":[{\"type\":\"string\",\"absolutePath\":false},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"futureEmitAssets\":{\"description\":\"Use the future version of asset emitting logic, which allows freeing memory of assets after emitting. It could break plugins which assume that assets are still readable after emitting. Will be the new default in the next major version.\",\"type\":\"boolean\"},\"globalObject\":{\"description\":\"An expression which is used to address the global object/scope in runtime code\",\"type\":\"string\",\"minLength\":1},\"hashDigest\":{\"description\":\"Digest type used for the hash\",\"type\":\"string\"},\"hashDigestLength\":{\"description\":\"Number of chars which are used for the hash\",\"type\":\"number\",\"minimum\":1},\"hashFunction\":{\"description\":\"Algorithm used for generation the hash (see node.js crypto package)\",\"anyOf\":[{\"type\":\"string\",\"minLength\":1},{\"instanceof\":\"Function\",\"tsType\":\"import('../lib/util/createHash').HashConstructor\"}]},\"hashSalt\":{\"description\":\"Any string which is added to the hash to salt it\",\"type\":\"string\",\"minLength\":1},\"hotUpdateChunkFilename\":{\"description\":\"The filename of the Hot Update Chunks. They are inside the output.path directory.\",\"type\":\"string\",\"absolutePath\":false},\"hotUpdateFunction\":{\"description\":\"The JSONP function used by webpack for async loading of hot update chunks.\",\"type\":\"string\"},\"hotUpdateMainFilename\":{\"description\":\"The filename of the Hot Update Main File. It is inside the `output.path` directory.\",\"anyOf\":[{\"type\":\"string\",\"absolutePath\":false},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"jsonpFunction\":{\"description\":\"The JSONP function used by webpack for async loading of chunks.\",\"type\":\"string\"},\"jsonpScriptType\":{\"description\":\"This option enables loading async chunks via a custom script type, such as script type=\\\"module\\\"\",\"enum\":[false,\"text/javascript\",\"module\"]},\"library\":{\"description\":\"If set, export the bundle as library. `output.library` is the name.\",\"anyOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"description\":\"A part of the library name\",\"type\":\"string\"}},{\"$ref\":\"#/definitions/LibraryCustomUmdObject\"}]},\"libraryExport\":{\"description\":\"Specify which export should be exposed as library\",\"anyOf\":[{\"type\":\"string\"},{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"libraryTarget\":{\"description\":\"Type of library\",\"enum\":[\"var\",\"assign\",\"this\",\"window\",\"self\",\"global\",\"commonjs\",\"commonjs2\",\"commonjs-module\",\"amd\",\"amd-require\",\"umd\",\"umd2\",\"jsonp\",\"system\"]},\"path\":{\"description\":\"The output directory as **absolute path** (required).\",\"type\":\"string\",\"absolutePath\":true},\"pathinfo\":{\"description\":\"Include comments with information about the modules.\",\"type\":\"boolean\"},\"publicPath\":{\"description\":\"The `publicPath` specifies the public URL address of the output files when referenced in a browser.\",\"anyOf\":[{\"type\":\"string\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"}]},\"sourceMapFilename\":{\"description\":\"The filename of the SourceMaps for the JavaScript files. They are inside the `output.path` directory.\",\"type\":\"string\",\"absolutePath\":false},\"sourcePrefix\":{\"description\":\"Prefixes every line of the source in the bundle with this string.\",\"type\":\"string\"},\"strictModuleExceptionHandling\":{\"description\":\"Handles exceptions in module loading correctly at a performance cost.\",\"type\":\"boolean\"},\"umdNamedDefine\":{\"description\":\"If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.\",\"type\":\"boolean\"},\"webassemblyModuleFilename\":{\"description\":\"The filename of WebAssembly modules as relative path inside the `output.path` directory.\",\"type\":\"string\",\"absolutePath\":false}}},\"PerformanceOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"assetFilter\":{\"description\":\"Filter function to select assets that are checked\",\"instanceof\":\"Function\",\"tsType\":\"Function\"},\"hints\":{\"description\":\"Sets the format of the hints: warnings, errors or nothing at all\",\"enum\":[false,\"warning\",\"error\"]},\"maxAssetSize\":{\"description\":\"Filesize limit (in bytes) when exceeded, that webpack will provide performance hints\",\"type\":\"number\"},\"maxEntrypointSize\":{\"description\":\"Total size of an entry point (in bytes)\",\"type\":\"number\"}}},\"ResolveOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"alias\":{\"description\":\"Redirect module requests\",\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":{\"description\":\"New request\",\"type\":\"string\"}},{\"type\":\"array\",\"items\":{\"description\":\"Alias configuration\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"alias\":{\"description\":\"New request\",\"type\":\"string\"},\"name\":{\"description\":\"Request to be redirected\",\"type\":\"string\"},\"onlyModule\":{\"description\":\"Redirect only exact matching request\",\"type\":\"boolean\"}}}}]},\"aliasFields\":{\"description\":\"Fields in the description file (package.json) which are used to redirect requests inside the module\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringOrStringArrayValues\"}]},\"cachePredicate\":{\"description\":\"Predicate function to decide which requests should be cached\",\"instanceof\":\"Function\",\"tsType\":\"Function\"},\"cacheWithContext\":{\"description\":\"Include the context information in the cache identifier when caching\",\"type\":\"boolean\"},\"concord\":{\"description\":\"Enable concord resolving extras\",\"type\":\"boolean\"},\"descriptionFiles\":{\"description\":\"Filenames used to find a description file\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"enforceExtension\":{\"description\":\"Enforce using one of the extensions from the extensions option\",\"type\":\"boolean\"},\"enforceModuleExtension\":{\"description\":\"Enforce using one of the module extensions from the moduleExtensions option\",\"type\":\"boolean\"},\"extensions\":{\"description\":\"Extensions added to the request when trying to find the file\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"fileSystem\":{\"description\":\"Filesystem for the resolver\"},\"mainFields\":{\"description\":\"Field names from the description file (package.json) which are used to find the default entry point\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringOrStringArrayValues\"}]},\"mainFiles\":{\"description\":\"Filenames used to find the default entry point if there is no description file or main field\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"moduleExtensions\":{\"description\":\"Extensions added to the module request when trying to find the module\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"modules\":{\"description\":\"Folder names or directory paths where to find modules\",\"anyOf\":[{\"$ref\":\"#/definitions/ArrayOfStringValues\"}]},\"plugins\":{\"description\":\"Plugins for the resolver\",\"type\":\"array\",\"items\":{\"description\":\"Plugin of type object or instanceof Function\",\"anyOf\":[{\"$ref\":\"#/definitions/WebpackPluginInstance\"},{\"$ref\":\"#/definitions/WebpackPluginFunction\"}]}},\"resolver\":{\"description\":\"Custom resolver\"},\"roots\":{\"description\":\"A list of directories in which requests that are server-relative URLs (starting with '/') are resolved. On non-windows system these requests are tried to resolve as absolute path first.\",\"type\":\"array\",\"items\":{\"description\":\"Directory in which requests that are server-relative URLs (starting with '/') are resolved.\",\"type\":\"string\"}},\"symlinks\":{\"description\":\"Enable resolving symlinks to the original location\",\"type\":\"boolean\"},\"unsafeCache\":{\"description\":\"Enable caching of successfully resolved requests\",\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"object\",\"additionalProperties\":true}]},\"useSyncFileSystemCalls\":{\"description\":\"Use synchronous filesystem calls for the resolver\",\"type\":\"boolean\"}}},\"RuleSetCondition\":{\"anyOf\":[{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"string\",\"minLength\":1},{\"instanceof\":\"Function\",\"tsType\":\"((value: string) => boolean)\"},{\"$ref\":\"#/definitions/RuleSetConditions\"},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"and\":{\"description\":\"Logical AND\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditions\"}]},\"exclude\":{\"description\":\"Exclude all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditions\"}]},\"include\":{\"description\":\"Exclude all modules matching not any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditions\"}]},\"not\":{\"description\":\"Logical NOT\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditions\"}]},\"or\":{\"description\":\"Logical OR\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditions\"}]},\"test\":{\"description\":\"Exclude all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditions\"}]}}}]},\"RuleSetConditionAbsolute\":{\"anyOf\":[{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"string\",\"absolutePath\":true},{\"instanceof\":\"Function\",\"tsType\":\"((value: string) => boolean)\"},{\"$ref\":\"#/definitions/RuleSetConditionsAbsolute\"},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"and\":{\"description\":\"Logical AND\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionsAbsolute\"}]},\"exclude\":{\"description\":\"Exclude all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"include\":{\"description\":\"Exclude all modules matching not any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"not\":{\"description\":\"Logical NOT\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionsAbsolute\"}]},\"or\":{\"description\":\"Logical OR\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionsAbsolute\"}]},\"test\":{\"description\":\"Exclude all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]}}}]},\"RuleSetConditionOrConditions\":{\"description\":\"One or multiple rule conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetCondition\"},{\"$ref\":\"#/definitions/RuleSetConditions\"}]},\"RuleSetConditionOrConditionsAbsolute\":{\"description\":\"One or multiple rule conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionAbsolute\"},{\"$ref\":\"#/definitions/RuleSetConditionsAbsolute\"}]},\"RuleSetConditions\":{\"type\":\"array\",\"items\":{\"description\":\"A rule condition\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetCondition\"}]}},\"RuleSetConditionsAbsolute\":{\"type\":\"array\",\"items\":{\"description\":\"A rule condition\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionAbsolute\"}]}},\"RuleSetLoader\":{\"type\":\"string\",\"minLength\":1},\"RuleSetQuery\":{\"anyOf\":[{\"type\":\"object\"},{\"type\":\"string\"}]},\"RuleSetRule\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"compiler\":{\"description\":\"Match the child compiler name\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditions\"}]},\"enforce\":{\"description\":\"Enforce this rule as pre or post step\",\"enum\":[\"pre\",\"post\"]},\"exclude\":{\"description\":\"Shortcut for resource.exclude\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"include\":{\"description\":\"Shortcut for resource.include\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"issuer\":{\"description\":\"Match the issuer of the module (The module pointing to this module)\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"loader\":{\"description\":\"Shortcut for use.loader\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetLoader\"},{\"$ref\":\"#/definitions/RuleSetUse\"}]},\"loaders\":{\"description\":\"Shortcut for use.loader\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetUse\"}]},\"oneOf\":{\"description\":\"Only execute the first matching rule in this array\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetRules\"}]},\"options\":{\"description\":\"Shortcut for use.options\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetQuery\"}]},\"parser\":{\"description\":\"Options for parsing\",\"type\":\"object\",\"additionalProperties\":true},\"query\":{\"description\":\"Shortcut for use.query\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetQuery\"}]},\"realResource\":{\"description\":\"Match rules with custom resource name\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"resolve\":{\"description\":\"Options for the resolver\",\"type\":\"object\",\"anyOf\":[{\"$ref\":\"#/definitions/ResolveOptions\"}]},\"resource\":{\"description\":\"Match the resource path of the module\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"resourceQuery\":{\"description\":\"Match the resource query of the module\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditions\"}]},\"rules\":{\"description\":\"Match and execute these rules when this rule is matched\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetRules\"}]},\"sideEffects\":{\"description\":\"Flags a module as with or without side effects\",\"type\":\"boolean\"},\"test\":{\"description\":\"Shortcut for resource.test\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetConditionOrConditionsAbsolute\"}]},\"type\":{\"description\":\"Module type to use for the module\",\"enum\":[\"javascript/auto\",\"javascript/dynamic\",\"javascript/esm\",\"json\",\"webassembly/experimental\"]},\"use\":{\"description\":\"Modifiers applied to the module when rule is matched\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetUse\"}]}}},\"RuleSetRules\":{\"type\":\"array\",\"items\":{\"description\":\"A rule\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetRule\"}]}},\"RuleSetUse\":{\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetUseItem\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"array\",\"items\":{\"description\":\"An use item\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetUseItem\"}]}}]},\"RuleSetUseItem\":{\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetLoader\"},{\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"ident\":{\"description\":\"Unique loader identifier\",\"type\":\"string\"},\"loader\":{\"description\":\"Loader name\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetLoader\"}]},\"options\":{\"description\":\"Loader options\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetQuery\"}]},\"query\":{\"description\":\"Loader query\",\"anyOf\":[{\"$ref\":\"#/definitions/RuleSetQuery\"}]}}}]},\"StatsOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"all\":{\"description\":\"fallback value for stats options when an option is not defined (has precedence over local webpack defaults)\",\"type\":\"boolean\"},\"assets\":{\"description\":\"add assets information\",\"type\":\"boolean\"},\"assetsSort\":{\"description\":\"sort the assets by that field\",\"type\":\"string\"},\"builtAt\":{\"description\":\"add built at time information\",\"type\":\"boolean\"},\"cached\":{\"description\":\"add also information about cached (not built) modules\",\"type\":\"boolean\"},\"cachedAssets\":{\"description\":\"Show cached assets (setting this to `false` only shows emitted files)\",\"type\":\"boolean\"},\"children\":{\"description\":\"add children information\",\"type\":\"boolean\"},\"chunkGroups\":{\"description\":\"Display all chunk groups with the corresponding bundles\",\"type\":\"boolean\"},\"chunkModules\":{\"description\":\"add built modules information to chunk information\",\"type\":\"boolean\"},\"chunkOrigins\":{\"description\":\"add the origins of chunks and chunk merging info\",\"type\":\"boolean\"},\"chunks\":{\"description\":\"add chunk information\",\"type\":\"boolean\"},\"chunksSort\":{\"description\":\"sort the chunks by that field\",\"type\":\"string\"},\"colors\":{\"description\":\"Enables/Disables colorful output\",\"oneOf\":[{\"description\":\"`webpack --colors` equivalent\",\"type\":\"boolean\"},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"bold\":{\"description\":\"Custom color for bold text\",\"type\":\"string\"},\"cyan\":{\"description\":\"Custom color for cyan text\",\"type\":\"string\"},\"green\":{\"description\":\"Custom color for green text\",\"type\":\"string\"},\"magenta\":{\"description\":\"Custom color for magenta text\",\"type\":\"string\"},\"red\":{\"description\":\"Custom color for red text\",\"type\":\"string\"},\"yellow\":{\"description\":\"Custom color for yellow text\",\"type\":\"string\"}}}]},\"context\":{\"description\":\"context directory for request shortening\",\"type\":\"string\",\"absolutePath\":true},\"depth\":{\"description\":\"add module depth in module graph\",\"type\":\"boolean\"},\"entrypoints\":{\"description\":\"Display the entry points with the corresponding bundles\",\"type\":\"boolean\"},\"env\":{\"description\":\"add --env information\",\"type\":\"boolean\"},\"errorDetails\":{\"description\":\"add details to errors (like resolving log)\",\"type\":\"boolean\"},\"errors\":{\"description\":\"add errors\",\"type\":\"boolean\"},\"exclude\":{\"description\":\"Please use excludeModules instead.\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"},{\"type\":\"boolean\"}]},\"excludeAssets\":{\"description\":\"Suppress assets that match the specified filters. Filters can be Strings, RegExps or Functions\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"}]},\"excludeModules\":{\"description\":\"Suppress modules that match the specified filters. Filters can be Strings, RegExps, Booleans or Functions\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"},{\"type\":\"boolean\"}]},\"hash\":{\"description\":\"add the hash of the compilation\",\"type\":\"boolean\"},\"logging\":{\"description\":\"add logging output\",\"anyOf\":[{\"description\":\"enable/disable logging output (true: shows normal logging output, loglevel: log)\",\"type\":\"boolean\"},{\"description\":\"specify log level of logging output\",\"enum\":[\"none\",\"error\",\"warn\",\"info\",\"log\",\"verbose\"]}]},\"loggingDebug\":{\"description\":\"Include debug logging of specified loggers (i. e. for plugins or loaders). Filters can be Strings, RegExps or Functions\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"},{\"description\":\"Enable/Disable debug logging for all loggers\",\"type\":\"boolean\"}]},\"loggingTrace\":{\"description\":\"add stack traces to logging output\",\"type\":\"boolean\"},\"maxModules\":{\"description\":\"Set the maximum number of modules to be shown\",\"type\":\"number\"},\"moduleAssets\":{\"description\":\"add information about assets inside modules\",\"type\":\"boolean\"},\"moduleTrace\":{\"description\":\"add dependencies and origin of warnings/errors\",\"type\":\"boolean\"},\"modules\":{\"description\":\"add built modules information\",\"type\":\"boolean\"},\"modulesSort\":{\"description\":\"sort the modules by that field\",\"type\":\"string\"},\"nestedModules\":{\"description\":\"add information about modules nested in other modules (like with module concatenation)\",\"type\":\"boolean\"},\"optimizationBailout\":{\"description\":\"show reasons why optimization bailed out for modules\",\"type\":\"boolean\"},\"outputPath\":{\"description\":\"Add output path information\",\"type\":\"boolean\"},\"performance\":{\"description\":\"add performance hint flags\",\"type\":\"boolean\"},\"providedExports\":{\"description\":\"show exports provided by modules\",\"type\":\"boolean\"},\"publicPath\":{\"description\":\"Add public path information\",\"type\":\"boolean\"},\"reasons\":{\"description\":\"add information about the reasons why modules are included\",\"type\":\"boolean\"},\"source\":{\"description\":\"add the source code of modules\",\"type\":\"boolean\"},\"timings\":{\"description\":\"add timing information\",\"type\":\"boolean\"},\"usedExports\":{\"description\":\"show exports used by modules\",\"type\":\"boolean\"},\"version\":{\"description\":\"add webpack version information\",\"type\":\"boolean\"},\"warnings\":{\"description\":\"add warnings\",\"type\":\"boolean\"},\"warningsFilter\":{\"description\":\"Suppress warnings that match the specified filters. Filters can be Strings, RegExps or Functions\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"}]}}},\"WebpackPluginFunction\":{\"description\":\"Function acting as plugin\",\"instanceof\":\"Function\",\"tsType\":\"(this: import('../lib/Compiler'), compiler: import('../lib/Compiler')) => void\"},\"WebpackPluginInstance\":{\"description\":\"Plugin instance\",\"type\":\"object\",\"additionalProperties\":true,\"properties\":{\"apply\":{\"description\":\"The run point of the plugin, required method.\",\"instanceof\":\"Function\",\"tsType\":\"(compiler: import('../lib/Compiler')) => void\"}},\"required\":[\"apply\"]}},\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"amd\":{\"description\":\"Set the value of `require.amd` and `define.amd`. Or disable AMD support.\",\"anyOf\":[{\"description\":\"You can pass `false` to disable AMD support.\",\"enum\":[false]},{\"description\":\"You can pass an object to set the value of `require.amd` and `define.amd`.\",\"type\":\"object\"}]},\"bail\":{\"description\":\"Report the first error as a hard error instead of tolerating it.\",\"type\":\"boolean\"},\"cache\":{\"description\":\"Cache generated modules and chunks to improve performance for multiple incremental builds.\",\"anyOf\":[{\"description\":\"You can pass `false` to disable it.\",\"type\":\"boolean\"},{\"description\":\"You can pass an object to enable it and let webpack use the passed object as cache. This way you can share the cache object between multiple compiler calls.\",\"type\":\"object\"}]},\"context\":{\"description\":\"The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory.\",\"type\":\"string\",\"absolutePath\":true},\"dependencies\":{\"description\":\"References to other configurations to depend on.\",\"type\":\"array\",\"items\":{\"description\":\"References to another configuration to depend on.\",\"type\":\"string\"}},\"devServer\":{\"description\":\"Options for the webpack-dev-server\",\"type\":\"object\"},\"devtool\":{\"description\":\"A developer tool to enhance debugging.\",\"anyOf\":[{\"type\":\"string\"},{\"enum\":[false]}]},\"entry\":{\"description\":\"The entry point(s) of the compilation.\",\"anyOf\":[{\"$ref\":\"#/definitions/Entry\"}]},\"externals\":{\"description\":\"Specify dependencies that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on `output.libraryTarget`.\",\"anyOf\":[{\"$ref\":\"#/definitions/Externals\"}]},\"infrastructureLogging\":{\"description\":\"Options for infrastructure level logging\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"debug\":{\"description\":\"Enable debug logging for specific loggers\",\"anyOf\":[{\"$ref\":\"#/definitions/FilterTypes\"},{\"description\":\"Enable/Disable debug logging for all loggers\",\"type\":\"boolean\"}]},\"level\":{\"description\":\"Log level\",\"enum\":[\"none\",\"error\",\"warn\",\"info\",\"log\",\"verbose\"]}}},\"loader\":{\"description\":\"Custom values available in the loader context.\",\"type\":\"object\"},\"mode\":{\"description\":\"Enable production optimizations or development hints.\",\"enum\":[\"development\",\"production\",\"none\"]},\"module\":{\"description\":\"Options affecting the normal modules (`NormalModuleFactory`).\",\"anyOf\":[{\"$ref\":\"#/definitions/ModuleOptions\"}]},\"name\":{\"description\":\"Name of the configuration. Used when loading multiple configurations.\",\"type\":\"string\"},\"node\":{\"description\":\"Include polyfills or mocks for various node stuff.\",\"anyOf\":[{\"enum\":[false]},{\"$ref\":\"#/definitions/NodeOptions\"}]},\"optimization\":{\"description\":\"Enables/Disables integrated optimizations\",\"anyOf\":[{\"$ref\":\"#/definitions/OptimizationOptions\"}]},\"output\":{\"description\":\"Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.\",\"anyOf\":[{\"$ref\":\"#/definitions/OutputOptions\"}]},\"parallelism\":{\"description\":\"The number of parallel processed modules in the compilation.\",\"type\":\"number\",\"minimum\":1},\"performance\":{\"description\":\"Configuration for web performance recommendations.\",\"anyOf\":[{\"enum\":[false]},{\"$ref\":\"#/definitions/PerformanceOptions\"}]},\"plugins\":{\"description\":\"Add additional plugins to the compiler.\",\"type\":\"array\",\"items\":{\"description\":\"Plugin of type object or instanceof Function\",\"anyOf\":[{\"$ref\":\"#/definitions/WebpackPluginInstance\"},{\"$ref\":\"#/definitions/WebpackPluginFunction\"}]}},\"profile\":{\"description\":\"Capture timing information for each module.\",\"type\":\"boolean\"},\"recordsInputPath\":{\"description\":\"Store compiler state to a json file.\",\"type\":\"string\",\"absolutePath\":true},\"recordsOutputPath\":{\"description\":\"Load compiler state from a json file.\",\"type\":\"string\",\"absolutePath\":true},\"recordsPath\":{\"description\":\"Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks. An absolute path is expected. `recordsPath` is used for `recordsInputPath` and `recordsOutputPath` if they left undefined.\",\"type\":\"string\",\"absolutePath\":true},\"resolve\":{\"description\":\"Options for the resolver\",\"anyOf\":[{\"$ref\":\"#/definitions/ResolveOptions\"}]},\"resolveLoader\":{\"description\":\"Options for the resolver when resolving loaders\",\"anyOf\":[{\"$ref\":\"#/definitions/ResolveOptions\"}]},\"serve\":{\"description\":\"Options for webpack-serve\",\"type\":\"object\"},\"stats\":{\"description\":\"Used by the webpack CLI program to pass stats options.\",\"anyOf\":[{\"$ref\":\"#/definitions/StatsOptions\"},{\"type\":\"boolean\"},{\"enum\":[\"none\",\"errors-only\",\"minimal\",\"normal\",\"detailed\",\"verbose\",\"errors-warnings\"]}]},\"target\":{\"description\":\"Environment to build for\",\"anyOf\":[{\"enum\":[\"web\",\"webworker\",\"node\",\"async-node\",\"node-webkit\",\"electron-main\",\"electron-renderer\",\"electron-preload\"]},{\"instanceof\":\"Function\",\"tsType\":\"((compiler: import('../lib/Compiler')) => void)\"}]},\"watch\":{\"description\":\"Enter watch mode, which rebuilds on file change.\",\"type\":\"boolean\"},\"watchOptions\":{\"description\":\"Options for the watcher\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"aggregateTimeout\":{\"description\":\"Delay the rebuilt after the first change. Value is a time in ms.\",\"type\":\"number\"},\"ignored\":{\"description\":\"Ignore some files from watching\"},\"poll\":{\"description\":\"Enable polling mode for watching\",\"anyOf\":[{\"description\":\"`true`: use polling.\",\"type\":\"boolean\"},{\"description\":\"`number`: use polling with specified interval.\",\"type\":\"number\"}]},\"stdin\":{\"description\":\"Stop watching when stdin stream has ended\",\"type\":\"boolean\"}}}}}"); + +/***/ }), + +/***/ 10171: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"definitions\":{\"BannerFunction\":{\"description\":\"The banner as function, it will be wrapped in a comment\",\"instanceof\":\"Function\",\"tsType\":\"(data: { hash: string, chunk: import('../../lib/Chunk'), filename: string, basename: string, query: string}) => string\"},\"Rule\":{\"oneOf\":[{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"string\",\"minLength\":1}]},\"Rules\":{\"oneOf\":[{\"type\":\"array\",\"items\":{\"description\":\"A rule condition\",\"anyOf\":[{\"$ref\":\"#/definitions/Rule\"}]}},{\"$ref\":\"#/definitions/Rule\"}]}},\"title\":\"BannerPluginArgument\",\"oneOf\":[{\"title\":\"BannerPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"banner\":{\"description\":\"Specifies the banner\",\"anyOf\":[{\"$ref\":\"#/definitions/BannerFunction\"},{\"type\":\"string\"}]},\"entryOnly\":{\"description\":\"If true, the banner will only be added to the entry chunks\",\"type\":\"boolean\"},\"exclude\":{\"description\":\"Exclude all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/Rules\"}]},\"include\":{\"description\":\"Include all modules matching any of these conditions\",\"anyOf\":[{\"$ref\":\"#/definitions/Rules\"}]},\"raw\":{\"description\":\"If true, banner will not be wrapped in a comment\",\"type\":\"boolean\"},\"test\":{\"description\":\"Include all modules that pass test assertion\",\"anyOf\":[{\"$ref\":\"#/definitions/Rules\"}]}},\"required\":[\"banner\"]},{\"$ref\":\"#/definitions/BannerFunction\"},{\"description\":\"The banner as string, it will be wrapped in a comment\",\"type\":\"string\",\"minLength\":1}]}"); + +/***/ }), + +/***/ 7303: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"DllPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"context\":{\"description\":\"Context of requests in the manifest file (defaults to the webpack context)\",\"type\":\"string\",\"minLength\":1},\"entryOnly\":{\"description\":\"If true, only entry points will be exposed\",\"type\":\"boolean\"},\"format\":{\"description\":\"If true, manifest json file (output) will be formatted\",\"type\":\"boolean\"},\"name\":{\"description\":\"Name of the exposed dll function (external name, use value of 'output.library')\",\"type\":\"string\",\"minLength\":1},\"path\":{\"description\":\"Absolute path to the manifest json file (output)\",\"type\":\"string\",\"minLength\":1},\"type\":{\"description\":\"Type of the dll bundle (external type, use value of 'output.libraryTarget')\",\"type\":\"string\",\"minLength\":1}},\"required\":[\"path\"]}"); + +/***/ }), + +/***/ 61112: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"definitions\":{\"DllReferencePluginOptionsContent\":{\"description\":\"The mappings from request to module info\",\"type\":\"object\",\"additionalProperties\":{\"description\":\"Module info\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"buildMeta\":{\"description\":\"Meta information about the module\",\"type\":\"object\"},\"exports\":{\"description\":\"Information about the provided exports of the module\",\"anyOf\":[{\"description\":\"Exports unknown/dynamic\",\"enum\":[true]},{\"description\":\"List of provided exports of the module\",\"type\":\"array\",\"items\":{\"description\":\"Name of the export\",\"type\":\"string\",\"minLength\":1}}]},\"id\":{\"description\":\"Module ID\",\"anyOf\":[{\"type\":\"number\"},{\"type\":\"string\",\"minLength\":1}]}},\"required\":[\"id\"]},\"minProperties\":1},\"DllReferencePluginOptionsManifest\":{\"description\":\"An object containing content, name and type\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"content\":{\"description\":\"The mappings from request to module info\",\"anyOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsContent\"}]},\"name\":{\"description\":\"The name where the dll is exposed (external name)\",\"type\":\"string\",\"minLength\":1},\"type\":{\"description\":\"The type how the dll is exposed (external type)\",\"anyOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsSourceType\"}]}},\"required\":[\"content\"]},\"DllReferencePluginOptionsSourceType\":{\"description\":\"The type how the dll is exposed (external type)\",\"enum\":[\"var\",\"assign\",\"this\",\"window\",\"global\",\"commonjs\",\"commonjs2\",\"commonjs-module\",\"amd\",\"amd-require\",\"umd\",\"umd2\",\"jsonp\"]}},\"title\":\"DllReferencePluginOptions\",\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"context\":{\"description\":\"(absolute path) context of requests in the manifest (or content property)\",\"type\":\"string\",\"absolutePath\":true},\"extensions\":{\"description\":\"Extensions used to resolve modules in the dll bundle (only used when using 'scope')\",\"type\":\"array\",\"items\":{\"description\":\"An extension\",\"type\":\"string\"}},\"manifest\":{\"description\":\"An object containing content and name or a string to the absolute path of the JSON manifest to be loaded upon compilation\",\"oneOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsManifest\"},{\"type\":\"string\",\"absolutePath\":true}]},\"name\":{\"description\":\"The name where the dll is exposed (external name, defaults to manifest.name)\",\"type\":\"string\",\"minLength\":1},\"scope\":{\"description\":\"Prefix which is used for accessing the content of the dll\",\"type\":\"string\",\"minLength\":1},\"sourceType\":{\"description\":\"How the dll is exposed (libraryTarget, defaults to manifest.type)\",\"anyOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsSourceType\"}]},\"type\":{\"description\":\"The way how the export of the dll bundle is used\",\"enum\":[\"require\",\"object\"]}},\"required\":[\"manifest\"]},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"content\":{\"description\":\"The mappings from request to module info\",\"anyOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsContent\"}]},\"context\":{\"description\":\"(absolute path) context of requests in the manifest (or content property)\",\"type\":\"string\",\"absolutePath\":true},\"extensions\":{\"description\":\"Extensions used to resolve modules in the dll bundle (only used when using 'scope')\",\"type\":\"array\",\"items\":{\"description\":\"An extension\",\"type\":\"string\"}},\"name\":{\"description\":\"The name where the dll is exposed (external name)\",\"type\":\"string\",\"minLength\":1},\"scope\":{\"description\":\"Prefix which is used for accessing the content of the dll\",\"type\":\"string\",\"minLength\":1},\"sourceType\":{\"description\":\"How the dll is exposed (libraryTarget)\",\"anyOf\":[{\"$ref\":\"#/definitions/DllReferencePluginOptionsSourceType\"}]},\"type\":{\"description\":\"The way how the export of the dll bundle is used\",\"enum\":[\"require\",\"object\"]}},\"required\":[\"content\",\"name\"]}]}"); + +/***/ }), + +/***/ 45843: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"HashedModuleIdsPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"context\":{\"description\":\"The context directory for creating names.\",\"type\":\"string\",\"absolutePath\":true},\"hashDigest\":{\"description\":\"The encoding to use when generating the hash, defaults to 'base64'. All encodings from Node.JS' hash.digest are supported.\",\"enum\":[\"hex\",\"latin1\",\"base64\"]},\"hashDigestLength\":{\"description\":\"The prefix length of the hash digest to use, defaults to 4.\",\"type\":\"number\",\"minimum\":1},\"hashFunction\":{\"description\":\"The hashing algorithm to use, defaults to 'md5'. All functions from Node.JS' crypto.createHash are supported.\",\"type\":\"string\",\"minLength\":1}}}"); + +/***/ }), + +/***/ 69667: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"IgnorePluginOptions\",\"oneOf\":[{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"contextRegExp\":{\"description\":\"A RegExp to test the context (directory) against\",\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},\"resourceRegExp\":{\"description\":\"A RegExp to test the request against\",\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}}},{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"checkContext\":{\"description\":\"A filter function for context\",\"instanceof\":\"Function\",\"tsType\":\"((context: string) => boolean)\"},\"checkResource\":{\"description\":\"A filter function for resource and context\",\"instanceof\":\"Function\",\"tsType\":\"((resource: string, context: string) => boolean)\"}}}]}"); + +/***/ }), + +/***/ 4994: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"LoaderOptionsPluginOptions\",\"type\":\"object\",\"additionalProperties\":true,\"properties\":{\"debug\":{\"description\":\"Whether loaders should be in debug mode or not. debug will be removed as of webpack 3\",\"type\":\"boolean\"},\"minimize\":{\"description\":\"Where loaders can be switched to minimize mode\",\"type\":\"boolean\"},\"options\":{\"description\":\"A configuration object that can be used to configure older loaders\",\"type\":\"object\",\"additionalProperties\":true,\"properties\":{\"context\":{\"description\":\"The context that can be used to configure older loaders\",\"type\":\"string\",\"absolutePath\":true}}}}}"); + +/***/ }), + +/***/ 26336: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"definitions\":{\"HandlerFunction\":{\"description\":\"Function that executes for every progress step\",\"instanceof\":\"Function\",\"tsType\":\"((percentage: number, msg: string, ...args: string[]) => void)\"},\"ProgressPluginOptions\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"activeModules\":{\"description\":\"Show active modules count and one active module in progress message\",\"type\":\"boolean\"},\"entries\":{\"description\":\"Show entries count in progress message\",\"type\":\"boolean\"},\"handler\":{\"description\":\"Function that executes for every progress step\",\"anyOf\":[{\"$ref\":\"#/definitions/HandlerFunction\"}]},\"modules\":{\"description\":\"Show modules count in progress message\",\"type\":\"boolean\"},\"modulesCount\":{\"description\":\"Minimum modules count to start with. Only for mode=modules. Default: 500\",\"type\":\"number\"},\"profile\":{\"description\":\"Collect profile data for progress steps. Default: false\",\"enum\":[true,false,null]}}}},\"title\":\"ProgressPluginArgument\",\"oneOf\":[{\"$ref\":\"#/definitions/ProgressPluginOptions\"},{\"$ref\":\"#/definitions/HandlerFunction\"}]}"); + +/***/ }), + +/***/ 7368: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"definitions\":{\"rule\":{\"oneOf\":[{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"},{\"type\":\"string\",\"minLength\":1}]},\"rules\":{\"oneOf\":[{\"type\":\"array\",\"items\":{\"description\":\"A rule condition\",\"anyOf\":[{\"$ref\":\"#/definitions/rule\"}]}},{\"$ref\":\"#/definitions/rule\"}]}},\"title\":\"SourceMapDevToolPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"append\":{\"description\":\"Appends the given value to the original asset. Usually the #sourceMappingURL comment. [url] is replaced with a URL to the source map file. false disables the appending\",\"oneOf\":[{\"description\":\"Append no SourceMap comment to the bundle, but still generate SourceMaps\",\"enum\":[false,null]},{\"type\":\"string\",\"minLength\":1}]},\"columns\":{\"description\":\"Indicates whether column mappings should be used (defaults to true)\",\"type\":\"boolean\"},\"exclude\":{\"description\":\"Exclude modules that match the given value from source map generation\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]},\"fallbackModuleFilenameTemplate\":{\"description\":\"Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict\",\"oneOf\":[{\"description\":\"Custom function generating the identifer\",\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\",\"minLength\":1}]},\"fileContext\":{\"description\":\"Path prefix to which the [file] placeholder is relative to\",\"type\":\"string\"},\"filename\":{\"description\":\"Defines the output filename of the SourceMap (will be inlined if no value is provided)\",\"oneOf\":[{\"description\":\"Disable separate SourceMap file and inline SourceMap as DataUrl\",\"enum\":[false,null]},{\"type\":\"string\",\"absolutePath\":false,\"minLength\":1}]},\"include\":{\"description\":\"Include source maps for module paths that match the given value\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]},\"lineToLine\":{\"description\":\"(deprecated) try to map original files line to line to generated files\",\"anyOf\":[{\"type\":\"boolean\"},{\"description\":\"Simplify and speed up source mapping by using line to line source mappings for matched modules\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"exclude\":{\"description\":\"Exclude modules that match the given value from source map generation\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]},\"include\":{\"description\":\"Include source maps for module paths that match the given value\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]},\"test\":{\"description\":\"Include source maps for modules based on their extension (defaults to .js and .css)\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]}}}]},\"module\":{\"description\":\"Indicates whether SourceMaps from loaders should be used (defaults to true)\",\"type\":\"boolean\"},\"moduleFilenameTemplate\":{\"description\":\"Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap\",\"oneOf\":[{\"description\":\"Custom function generating the identifer\",\"instanceof\":\"Function\",\"tsType\":\"Function\"},{\"type\":\"string\",\"minLength\":1}]},\"namespace\":{\"description\":\"Namespace prefix to allow multiple webpack roots in the devtools\",\"type\":\"string\"},\"noSources\":{\"description\":\"Omit the 'sourceContents' array from the SourceMap\",\"type\":\"boolean\"},\"publicPath\":{\"description\":\"Provide a custom public path for the SourceMapping comment\",\"type\":\"string\"},\"sourceRoot\":{\"description\":\"Provide a custom value for the 'sourceRoot' property in the SourceMap\",\"type\":\"string\"},\"test\":{\"description\":\"Include source maps for modules based on their extension (defaults to .js and .css)\",\"anyOf\":[{\"$ref\":\"#/definitions/rules\"}]}}}"); + +/***/ }), + +/***/ 97009: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"WatchIgnorePluginOptions\",\"description\":\"A list of RegExps or absolute paths to directories or files that should be ignored\",\"type\":\"array\",\"items\":{\"description\":\"RegExp or absolute path to directories or files that should be ignored\",\"oneOf\":[{\"type\":\"string\"},{\"instanceof\":\"RegExp\",\"tsType\":\"RegExp\"}]},\"minItems\":1}"); + +/***/ }), + +/***/ 49049: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"ProfilingPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"outputPath\":{\"description\":\"Path to the output file e.g. `profiling/events.json`. Defaults to `events.json`.\",\"type\":\"string\",\"absolutePath\":false,\"minLength\":4}}}"); + +/***/ }), + +/***/ 71884: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"AggressiveSplittingPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"chunkOverhead\":{\"description\":\"Default: 0\",\"type\":\"number\"},\"entryChunkMultiplicator\":{\"description\":\"Default: 1\",\"type\":\"number\"},\"maxSize\":{\"description\":\"Byte, maxsize of per file. Default: 51200\",\"type\":\"number\"},\"minSize\":{\"description\":\"Byte, split point. Default: 30720\",\"type\":\"number\"}}}"); + +/***/ }), + +/***/ 27993: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"LimitChunkCountPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"maxChunks\":{\"description\":\"Limit the maximum number of chunks using a value greater greater than or equal to 1\",\"type\":\"number\",\"minimum\":1},\"minChunkSize\":{\"description\":\"Set a minimum chunk size\",\"type\":\"number\"}}}"); + +/***/ }), + +/***/ 8670: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"MinChunkSizePluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"minChunkSize\":{\"description\":\"Minimum number of characters\",\"type\":\"number\"}},\"required\":[\"minChunkSize\"]}"); + +/***/ }), + +/***/ 88771: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"OccurrenceOrderChunkIdsPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"prioritiseInitial\":{\"description\":\"Prioritise initial size over total size\",\"type\":\"boolean\"}}}"); + +/***/ }), + +/***/ 81430: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"title\":\"OccurrenceOrderModuleIdsPluginOptions\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"prioritiseInitial\":{\"description\":\"Prioritise initial size over total size\",\"type\":\"boolean\"}}}"); + +/***/ }), + +/***/ 95373: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.cloneNode = cloneNode; + +function cloneNode(n) { + // $FlowIgnore + var newObj = {}; + + for (var k in n) { + newObj[k] = n[k]; + } + + return newObj; +} + +/***/ }), + +/***/ 98688: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + numberLiteralFromRaw: true, + withLoc: true, + withRaw: true, + funcParam: true, + indexLiteral: true, + memIndexLiteral: true, + instruction: true, + objectInstruction: true, + traverse: true, + signatures: true, + cloneNode: true +}; +Object.defineProperty(exports, "numberLiteralFromRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.numberLiteralFromRaw; + } +})); +Object.defineProperty(exports, "withLoc", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withLoc; + } +})); +Object.defineProperty(exports, "withRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withRaw; + } +})); +Object.defineProperty(exports, "funcParam", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.funcParam; + } +})); +Object.defineProperty(exports, "indexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.indexLiteral; + } +})); +Object.defineProperty(exports, "memIndexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.memIndexLiteral; + } +})); +Object.defineProperty(exports, "instruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.instruction; + } +})); +Object.defineProperty(exports, "objectInstruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.objectInstruction; + } +})); +Object.defineProperty(exports, "traverse", ({ + enumerable: true, + get: function get() { + return _traverse.traverse; + } +})); +Object.defineProperty(exports, "signatures", ({ + enumerable: true, + get: function get() { + return _signatures.signatures; + } +})); +Object.defineProperty(exports, "cloneNode", ({ + enumerable: true, + get: function get() { + return _clone.cloneNode; + } +})); + +var _nodes = __webpack_require__(36588); + +Object.keys(_nodes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _nodes[key]; + } + }); +}); + +var _nodeHelpers = __webpack_require__(69887); + +var _traverse = __webpack_require__(34390); + +var _signatures = __webpack_require__(14004); + +var _utils = __webpack_require__(26038); + +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); + +var _clone = __webpack_require__(95373); + +/***/ }), + +/***/ 69887: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.numberLiteralFromRaw = numberLiteralFromRaw; +exports.instruction = instruction; +exports.objectInstruction = objectInstruction; +exports.withLoc = withLoc; +exports.withRaw = withRaw; +exports.funcParam = funcParam; +exports.indexLiteral = indexLiteral; +exports.memIndexLiteral = memIndexLiteral; + +var _wastParser = __webpack_require__(9016); + +var _nodes = __webpack_require__(36588); + +function numberLiteralFromRaw(rawValue) { + var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32"; + var original = rawValue; // Remove numeric separators _ + + if (typeof rawValue === "string") { + rawValue = rawValue.replace(/_/g, ""); + } + + if (typeof rawValue === "number") { + return (0, _nodes.numberLiteral)(rawValue, String(original)); + } else { + switch (instructionType) { + case "i32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parse32I)(rawValue), String(original)); + } + + case "u32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parseU32)(rawValue), String(original)); + } + + case "i64": + { + return (0, _nodes.longNumberLiteral)((0, _wastParser.parse64I)(rawValue), String(original)); + } + + case "f32": + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse32F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + // f64 + + default: + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + } + } +} + +function instruction(id) { + var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return (0, _nodes.instr)(id, undefined, args, namedArgs); +} + +function objectInstruction(id, object) { + var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + return (0, _nodes.instr)(id, object, args, namedArgs); +} +/** + * Decorators + */ + + +function withLoc(n, end, start) { + var loc = { + start: start, + end: end + }; + n.loc = loc; + return n; +} + +function withRaw(n, raw) { + n.raw = raw; + return n; +} + +function funcParam(valtype, id) { + return { + id: id, + valtype: valtype + }; +} + +function indexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} + +function memIndexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} + +/***/ }), + +/***/ 27110: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPath = createPath; + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +function findParent(_ref, cb) { + var parentPath = _ref.parentPath; + + if (parentPath == null) { + throw new Error("node is root"); + } + + var currentPath = parentPath; + + while (cb(currentPath) !== false) { + // Hit the root node, stop + // $FlowIgnore + if (currentPath.parentPath == null) { + return null; + } // $FlowIgnore + + + currentPath = currentPath.parentPath; + } + + return currentPath.node; +} + +function insertBefore(context, newNode) { + return insert(context, newNode); +} + +function insertAfter(context, newNode) { + return insert(context, newNode, 1); +} + +function insert(_ref2, newNode) { + var node = _ref2.node, + inList = _ref2.inList, + parentPath = _ref2.parentPath, + parentKey = _ref2.parentKey; + var indexOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (!inList) { + throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); + } + + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } + + // $FlowIgnore + var parentList = parentPath.node[parentKey]; + var indexInList = parentList.findIndex(function (n) { + return n === node; + }); + parentList.splice(indexInList + indexOffset, 0, newNode); +} + +function remove(_ref3) { + var node = _ref3.node, + parentKey = _ref3.parentKey, + parentPath = _ref3.parentPath; + + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } + + // $FlowIgnore + var parentNode = parentPath.node; // $FlowIgnore + + var parentProperty = parentNode[parentKey]; + + if (Array.isArray(parentProperty)) { + // $FlowIgnore + parentNode[parentKey] = parentProperty.filter(function (n) { + return n !== node; + }); + } else { + // $FlowIgnore + delete parentNode[parentKey]; + } + + node._deleted = true; +} + +function stop(context) { + context.shouldStop = true; +} + +function replaceWith(context, newNode) { + // $FlowIgnore + var parentNode = context.parentPath.node; // $FlowIgnore + + var parentProperty = parentNode[context.parentKey]; + + if (Array.isArray(parentProperty)) { + var indexInList = parentProperty.findIndex(function (n) { + return n === context.node; + }); + parentProperty.splice(indexInList, 1, newNode); + } else { + // $FlowIgnore + parentNode[context.parentKey] = newNode; + } + + context.node._deleted = true; + context.node = newNode; +} // bind the context to the first argument of node operations + + +function bindNodeOperations(operations, context) { + var keys = Object.keys(operations); + var boundOperations = {}; + keys.forEach(function (key) { + boundOperations[key] = operations[key].bind(null, context); + }); + return boundOperations; +} + +function createPathOperations(context) { + // $FlowIgnore + return bindNodeOperations({ + findParent: findParent, + replaceWith: replaceWith, + remove: remove, + insertBefore: insertBefore, + insertAfter: insertAfter, + stop: stop + }, context); +} + +function createPath(context) { + var path = _extends({}, context); // $FlowIgnore + + + Object.assign(path, createPathOperations(path)); // $FlowIgnore + + return path; +} + +/***/ }), + +/***/ 36588: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.module = _module; +exports.moduleMetadata = moduleMetadata; +exports.moduleNameMetadata = moduleNameMetadata; +exports.functionNameMetadata = functionNameMetadata; +exports.localNameMetadata = localNameMetadata; +exports.binaryModule = binaryModule; +exports.quoteModule = quoteModule; +exports.sectionMetadata = sectionMetadata; +exports.producersSectionMetadata = producersSectionMetadata; +exports.producerMetadata = producerMetadata; +exports.producerMetadataVersionedName = producerMetadataVersionedName; +exports.loopInstruction = loopInstruction; +exports.instr = instr; +exports.ifInstruction = ifInstruction; +exports.stringLiteral = stringLiteral; +exports.numberLiteral = numberLiteral; +exports.longNumberLiteral = longNumberLiteral; +exports.floatLiteral = floatLiteral; +exports.elem = elem; +exports.indexInFuncSection = indexInFuncSection; +exports.valtypeLiteral = valtypeLiteral; +exports.typeInstruction = typeInstruction; +exports.start = start; +exports.globalType = globalType; +exports.leadingComment = leadingComment; +exports.blockComment = blockComment; +exports.data = data; +exports.global = global; +exports.table = table; +exports.memory = memory; +exports.funcImportDescr = funcImportDescr; +exports.moduleImport = moduleImport; +exports.moduleExportDescr = moduleExportDescr; +exports.moduleExport = moduleExport; +exports.limit = limit; +exports.signature = signature; +exports.program = program; +exports.identifier = identifier; +exports.blockInstruction = blockInstruction; +exports.callInstruction = callInstruction; +exports.callIndirectInstruction = callIndirectInstruction; +exports.byteArray = byteArray; +exports.func = func; +exports.internalBrUnless = internalBrUnless; +exports.internalGoto = internalGoto; +exports.internalCallExtern = internalCallExtern; +exports.internalEndAndReturn = internalEndAndReturn; +exports.assertInternalCallExtern = exports.assertInternalGoto = exports.assertInternalBrUnless = exports.assertFunc = exports.assertByteArray = exports.assertCallIndirectInstruction = exports.assertCallInstruction = exports.assertBlockInstruction = exports.assertIdentifier = exports.assertProgram = exports.assertSignature = exports.assertLimit = exports.assertModuleExport = exports.assertModuleExportDescr = exports.assertModuleImport = exports.assertFuncImportDescr = exports.assertMemory = exports.assertTable = exports.assertGlobal = exports.assertData = exports.assertBlockComment = exports.assertLeadingComment = exports.assertGlobalType = exports.assertStart = exports.assertTypeInstruction = exports.assertValtypeLiteral = exports.assertIndexInFuncSection = exports.assertElem = exports.assertFloatLiteral = exports.assertLongNumberLiteral = exports.assertNumberLiteral = exports.assertStringLiteral = exports.assertIfInstruction = exports.assertInstr = exports.assertLoopInstruction = exports.assertProducerMetadataVersionedName = exports.assertProducerMetadata = exports.assertProducersSectionMetadata = exports.assertSectionMetadata = exports.assertQuoteModule = exports.assertBinaryModule = exports.assertLocalNameMetadata = exports.assertFunctionNameMetadata = exports.assertModuleNameMetadata = exports.assertModuleMetadata = exports.assertModule = exports.isIntrinsic = exports.isImportDescr = exports.isNumericLiteral = exports.isExpression = exports.isInstruction = exports.isBlock = exports.isNode = exports.isInternalEndAndReturn = exports.isInternalCallExtern = exports.isInternalGoto = exports.isInternalBrUnless = exports.isFunc = exports.isByteArray = exports.isCallIndirectInstruction = exports.isCallInstruction = exports.isBlockInstruction = exports.isIdentifier = exports.isProgram = exports.isSignature = exports.isLimit = exports.isModuleExport = exports.isModuleExportDescr = exports.isModuleImport = exports.isFuncImportDescr = exports.isMemory = exports.isTable = exports.isGlobal = exports.isData = exports.isBlockComment = exports.isLeadingComment = exports.isGlobalType = exports.isStart = exports.isTypeInstruction = exports.isValtypeLiteral = exports.isIndexInFuncSection = exports.isElem = exports.isFloatLiteral = exports.isLongNumberLiteral = exports.isNumberLiteral = exports.isStringLiteral = exports.isIfInstruction = exports.isInstr = exports.isLoopInstruction = exports.isProducerMetadataVersionedName = exports.isProducerMetadata = exports.isProducersSectionMetadata = exports.isSectionMetadata = exports.isQuoteModule = exports.isBinaryModule = exports.isLocalNameMetadata = exports.isFunctionNameMetadata = exports.isModuleNameMetadata = exports.isModuleMetadata = exports.isModule = void 0; +exports.nodeAndUnionTypes = exports.unionTypesMap = exports.assertInternalEndAndReturn = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +// THIS FILE IS AUTOGENERATED +// see scripts/generateNodeUtils.js +function isTypeOf(t) { + return function (n) { + return n.type === t; + }; +} + +function assertTypeOf(t) { + return function (n) { + return function () { + if (!(n.type === t)) { + throw new Error('n.type === t' + " error: " + (undefined || "unknown")); + } + }(); + }; +} + +function _module(id, fields, metadata) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(fields) === "object" && typeof fields.length !== "undefined")) { + throw new Error('typeof fields === "object" && typeof fields.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Module", + id: id, + fields: fields + }; + + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } + + return node; +} + +function moduleMetadata(sections, functionNames, localNames, producers) { + if (!(_typeof(sections) === "object" && typeof sections.length !== "undefined")) { + throw new Error('typeof sections === "object" && typeof sections.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (functionNames !== null && functionNames !== undefined) { + if (!(_typeof(functionNames) === "object" && typeof functionNames.length !== "undefined")) { + throw new Error('typeof functionNames === "object" && typeof functionNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + if (localNames !== null && localNames !== undefined) { + if (!(_typeof(localNames) === "object" && typeof localNames.length !== "undefined")) { + throw new Error('typeof localNames === "object" && typeof localNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + if (producers !== null && producers !== undefined) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "ModuleMetadata", + sections: sections + }; + + if (typeof functionNames !== "undefined" && functionNames.length > 0) { + node.functionNames = functionNames; + } + + if (typeof localNames !== "undefined" && localNames.length > 0) { + node.localNames = localNames; + } + + if (typeof producers !== "undefined" && producers.length > 0) { + node.producers = producers; + } + + return node; +} + +function moduleNameMetadata(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "ModuleNameMetadata", + value: value + }; + return node; +} + +function functionNameMetadata(value, index) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (!(typeof index === "number")) { + throw new Error('typeof index === "number"' + " error: " + ("Argument index must be of type number, given: " + _typeof(index) || 0)); + } + + var node = { + type: "FunctionNameMetadata", + value: value, + index: index + }; + return node; +} + +function localNameMetadata(value, localIndex, functionIndex) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (!(typeof localIndex === "number")) { + throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); + } + + if (!(typeof functionIndex === "number")) { + throw new Error('typeof functionIndex === "number"' + " error: " + ("Argument functionIndex must be of type number, given: " + _typeof(functionIndex) || 0)); + } + + var node = { + type: "LocalNameMetadata", + value: value, + localIndex: localIndex, + functionIndex: functionIndex + }; + return node; +} + +function binaryModule(id, blob) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(blob) === "object" && typeof blob.length !== "undefined")) { + throw new Error('typeof blob === "object" && typeof blob.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "BinaryModule", + id: id, + blob: blob + }; + return node; +} + +function quoteModule(id, string) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(string) === "object" && typeof string.length !== "undefined")) { + throw new Error('typeof string === "object" && typeof string.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "QuoteModule", + id: id, + string: string + }; + return node; +} + +function sectionMetadata(section, startOffset, size, vectorOfSize) { + if (!(typeof startOffset === "number")) { + throw new Error('typeof startOffset === "number"' + " error: " + ("Argument startOffset must be of type number, given: " + _typeof(startOffset) || 0)); + } + + var node = { + type: "SectionMetadata", + section: section, + startOffset: startOffset, + size: size, + vectorOfSize: vectorOfSize + }; + return node; +} + +function producersSectionMetadata(producers) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ProducersSectionMetadata", + producers: producers + }; + return node; +} + +function producerMetadata(language, processedBy, sdk) { + if (!(_typeof(language) === "object" && typeof language.length !== "undefined")) { + throw new Error('typeof language === "object" && typeof language.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(processedBy) === "object" && typeof processedBy.length !== "undefined")) { + throw new Error('typeof processedBy === "object" && typeof processedBy.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(sdk) === "object" && typeof sdk.length !== "undefined")) { + throw new Error('typeof sdk === "object" && typeof sdk.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ProducerMetadata", + language: language, + processedBy: processedBy, + sdk: sdk + }; + return node; +} + +function producerMetadataVersionedName(name, version) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + if (!(typeof version === "string")) { + throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); + } + + var node = { + type: "ProducerMetadataVersionedName", + name: name, + version: version + }; + return node; +} + +function loopInstruction(label, resulttype, instr) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "LoopInstruction", + id: "loop", + label: label, + resulttype: resulttype, + instr: instr + }; + return node; +} + +function instr(id, object, args, namedArgs) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + + if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { + throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Instr", + id: id, + args: args + }; + + if (typeof object !== "undefined") { + node.object = object; + } + + if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { + node.namedArgs = namedArgs; + } + + return node; +} + +function ifInstruction(testLabel, test, result, consequent, alternate) { + if (!(_typeof(test) === "object" && typeof test.length !== "undefined")) { + throw new Error('typeof test === "object" && typeof test.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(consequent) === "object" && typeof consequent.length !== "undefined")) { + throw new Error('typeof consequent === "object" && typeof consequent.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(alternate) === "object" && typeof alternate.length !== "undefined")) { + throw new Error('typeof alternate === "object" && typeof alternate.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "IfInstruction", + id: "if", + testLabel: testLabel, + test: test, + result: result, + consequent: consequent, + alternate: alternate + }; + return node; +} + +function stringLiteral(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "StringLiteral", + value: value + }; + return node; +} + +function numberLiteral(value, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } + + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "NumberLiteral", + value: value, + raw: raw + }; + return node; +} + +function longNumberLiteral(value, raw) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "LongNumberLiteral", + value: value, + raw: raw + }; + return node; +} + +function floatLiteral(value, nan, inf, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } + + if (nan !== null && nan !== undefined) { + if (!(typeof nan === "boolean")) { + throw new Error('typeof nan === "boolean"' + " error: " + ("Argument nan must be of type boolean, given: " + _typeof(nan) || 0)); + } + } + + if (inf !== null && inf !== undefined) { + if (!(typeof inf === "boolean")) { + throw new Error('typeof inf === "boolean"' + " error: " + ("Argument inf must be of type boolean, given: " + _typeof(inf) || 0)); + } + } + + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "FloatLiteral", + value: value, + raw: raw + }; + + if (nan === true) { + node.nan = true; + } + + if (inf === true) { + node.inf = true; + } + + return node; +} + +function elem(table, offset, funcs) { + if (!(_typeof(offset) === "object" && typeof offset.length !== "undefined")) { + throw new Error('typeof offset === "object" && typeof offset.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(funcs) === "object" && typeof funcs.length !== "undefined")) { + throw new Error('typeof funcs === "object" && typeof funcs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Elem", + table: table, + offset: offset, + funcs: funcs + }; + return node; +} + +function indexInFuncSection(index) { + var node = { + type: "IndexInFuncSection", + index: index + }; + return node; +} + +function valtypeLiteral(name) { + var node = { + type: "ValtypeLiteral", + name: name + }; + return node; +} + +function typeInstruction(id, functype) { + var node = { + type: "TypeInstruction", + id: id, + functype: functype + }; + return node; +} + +function start(index) { + var node = { + type: "Start", + index: index + }; + return node; +} + +function globalType(valtype, mutability) { + var node = { + type: "GlobalType", + valtype: valtype, + mutability: mutability + }; + return node; +} + +function leadingComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "LeadingComment", + value: value + }; + return node; +} + +function blockComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "BlockComment", + value: value + }; + return node; +} + +function data(memoryIndex, offset, init) { + var node = { + type: "Data", + memoryIndex: memoryIndex, + offset: offset, + init: init + }; + return node; +} + +function global(globalType, init, name) { + if (!(_typeof(init) === "object" && typeof init.length !== "undefined")) { + throw new Error('typeof init === "object" && typeof init.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Global", + globalType: globalType, + init: init, + name: name + }; + return node; +} + +function table(elementType, limits, name, elements) { + if (!(limits.type === "Limit")) { + throw new Error('limits.type === "Limit"' + " error: " + ("Argument limits must be of type Limit, given: " + limits.type || 0)); + } + + if (elements !== null && elements !== undefined) { + if (!(_typeof(elements) === "object" && typeof elements.length !== "undefined")) { + throw new Error('typeof elements === "object" && typeof elements.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "Table", + elementType: elementType, + limits: limits, + name: name + }; + + if (typeof elements !== "undefined" && elements.length > 0) { + node.elements = elements; + } + + return node; +} + +function memory(limits, id) { + var node = { + type: "Memory", + limits: limits, + id: id + }; + return node; +} + +function funcImportDescr(id, signature) { + var node = { + type: "FuncImportDescr", + id: id, + signature: signature + }; + return node; +} + +function moduleImport(module, name, descr) { + if (!(typeof module === "string")) { + throw new Error('typeof module === "string"' + " error: " + ("Argument module must be of type string, given: " + _typeof(module) || 0)); + } + + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleImport", + module: module, + name: name, + descr: descr + }; + return node; +} + +function moduleExportDescr(exportType, id) { + var node = { + type: "ModuleExportDescr", + exportType: exportType, + id: id + }; + return node; +} + +function moduleExport(name, descr) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleExport", + name: name, + descr: descr + }; + return node; +} + +function limit(min, max) { + if (!(typeof min === "number")) { + throw new Error('typeof min === "number"' + " error: " + ("Argument min must be of type number, given: " + _typeof(min) || 0)); + } + + if (max !== null && max !== undefined) { + if (!(typeof max === "number")) { + throw new Error('typeof max === "number"' + " error: " + ("Argument max must be of type number, given: " + _typeof(max) || 0)); + } + } + + var node = { + type: "Limit", + min: min + }; + + if (typeof max !== "undefined") { + node.max = max; + } + + return node; +} + +function signature(params, results) { + if (!(_typeof(params) === "object" && typeof params.length !== "undefined")) { + throw new Error('typeof params === "object" && typeof params.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(results) === "object" && typeof results.length !== "undefined")) { + throw new Error('typeof results === "object" && typeof results.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Signature", + params: params, + results: results + }; + return node; +} + +function program(body) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Program", + body: body + }; + return node; +} + +function identifier(value, raw) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (raw !== null && raw !== undefined) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + } + + var node = { + type: "Identifier", + value: value + }; + + if (typeof raw !== "undefined") { + node.raw = raw; + } + + return node; +} + +function blockInstruction(label, instr, result) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "BlockInstruction", + id: "block", + label: label, + instr: instr, + result: result + }; + return node; +} + +function callInstruction(index, instrArgs, numeric) { + if (instrArgs !== null && instrArgs !== undefined) { + if (!(_typeof(instrArgs) === "object" && typeof instrArgs.length !== "undefined")) { + throw new Error('typeof instrArgs === "object" && typeof instrArgs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallInstruction", + id: "call", + index: index + }; + + if (typeof instrArgs !== "undefined" && instrArgs.length > 0) { + node.instrArgs = instrArgs; + } + + if (typeof numeric !== "undefined") { + node.numeric = numeric; + } + + return node; +} + +function callIndirectInstruction(signature, intrs) { + if (intrs !== null && intrs !== undefined) { + if (!(_typeof(intrs) === "object" && typeof intrs.length !== "undefined")) { + throw new Error('typeof intrs === "object" && typeof intrs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallIndirectInstruction", + id: "call_indirect", + signature: signature + }; + + if (typeof intrs !== "undefined" && intrs.length > 0) { + node.intrs = intrs; + } + + return node; +} + +function byteArray(values) { + if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { + throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ByteArray", + values: values + }; + return node; +} + +function func(name, signature, body, isExternal, metadata) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (isExternal !== null && isExternal !== undefined) { + if (!(typeof isExternal === "boolean")) { + throw new Error('typeof isExternal === "boolean"' + " error: " + ("Argument isExternal must be of type boolean, given: " + _typeof(isExternal) || 0)); + } + } + + var node = { + type: "Func", + name: name, + signature: signature, + body: body + }; + + if (isExternal === true) { + node.isExternal = true; + } + + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } + + return node; +} + +function internalBrUnless(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalBrUnless", + target: target + }; + return node; +} + +function internalGoto(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalGoto", + target: target + }; + return node; +} + +function internalCallExtern(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalCallExtern", + target: target + }; + return node; +} + +function internalEndAndReturn() { + var node = { + type: "InternalEndAndReturn" + }; + return node; +} + +var isModule = isTypeOf("Module"); +exports.isModule = isModule; +var isModuleMetadata = isTypeOf("ModuleMetadata"); +exports.isModuleMetadata = isModuleMetadata; +var isModuleNameMetadata = isTypeOf("ModuleNameMetadata"); +exports.isModuleNameMetadata = isModuleNameMetadata; +var isFunctionNameMetadata = isTypeOf("FunctionNameMetadata"); +exports.isFunctionNameMetadata = isFunctionNameMetadata; +var isLocalNameMetadata = isTypeOf("LocalNameMetadata"); +exports.isLocalNameMetadata = isLocalNameMetadata; +var isBinaryModule = isTypeOf("BinaryModule"); +exports.isBinaryModule = isBinaryModule; +var isQuoteModule = isTypeOf("QuoteModule"); +exports.isQuoteModule = isQuoteModule; +var isSectionMetadata = isTypeOf("SectionMetadata"); +exports.isSectionMetadata = isSectionMetadata; +var isProducersSectionMetadata = isTypeOf("ProducersSectionMetadata"); +exports.isProducersSectionMetadata = isProducersSectionMetadata; +var isProducerMetadata = isTypeOf("ProducerMetadata"); +exports.isProducerMetadata = isProducerMetadata; +var isProducerMetadataVersionedName = isTypeOf("ProducerMetadataVersionedName"); +exports.isProducerMetadataVersionedName = isProducerMetadataVersionedName; +var isLoopInstruction = isTypeOf("LoopInstruction"); +exports.isLoopInstruction = isLoopInstruction; +var isInstr = isTypeOf("Instr"); +exports.isInstr = isInstr; +var isIfInstruction = isTypeOf("IfInstruction"); +exports.isIfInstruction = isIfInstruction; +var isStringLiteral = isTypeOf("StringLiteral"); +exports.isStringLiteral = isStringLiteral; +var isNumberLiteral = isTypeOf("NumberLiteral"); +exports.isNumberLiteral = isNumberLiteral; +var isLongNumberLiteral = isTypeOf("LongNumberLiteral"); +exports.isLongNumberLiteral = isLongNumberLiteral; +var isFloatLiteral = isTypeOf("FloatLiteral"); +exports.isFloatLiteral = isFloatLiteral; +var isElem = isTypeOf("Elem"); +exports.isElem = isElem; +var isIndexInFuncSection = isTypeOf("IndexInFuncSection"); +exports.isIndexInFuncSection = isIndexInFuncSection; +var isValtypeLiteral = isTypeOf("ValtypeLiteral"); +exports.isValtypeLiteral = isValtypeLiteral; +var isTypeInstruction = isTypeOf("TypeInstruction"); +exports.isTypeInstruction = isTypeInstruction; +var isStart = isTypeOf("Start"); +exports.isStart = isStart; +var isGlobalType = isTypeOf("GlobalType"); +exports.isGlobalType = isGlobalType; +var isLeadingComment = isTypeOf("LeadingComment"); +exports.isLeadingComment = isLeadingComment; +var isBlockComment = isTypeOf("BlockComment"); +exports.isBlockComment = isBlockComment; +var isData = isTypeOf("Data"); +exports.isData = isData; +var isGlobal = isTypeOf("Global"); +exports.isGlobal = isGlobal; +var isTable = isTypeOf("Table"); +exports.isTable = isTable; +var isMemory = isTypeOf("Memory"); +exports.isMemory = isMemory; +var isFuncImportDescr = isTypeOf("FuncImportDescr"); +exports.isFuncImportDescr = isFuncImportDescr; +var isModuleImport = isTypeOf("ModuleImport"); +exports.isModuleImport = isModuleImport; +var isModuleExportDescr = isTypeOf("ModuleExportDescr"); +exports.isModuleExportDescr = isModuleExportDescr; +var isModuleExport = isTypeOf("ModuleExport"); +exports.isModuleExport = isModuleExport; +var isLimit = isTypeOf("Limit"); +exports.isLimit = isLimit; +var isSignature = isTypeOf("Signature"); +exports.isSignature = isSignature; +var isProgram = isTypeOf("Program"); +exports.isProgram = isProgram; +var isIdentifier = isTypeOf("Identifier"); +exports.isIdentifier = isIdentifier; +var isBlockInstruction = isTypeOf("BlockInstruction"); +exports.isBlockInstruction = isBlockInstruction; +var isCallInstruction = isTypeOf("CallInstruction"); +exports.isCallInstruction = isCallInstruction; +var isCallIndirectInstruction = isTypeOf("CallIndirectInstruction"); +exports.isCallIndirectInstruction = isCallIndirectInstruction; +var isByteArray = isTypeOf("ByteArray"); +exports.isByteArray = isByteArray; +var isFunc = isTypeOf("Func"); +exports.isFunc = isFunc; +var isInternalBrUnless = isTypeOf("InternalBrUnless"); +exports.isInternalBrUnless = isInternalBrUnless; +var isInternalGoto = isTypeOf("InternalGoto"); +exports.isInternalGoto = isInternalGoto; +var isInternalCallExtern = isTypeOf("InternalCallExtern"); +exports.isInternalCallExtern = isInternalCallExtern; +var isInternalEndAndReturn = isTypeOf("InternalEndAndReturn"); +exports.isInternalEndAndReturn = isInternalEndAndReturn; + +var isNode = function isNode(node) { + return isModule(node) || isModuleMetadata(node) || isModuleNameMetadata(node) || isFunctionNameMetadata(node) || isLocalNameMetadata(node) || isBinaryModule(node) || isQuoteModule(node) || isSectionMetadata(node) || isProducersSectionMetadata(node) || isProducerMetadata(node) || isProducerMetadataVersionedName(node) || isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isElem(node) || isIndexInFuncSection(node) || isValtypeLiteral(node) || isTypeInstruction(node) || isStart(node) || isGlobalType(node) || isLeadingComment(node) || isBlockComment(node) || isData(node) || isGlobal(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node) || isModuleImport(node) || isModuleExportDescr(node) || isModuleExport(node) || isLimit(node) || isSignature(node) || isProgram(node) || isIdentifier(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node) || isByteArray(node) || isFunc(node) || isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isNode = isNode; + +var isBlock = function isBlock(node) { + return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); +}; + +exports.isBlock = isBlock; + +var isInstruction = function isInstruction(node) { + return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); +}; + +exports.isInstruction = isInstruction; + +var isExpression = function isExpression(node) { + return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); +}; + +exports.isExpression = isExpression; + +var isNumericLiteral = function isNumericLiteral(node) { + return isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node); +}; + +exports.isNumericLiteral = isNumericLiteral; + +var isImportDescr = function isImportDescr(node) { + return isGlobalType(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node); +}; + +exports.isImportDescr = isImportDescr; + +var isIntrinsic = function isIntrinsic(node) { + return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isIntrinsic = isIntrinsic; +var assertModule = assertTypeOf("Module"); +exports.assertModule = assertModule; +var assertModuleMetadata = assertTypeOf("ModuleMetadata"); +exports.assertModuleMetadata = assertModuleMetadata; +var assertModuleNameMetadata = assertTypeOf("ModuleNameMetadata"); +exports.assertModuleNameMetadata = assertModuleNameMetadata; +var assertFunctionNameMetadata = assertTypeOf("FunctionNameMetadata"); +exports.assertFunctionNameMetadata = assertFunctionNameMetadata; +var assertLocalNameMetadata = assertTypeOf("LocalNameMetadata"); +exports.assertLocalNameMetadata = assertLocalNameMetadata; +var assertBinaryModule = assertTypeOf("BinaryModule"); +exports.assertBinaryModule = assertBinaryModule; +var assertQuoteModule = assertTypeOf("QuoteModule"); +exports.assertQuoteModule = assertQuoteModule; +var assertSectionMetadata = assertTypeOf("SectionMetadata"); +exports.assertSectionMetadata = assertSectionMetadata; +var assertProducersSectionMetadata = assertTypeOf("ProducersSectionMetadata"); +exports.assertProducersSectionMetadata = assertProducersSectionMetadata; +var assertProducerMetadata = assertTypeOf("ProducerMetadata"); +exports.assertProducerMetadata = assertProducerMetadata; +var assertProducerMetadataVersionedName = assertTypeOf("ProducerMetadataVersionedName"); +exports.assertProducerMetadataVersionedName = assertProducerMetadataVersionedName; +var assertLoopInstruction = assertTypeOf("LoopInstruction"); +exports.assertLoopInstruction = assertLoopInstruction; +var assertInstr = assertTypeOf("Instr"); +exports.assertInstr = assertInstr; +var assertIfInstruction = assertTypeOf("IfInstruction"); +exports.assertIfInstruction = assertIfInstruction; +var assertStringLiteral = assertTypeOf("StringLiteral"); +exports.assertStringLiteral = assertStringLiteral; +var assertNumberLiteral = assertTypeOf("NumberLiteral"); +exports.assertNumberLiteral = assertNumberLiteral; +var assertLongNumberLiteral = assertTypeOf("LongNumberLiteral"); +exports.assertLongNumberLiteral = assertLongNumberLiteral; +var assertFloatLiteral = assertTypeOf("FloatLiteral"); +exports.assertFloatLiteral = assertFloatLiteral; +var assertElem = assertTypeOf("Elem"); +exports.assertElem = assertElem; +var assertIndexInFuncSection = assertTypeOf("IndexInFuncSection"); +exports.assertIndexInFuncSection = assertIndexInFuncSection; +var assertValtypeLiteral = assertTypeOf("ValtypeLiteral"); +exports.assertValtypeLiteral = assertValtypeLiteral; +var assertTypeInstruction = assertTypeOf("TypeInstruction"); +exports.assertTypeInstruction = assertTypeInstruction; +var assertStart = assertTypeOf("Start"); +exports.assertStart = assertStart; +var assertGlobalType = assertTypeOf("GlobalType"); +exports.assertGlobalType = assertGlobalType; +var assertLeadingComment = assertTypeOf("LeadingComment"); +exports.assertLeadingComment = assertLeadingComment; +var assertBlockComment = assertTypeOf("BlockComment"); +exports.assertBlockComment = assertBlockComment; +var assertData = assertTypeOf("Data"); +exports.assertData = assertData; +var assertGlobal = assertTypeOf("Global"); +exports.assertGlobal = assertGlobal; +var assertTable = assertTypeOf("Table"); +exports.assertTable = assertTable; +var assertMemory = assertTypeOf("Memory"); +exports.assertMemory = assertMemory; +var assertFuncImportDescr = assertTypeOf("FuncImportDescr"); +exports.assertFuncImportDescr = assertFuncImportDescr; +var assertModuleImport = assertTypeOf("ModuleImport"); +exports.assertModuleImport = assertModuleImport; +var assertModuleExportDescr = assertTypeOf("ModuleExportDescr"); +exports.assertModuleExportDescr = assertModuleExportDescr; +var assertModuleExport = assertTypeOf("ModuleExport"); +exports.assertModuleExport = assertModuleExport; +var assertLimit = assertTypeOf("Limit"); +exports.assertLimit = assertLimit; +var assertSignature = assertTypeOf("Signature"); +exports.assertSignature = assertSignature; +var assertProgram = assertTypeOf("Program"); +exports.assertProgram = assertProgram; +var assertIdentifier = assertTypeOf("Identifier"); +exports.assertIdentifier = assertIdentifier; +var assertBlockInstruction = assertTypeOf("BlockInstruction"); +exports.assertBlockInstruction = assertBlockInstruction; +var assertCallInstruction = assertTypeOf("CallInstruction"); +exports.assertCallInstruction = assertCallInstruction; +var assertCallIndirectInstruction = assertTypeOf("CallIndirectInstruction"); +exports.assertCallIndirectInstruction = assertCallIndirectInstruction; +var assertByteArray = assertTypeOf("ByteArray"); +exports.assertByteArray = assertByteArray; +var assertFunc = assertTypeOf("Func"); +exports.assertFunc = assertFunc; +var assertInternalBrUnless = assertTypeOf("InternalBrUnless"); +exports.assertInternalBrUnless = assertInternalBrUnless; +var assertInternalGoto = assertTypeOf("InternalGoto"); +exports.assertInternalGoto = assertInternalGoto; +var assertInternalCallExtern = assertTypeOf("InternalCallExtern"); +exports.assertInternalCallExtern = assertInternalCallExtern; +var assertInternalEndAndReturn = assertTypeOf("InternalEndAndReturn"); +exports.assertInternalEndAndReturn = assertInternalEndAndReturn; +var unionTypesMap = { + Module: ["Node"], + ModuleMetadata: ["Node"], + ModuleNameMetadata: ["Node"], + FunctionNameMetadata: ["Node"], + LocalNameMetadata: ["Node"], + BinaryModule: ["Node"], + QuoteModule: ["Node"], + SectionMetadata: ["Node"], + ProducersSectionMetadata: ["Node"], + ProducerMetadata: ["Node"], + ProducerMetadataVersionedName: ["Node"], + LoopInstruction: ["Node", "Block", "Instruction"], + Instr: ["Node", "Expression", "Instruction"], + IfInstruction: ["Node", "Instruction"], + StringLiteral: ["Node", "Expression"], + NumberLiteral: ["Node", "NumericLiteral", "Expression"], + LongNumberLiteral: ["Node", "NumericLiteral", "Expression"], + FloatLiteral: ["Node", "NumericLiteral", "Expression"], + Elem: ["Node"], + IndexInFuncSection: ["Node"], + ValtypeLiteral: ["Node", "Expression"], + TypeInstruction: ["Node", "Instruction"], + Start: ["Node"], + GlobalType: ["Node", "ImportDescr"], + LeadingComment: ["Node"], + BlockComment: ["Node"], + Data: ["Node"], + Global: ["Node"], + Table: ["Node", "ImportDescr"], + Memory: ["Node", "ImportDescr"], + FuncImportDescr: ["Node", "ImportDescr"], + ModuleImport: ["Node"], + ModuleExportDescr: ["Node"], + ModuleExport: ["Node"], + Limit: ["Node"], + Signature: ["Node"], + Program: ["Node"], + Identifier: ["Node", "Expression"], + BlockInstruction: ["Node", "Block", "Instruction"], + CallInstruction: ["Node", "Instruction"], + CallIndirectInstruction: ["Node", "Instruction"], + ByteArray: ["Node"], + Func: ["Node", "Block"], + InternalBrUnless: ["Node", "Intrinsic"], + InternalGoto: ["Node", "Intrinsic"], + InternalCallExtern: ["Node", "Intrinsic"], + InternalEndAndReturn: ["Node", "Intrinsic"] +}; +exports.unionTypesMap = unionTypesMap; +var nodeAndUnionTypes = ["Module", "ModuleMetadata", "ModuleNameMetadata", "FunctionNameMetadata", "LocalNameMetadata", "BinaryModule", "QuoteModule", "SectionMetadata", "ProducersSectionMetadata", "ProducerMetadata", "ProducerMetadataVersionedName", "LoopInstruction", "Instr", "IfInstruction", "StringLiteral", "NumberLiteral", "LongNumberLiteral", "FloatLiteral", "Elem", "IndexInFuncSection", "ValtypeLiteral", "TypeInstruction", "Start", "GlobalType", "LeadingComment", "BlockComment", "Data", "Global", "Table", "Memory", "FuncImportDescr", "ModuleImport", "ModuleExportDescr", "ModuleExport", "Limit", "Signature", "Program", "Identifier", "BlockInstruction", "CallInstruction", "CallIndirectInstruction", "ByteArray", "Func", "InternalBrUnless", "InternalGoto", "InternalCallExtern", "InternalEndAndReturn", "Node", "Block", "Instruction", "Expression", "NumericLiteral", "ImportDescr", "Intrinsic"]; +exports.nodeAndUnionTypes = nodeAndUnionTypes; + +/***/ }), + +/***/ 14004: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.signatures = void 0; + +function sign(input, output) { + return [input, output]; +} + +var u32 = "u32"; +var i32 = "i32"; +var i64 = "i64"; +var f32 = "f32"; +var f64 = "f64"; + +var vector = function vector(t) { + var vecType = [t]; // $FlowIgnore + + vecType.vector = true; + return vecType; +}; + +var controlInstructions = { + unreachable: sign([], []), + nop: sign([], []), + // block ? + // loop ? + // if ? + // if else ? + br: sign([u32], []), + br_if: sign([u32], []), + br_table: sign(vector(u32), []), + return: sign([], []), + call: sign([u32], []), + call_indirect: sign([u32], []) +}; +var parametricInstructions = { + drop: sign([], []), + select: sign([], []) +}; +var variableInstructions = { + get_local: sign([u32], []), + set_local: sign([u32], []), + tee_local: sign([u32], []), + get_global: sign([u32], []), + set_global: sign([u32], []) +}; +var memoryInstructions = { + "i32.load": sign([u32, u32], [i32]), + "i64.load": sign([u32, u32], []), + "f32.load": sign([u32, u32], []), + "f64.load": sign([u32, u32], []), + "i32.load8_s": sign([u32, u32], [i32]), + "i32.load8_u": sign([u32, u32], [i32]), + "i32.load16_s": sign([u32, u32], [i32]), + "i32.load16_u": sign([u32, u32], [i32]), + "i64.load8_s": sign([u32, u32], [i64]), + "i64.load8_u": sign([u32, u32], [i64]), + "i64.load16_s": sign([u32, u32], [i64]), + "i64.load16_u": sign([u32, u32], [i64]), + "i64.load32_s": sign([u32, u32], [i64]), + "i64.load32_u": sign([u32, u32], [i64]), + "i32.store": sign([u32, u32], []), + "i64.store": sign([u32, u32], []), + "f32.store": sign([u32, u32], []), + "f64.store": sign([u32, u32], []), + "i32.store8": sign([u32, u32], []), + "i32.store16": sign([u32, u32], []), + "i64.store8": sign([u32, u32], []), + "i64.store16": sign([u32, u32], []), + "i64.store32": sign([u32, u32], []), + current_memory: sign([], []), + grow_memory: sign([], []) +}; +var numericInstructions = { + "i32.const": sign([i32], [i32]), + "i64.const": sign([i64], [i64]), + "f32.const": sign([f32], [f32]), + "f64.const": sign([f64], [f64]), + "i32.eqz": sign([i32], [i32]), + "i32.eq": sign([i32, i32], [i32]), + "i32.ne": sign([i32, i32], [i32]), + "i32.lt_s": sign([i32, i32], [i32]), + "i32.lt_u": sign([i32, i32], [i32]), + "i32.gt_s": sign([i32, i32], [i32]), + "i32.gt_u": sign([i32, i32], [i32]), + "i32.le_s": sign([i32, i32], [i32]), + "i32.le_u": sign([i32, i32], [i32]), + "i32.ge_s": sign([i32, i32], [i32]), + "i32.ge_u": sign([i32, i32], [i32]), + "i64.eqz": sign([i64], [i64]), + "i64.eq": sign([i64, i64], [i32]), + "i64.ne": sign([i64, i64], [i32]), + "i64.lt_s": sign([i64, i64], [i32]), + "i64.lt_u": sign([i64, i64], [i32]), + "i64.gt_s": sign([i64, i64], [i32]), + "i64.gt_u": sign([i64, i64], [i32]), + "i64.le_s": sign([i64, i64], [i32]), + "i64.le_u": sign([i64, i64], [i32]), + "i64.ge_s": sign([i64, i64], [i32]), + "i64.ge_u": sign([i64, i64], [i32]), + "f32.eq": sign([f32, f32], [i32]), + "f32.ne": sign([f32, f32], [i32]), + "f32.lt": sign([f32, f32], [i32]), + "f32.gt": sign([f32, f32], [i32]), + "f32.le": sign([f32, f32], [i32]), + "f32.ge": sign([f32, f32], [i32]), + "f64.eq": sign([f64, f64], [i32]), + "f64.ne": sign([f64, f64], [i32]), + "f64.lt": sign([f64, f64], [i32]), + "f64.gt": sign([f64, f64], [i32]), + "f64.le": sign([f64, f64], [i32]), + "f64.ge": sign([f64, f64], [i32]), + "i32.clz": sign([i32], [i32]), + "i32.ctz": sign([i32], [i32]), + "i32.popcnt": sign([i32], [i32]), + "i32.add": sign([i32, i32], [i32]), + "i32.sub": sign([i32, i32], [i32]), + "i32.mul": sign([i32, i32], [i32]), + "i32.div_s": sign([i32, i32], [i32]), + "i32.div_u": sign([i32, i32], [i32]), + "i32.rem_s": sign([i32, i32], [i32]), + "i32.rem_u": sign([i32, i32], [i32]), + "i32.and": sign([i32, i32], [i32]), + "i32.or": sign([i32, i32], [i32]), + "i32.xor": sign([i32, i32], [i32]), + "i32.shl": sign([i32, i32], [i32]), + "i32.shr_s": sign([i32, i32], [i32]), + "i32.shr_u": sign([i32, i32], [i32]), + "i32.rotl": sign([i32, i32], [i32]), + "i32.rotr": sign([i32, i32], [i32]), + "i64.clz": sign([i64], [i64]), + "i64.ctz": sign([i64], [i64]), + "i64.popcnt": sign([i64], [i64]), + "i64.add": sign([i64, i64], [i64]), + "i64.sub": sign([i64, i64], [i64]), + "i64.mul": sign([i64, i64], [i64]), + "i64.div_s": sign([i64, i64], [i64]), + "i64.div_u": sign([i64, i64], [i64]), + "i64.rem_s": sign([i64, i64], [i64]), + "i64.rem_u": sign([i64, i64], [i64]), + "i64.and": sign([i64, i64], [i64]), + "i64.or": sign([i64, i64], [i64]), + "i64.xor": sign([i64, i64], [i64]), + "i64.shl": sign([i64, i64], [i64]), + "i64.shr_s": sign([i64, i64], [i64]), + "i64.shr_u": sign([i64, i64], [i64]), + "i64.rotl": sign([i64, i64], [i64]), + "i64.rotr": sign([i64, i64], [i64]), + "f32.abs": sign([f32], [f32]), + "f32.neg": sign([f32], [f32]), + "f32.ceil": sign([f32], [f32]), + "f32.floor": sign([f32], [f32]), + "f32.trunc": sign([f32], [f32]), + "f32.nearest": sign([f32], [f32]), + "f32.sqrt": sign([f32], [f32]), + "f32.add": sign([f32, f32], [f32]), + "f32.sub": sign([f32, f32], [f32]), + "f32.mul": sign([f32, f32], [f32]), + "f32.div": sign([f32, f32], [f32]), + "f32.min": sign([f32, f32], [f32]), + "f32.max": sign([f32, f32], [f32]), + "f32.copysign": sign([f32, f32], [f32]), + "f64.abs": sign([f64], [f64]), + "f64.neg": sign([f64], [f64]), + "f64.ceil": sign([f64], [f64]), + "f64.floor": sign([f64], [f64]), + "f64.trunc": sign([f64], [f64]), + "f64.nearest": sign([f64], [f64]), + "f64.sqrt": sign([f64], [f64]), + "f64.add": sign([f64, f64], [f64]), + "f64.sub": sign([f64, f64], [f64]), + "f64.mul": sign([f64, f64], [f64]), + "f64.div": sign([f64, f64], [f64]), + "f64.min": sign([f64, f64], [f64]), + "f64.max": sign([f64, f64], [f64]), + "f64.copysign": sign([f64, f64], [f64]), + "i32.wrap/i64": sign([i64], [i32]), + "i32.trunc_s/f32": sign([f32], [i32]), + "i32.trunc_u/f32": sign([f32], [i32]), + "i32.trunc_s/f64": sign([f32], [i32]), + "i32.trunc_u/f64": sign([f64], [i32]), + "i64.extend_s/i32": sign([i32], [i64]), + "i64.extend_u/i32": sign([i32], [i64]), + "i64.trunc_s/f32": sign([f32], [i64]), + "i64.trunc_u/f32": sign([f32], [i64]), + "i64.trunc_s/f64": sign([f64], [i64]), + "i64.trunc_u/f64": sign([f64], [i64]), + "f32.convert_s/i32": sign([i32], [f32]), + "f32.convert_u/i32": sign([i32], [f32]), + "f32.convert_s/i64": sign([i64], [f32]), + "f32.convert_u/i64": sign([i64], [f32]), + "f32.demote/f64": sign([f64], [f32]), + "f64.convert_s/i32": sign([i32], [f64]), + "f64.convert_u/i32": sign([i32], [f64]), + "f64.convert_s/i64": sign([i64], [f64]), + "f64.convert_u/i64": sign([i64], [f64]), + "f64.promote/f32": sign([f32], [f64]), + "i32.reinterpret/f32": sign([f32], [i32]), + "i64.reinterpret/f64": sign([f64], [i64]), + "f32.reinterpret/i32": sign([i32], [f32]), + "f64.reinterpret/i64": sign([i64], [f64]) +}; +var signatures = Object.assign({}, controlInstructions, parametricInstructions, variableInstructions, memoryInstructions, numericInstructions); +exports.signatures = signatures; + +/***/ }), + +/***/ 34390: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.traverse = traverse; + +var _nodePath = __webpack_require__(27110); + +var _nodes = __webpack_require__(36588); + +// recursively walks the AST starting at the given node. The callback is invoked for +// and object that has a 'type' property. +function walk(context, callback) { + var stop = false; + + function innerWalk(context, callback) { + if (stop) { + return; + } + + var node = context.node; + + if (node === undefined) { + console.warn("traversing with an empty context"); + return; + } + + if (node._deleted === true) { + return; + } + + var path = (0, _nodePath.createPath)(context); + callback(node.type, path); + + if (path.shouldStop) { + stop = true; + return; + } + + Object.keys(node).forEach(function (prop) { + var value = node[prop]; + + if (value === null || value === undefined) { + return; + } + + var valueAsArray = Array.isArray(value) ? value : [value]; + valueAsArray.forEach(function (childNode) { + if (typeof childNode.type === "string") { + var childContext = { + node: childNode, + parentKey: prop, + parentPath: path, + shouldStop: false, + inList: Array.isArray(value) + }; + innerWalk(childContext, callback); + } + }); + }); + } + + innerWalk(context, callback); +} + +var noop = function noop() {}; + +function traverse(node, visitors) { + var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop; + var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop; + Object.keys(visitors).forEach(function (visitor) { + if (!_nodes.nodeAndUnionTypes.includes(visitor)) { + throw new Error("Unexpected visitor ".concat(visitor)); + } + }); + var context = { + node: node, + inList: false, + shouldStop: false, + parentPath: null, + parentKey: null + }; + walk(context, function (type, path) { + if (typeof visitors[type] === "function") { + before(type, path); + visitors[type](path); + after(type, path); + } + + var unionTypes = _nodes.unionTypesMap[type]; + + if (!unionTypes) { + throw new Error("Unexpected node type ".concat(type)); + } + + unionTypes.forEach(function (unionType) { + if (typeof visitors[unionType] === "function") { + before(unionType, path); + visitors[unionType](path); + after(unionType, path); + } + }); + }); +} + +/***/ }), + +/***/ 26038: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isAnonymous = isAnonymous; +exports.getSectionMetadata = getSectionMetadata; +exports.getSectionMetadatas = getSectionMetadatas; +exports.sortSectionMetadata = sortSectionMetadata; +exports.orderedInsertNode = orderedInsertNode; +exports.assertHasLoc = assertHasLoc; +exports.getEndOfSection = getEndOfSection; +exports.shiftLoc = shiftLoc; +exports.shiftSection = shiftSection; +exports.signatureForOpcode = signatureForOpcode; +exports.getUniqueNameGenerator = getUniqueNameGenerator; +exports.getStartByteOffset = getStartByteOffset; +exports.getEndByteOffset = getEndByteOffset; +exports.getFunctionBeginingByteOffset = getFunctionBeginingByteOffset; +exports.getEndBlockByteOffset = getEndBlockByteOffset; +exports.getStartBlockByteOffset = getStartBlockByteOffset; + +var _signatures = __webpack_require__(14004); + +var _traverse = __webpack_require__(34390); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(97527)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function isAnonymous(ident) { + return ident.raw === ""; +} + +function getSectionMetadata(ast, name) { + var section; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata) { + function SectionMetadata(_x) { + return _SectionMetadata.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata.toString(); + }; + + return SectionMetadata; + }(function (_ref) { + var node = _ref.node; + + if (node.section === name) { + section = node; + } + }) + }); + return section; +} + +function getSectionMetadatas(ast, name) { + var sections = []; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata2) { + function SectionMetadata(_x2) { + return _SectionMetadata2.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata2.toString(); + }; + + return SectionMetadata; + }(function (_ref2) { + var node = _ref2.node; + + if (node.section === name) { + sections.push(node); + } + }) + }); + return sections; +} + +function sortSectionMetadata(m) { + if (m.metadata == null) { + console.warn("sortSectionMetadata: no metadata to sort"); + return; + } // $FlowIgnore + + + m.metadata.sections.sort(function (a, b) { + var aId = _helperWasmBytecode.default.sections[a.section]; + var bId = _helperWasmBytecode.default.sections[b.section]; + + if (typeof aId !== "number" || typeof bId !== "number") { + throw new Error("Section id not found"); + } + + return aId - bId; + }); +} + +function orderedInsertNode(m, n) { + assertHasLoc(n); + var didInsert = false; + + if (n.type === "ModuleExport") { + m.fields.push(n); + return; + } + + m.fields = m.fields.reduce(function (acc, field) { + var fieldEndCol = Infinity; + + if (field.loc != null) { + // $FlowIgnore + fieldEndCol = field.loc.end.column; + } // $FlowIgnore: assertHasLoc ensures that + + + if (didInsert === false && n.loc.start.column < fieldEndCol) { + didInsert = true; + acc.push(n); + } + + acc.push(field); + return acc; + }, []); // Handles empty modules or n is the last element + + if (didInsert === false) { + m.fields.push(n); + } +} + +function assertHasLoc(n) { + if (n.loc == null || n.loc.start == null || n.loc.end == null) { + throw new Error("Internal failure: node (".concat(JSON.stringify(n.type), ") has no location information")); + } +} + +function getEndOfSection(s) { + assertHasLoc(s.size); + return s.startOffset + s.size.value + ( // $FlowIgnore + s.size.loc.end.column - s.size.loc.start.column); +} + +function shiftLoc(node, delta) { + // $FlowIgnore + node.loc.start.column += delta; // $FlowIgnore + + node.loc.end.column += delta; +} + +function shiftSection(ast, node, delta) { + if (node.type !== "SectionMetadata") { + throw new Error("Can not shift node " + JSON.stringify(node.type)); + } + + node.startOffset += delta; + + if (_typeof(node.size.loc) === "object") { + shiftLoc(node.size, delta); + } // Custom sections doesn't have vectorOfSize + + + if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { + shiftLoc(node.vectorOfSize, delta); + } + + var sectionName = node.section; // shift node locations within that section + + (0, _traverse.traverse)(ast, { + Node: function Node(_ref3) { + var node = _ref3.node; + var section = (0, _helperWasmBytecode.getSectionForNode)(node); + + if (section === sectionName && _typeof(node.loc) === "object") { + shiftLoc(node, delta); + } + } + }); +} + +function signatureForOpcode(object, name) { + var opcodeName = name; + + if (object !== undefined && object !== "") { + opcodeName = object + "." + name; + } + + var sign = _signatures.signatures[opcodeName]; + + if (sign == undefined) { + // TODO: Uncomment this when br_table and others has been done + //throw new Error("Invalid opcode: "+opcodeName); + return [object, object]; + } + + return sign[0]; +} + +function getUniqueNameGenerator() { + var inc = {}; + return function () { + var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + + if (!(prefix in inc)) { + inc[prefix] = 0; + } else { + inc[prefix] = inc[prefix] + 1; + } + + return prefix + "_" + inc[prefix]; + }; +} + +function getStartByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.start === "undefined") { + throw new Error( // $FlowIgnore + "Can not get byte offset without loc informations, node: " + String(n.id)); + } + + return n.loc.start.column; +} + +function getEndByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.end === "undefined") { + throw new Error("Can not get byte offset without loc informations, node: " + n.type); + } + + return n.loc.end.column; +} + +function getFunctionBeginingByteOffset(n) { + if (!(n.body.length > 0)) { + throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var _n$body = _slicedToArray(n.body, 1), + firstInstruction = _n$body[0]; + + return getStartByteOffset(firstInstruction); +} + +function getEndBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var lastInstruction; + + if (n.instr) { + // $FlowIgnore + lastInstruction = n.instr[n.instr.length - 1]; + } + + if (n.body) { + // $FlowIgnore + lastInstruction = n.body[n.body.length - 1]; + } + + if (!(_typeof(lastInstruction) === "object")) { + throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(lastInstruction); +} + +function getStartBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var fistInstruction; + + if (n.instr) { + // $FlowIgnore + var _n$instr = _slicedToArray(n.instr, 1); + + fistInstruction = _n$instr[0]; + } + + if (n.body) { + // $FlowIgnore + var _n$body2 = _slicedToArray(n.body, 1); + + fistInstruction = _n$body2[0]; + } + + if (!(_typeof(fistInstruction) === "object")) { + throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(fistInstruction); +} + +/***/ }), + +/***/ 83268: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = parse; + +function parse(input) { + input = input.toUpperCase(); + var splitIndex = input.indexOf("P"); + var mantissa, exponent; + + if (splitIndex !== -1) { + mantissa = input.substring(0, splitIndex); + exponent = parseInt(input.substring(splitIndex + 1)); + } else { + mantissa = input; + exponent = 0; + } + + var dotIndex = mantissa.indexOf("."); + + if (dotIndex !== -1) { + var integerPart = parseInt(mantissa.substring(0, dotIndex), 16); + var sign = Math.sign(integerPart); + integerPart = sign * integerPart; + var fractionLength = mantissa.length - dotIndex - 1; + var fractionalPart = parseInt(mantissa.substring(dotIndex + 1), 16); + var fraction = fractionLength > 0 ? fractionalPart / Math.pow(16, fractionLength) : 0; + + if (sign === 0) { + if (fraction === 0) { + mantissa = sign; + } else { + if (Object.is(sign, -0)) { + mantissa = -fraction; + } else { + mantissa = fraction; + } + } + } else { + mantissa = sign * (integerPart + fraction); + } + } else { + mantissa = parseInt(mantissa, 16); + } + + return mantissa * (splitIndex !== -1 ? Math.pow(2, exponent) : 1); +} + +/***/ }), + +/***/ 36194: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var RuntimeError = +/*#__PURE__*/ +function (_Error) { + _inherits(RuntimeError, _Error); + + function RuntimeError() { + _classCallCheck(this, RuntimeError); + + return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); + } + + return RuntimeError; +}(Error); + +exports.RuntimeError = RuntimeError; + +var CompileError = +/*#__PURE__*/ +function (_Error2) { + _inherits(CompileError, _Error2); + + function CompileError() { + _classCallCheck(this, CompileError); + + return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); + } + + return CompileError; +}(Error); + +exports.CompileError = CompileError; + +var LinkError = +/*#__PURE__*/ +function (_Error3) { + _inherits(LinkError, _Error3); + + function LinkError() { + _classCallCheck(this, LinkError); + + return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); + } + + return LinkError; +}(Error); + +exports.LinkError = LinkError; + +/***/ }), + +/***/ 57827: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.overrideBytesInBuffer = overrideBytesInBuffer; +exports.makeBuffer = makeBuffer; +exports.fromHexdump = fromHexdump; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function concatUint8Arrays() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; + } + + var totalLength = arrays.reduce(function (a, b) { + return a + b.length; + }, 0); + var result = new Uint8Array(totalLength); + var offset = 0; + + for (var _i = 0; _i < arrays.length; _i++) { + var arr = arrays[_i]; + + if (arr instanceof Uint8Array === false) { + throw new Error("arr must be of type Uint8Array"); + } + + result.set(arr, offset); + offset += arr.length; + } + + return result; +} + +function overrideBytesInBuffer(buffer, startLoc, endLoc, newBytes) { + var beforeBytes = buffer.slice(0, startLoc); + var afterBytes = buffer.slice(endLoc, buffer.length); // replacement is empty, we can omit it + + if (newBytes.length === 0) { + return concatUint8Arrays(beforeBytes, afterBytes); + } + + var replacement = Uint8Array.from(newBytes); + return concatUint8Arrays(beforeBytes, replacement, afterBytes); +} + +function makeBuffer() { + for (var _len2 = arguments.length, splitedBytes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + splitedBytes[_key2] = arguments[_key2]; + } + + var bytes = [].concat.apply([], splitedBytes); + return new Uint8Array(bytes).buffer; +} + +function fromHexdump(str) { + var lines = str.split("\n"); // remove any leading left whitespace + + lines = lines.map(function (line) { + return line.trim(); + }); + var bytes = lines.reduce(function (acc, line) { + var cols = line.split(" "); // remove the offset, left column + + cols.shift(); + cols = cols.filter(function (x) { + return x !== ""; + }); + var bytes = cols.map(function (x) { + return parseInt(x, 16); + }); + acc.push.apply(acc, _toConsumableArray(bytes)); + return acc; + }, []); + return Buffer.from(bytes); +} + +/***/ }), + +/***/ 48333: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.codeFrameFromAst = codeFrameFromAst; +exports.codeFrameFromSource = codeFrameFromSource; + +var _wastPrinter = __webpack_require__(45378); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var SHOW_LINES_AROUND_POINTER = 5; + +function repeat(char, nb) { + return Array(nb).fill(char).join(""); +} // TODO(sven): allow arbitrary ast nodes + + +function codeFrameFromAst(ast, loc) { + return codeFrameFromSource((0, _wastPrinter.print)(ast), loc); +} + +function codeFrameFromSource(source, loc) { + var start = loc.start, + end = loc.end; + var length = 1; + + if (_typeof(end) === "object") { + length = end.column - start.column + 1; + } + + return source.split("\n").reduce(function (acc, line, lineNbr) { + if (Math.abs(start.line - lineNbr) < SHOW_LINES_AROUND_POINTER) { + acc += line + "\n"; + } // Add a new line with the pointer padded left + + + if (lineNbr === start.line - 1) { + acc += repeat(" ", start.column - 1); + acc += repeat("^", length); + acc += "\n"; + } + + return acc; + }, ""); +} + +/***/ }), + +/***/ 38902: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.makeTransition = makeTransition; +exports.FSM = void 0; + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var STOP = Symbol("STOP"); + +function makeTransition(regex, nextState) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$n = _ref.n, + n = _ref$n === void 0 ? 1 : _ref$n, + allowedSeparator = _ref.allowedSeparator; + + return function (instance) { + if (allowedSeparator) { + if (instance.input[instance.ptr] === allowedSeparator) { + if (regex.test(instance.input.substring(instance.ptr - 1, instance.ptr))) { + // Consume the separator and stay in current state + return [instance.currentState, 1]; + } else { + return [instance.terminatingState, 0]; + } + } + } + + if (regex.test(instance.input.substring(instance.ptr, instance.ptr + n))) { + return [nextState, n]; + } + + return false; + }; +} + +function combineTransitions(transitions) { + return function () { + var match = false; + var currentTransitions = transitions[this.currentState] || []; + + for (var i = 0; i < currentTransitions.length; ++i) { + match = currentTransitions[i](this); + + if (match !== false) { + break; + } + } + + return match || [this.terminatingState, 0]; + }; +} + +var FSM = +/*#__PURE__*/ +function () { + function FSM(transitions, initialState) { + var terminatingState = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : STOP; + + _classCallCheck(this, FSM); + + this.initialState = initialState; + this.terminatingState = terminatingState; + + if (terminatingState === STOP || !transitions[terminatingState]) { + transitions[terminatingState] = []; + } + + this.transitionFunction = combineTransitions.call(this, transitions); + } + + _createClass(FSM, [{ + key: "run", + value: function run(input) { + this.input = input; + this.ptr = 0; + this.currentState = this.initialState; + var value = ""; + var eatLength, nextState; + + while (this.currentState !== this.terminatingState && this.ptr < this.input.length) { + var _transitionFunction = this.transitionFunction(); + + var _transitionFunction2 = _slicedToArray(_transitionFunction, 2); + + nextState = _transitionFunction2[0]; + eatLength = _transitionFunction2[1]; + value += this.input.substring(this.ptr, this.ptr += eatLength); + this.currentState = nextState; + } + + return value; + } + }]); + + return FSM; +}(); + +exports.FSM = FSM; + +/***/ }), + +/***/ 71234: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.moduleContextFromModuleAST = moduleContextFromModuleAST; +exports.ModuleContext = void 0; + +var _ast = __webpack_require__(98688); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function moduleContextFromModuleAST(m) { + var moduleContext = new ModuleContext(); + + if (!(m.type === "Module")) { + throw new Error('m.type === "Module"' + " error: " + (undefined || "unknown")); + } + + m.fields.forEach(function (field) { + switch (field.type) { + case "Start": + { + moduleContext.setStart(field.index); + break; + } + + case "TypeInstruction": + { + moduleContext.addType(field); + break; + } + + case "Func": + { + moduleContext.addFunction(field); + break; + } + + case "Global": + { + moduleContext.defineGlobal(field); + break; + } + + case "ModuleImport": + { + switch (field.descr.type) { + case "GlobalType": + { + moduleContext.importGlobal(field.descr.valtype, field.descr.mutability); + break; + } + + case "Memory": + { + moduleContext.addMemory(field.descr.limits.min, field.descr.limits.max); + break; + } + + case "FuncImportDescr": + { + moduleContext.importFunction(field.descr); + break; + } + + case "Table": + { + // FIXME(sven): not implemented yet + break; + } + + default: + throw new Error("Unsupported ModuleImport of type " + JSON.stringify(field.descr.type)); + } + + break; + } + + case "Memory": + { + moduleContext.addMemory(field.limits.min, field.limits.max); + break; + } + } + }); + return moduleContext; +} +/** + * Module context for type checking + */ + + +var ModuleContext = +/*#__PURE__*/ +function () { + function ModuleContext() { + _classCallCheck(this, ModuleContext); + + this.funcs = []; + this.funcsOffsetByIdentifier = []; + this.types = []; + this.globals = []; + this.globalsOffsetByIdentifier = []; + this.mems = []; // Current stack frame + + this.locals = []; + this.labels = []; + this.return = []; + this.debugName = "unknown"; + this.start = null; + } + /** + * Set start segment + */ + + + _createClass(ModuleContext, [{ + key: "setStart", + value: function setStart(index) { + this.start = index.value; + } + /** + * Get start function + */ + + }, { + key: "getStart", + value: function getStart() { + return this.start; + } + /** + * Reset the active stack frame + */ + + }, { + key: "newContext", + value: function newContext(debugName, expectedResult) { + this.locals = []; + this.labels = [expectedResult]; + this.return = expectedResult; + this.debugName = debugName; + } + /** + * Functions + */ + + }, { + key: "addFunction", + value: function addFunction(func + /*: Func*/ + ) { + // eslint-disable-next-line prefer-const + var _ref = func.signature || {}, + _ref$params = _ref.params, + args = _ref$params === void 0 ? [] : _ref$params, + _ref$results = _ref.results, + result = _ref$results === void 0 ? [] : _ref$results; + + args = args.map(function (arg) { + return arg.valtype; + }); + this.funcs.push({ + args: args, + result: result + }); + + if (typeof func.name !== "undefined") { + this.funcsOffsetByIdentifier[func.name.value] = this.funcs.length - 1; + } + } + }, { + key: "importFunction", + value: function importFunction(funcimport) { + if ((0, _ast.isSignature)(funcimport.signature)) { + // eslint-disable-next-line prefer-const + var _funcimport$signature = funcimport.signature, + args = _funcimport$signature.params, + result = _funcimport$signature.results; + args = args.map(function (arg) { + return arg.valtype; + }); + this.funcs.push({ + args: args, + result: result + }); + } else { + if (!(0, _ast.isNumberLiteral)(funcimport.signature)) { + throw new Error('isNumberLiteral(funcimport.signature)' + " error: " + (undefined || "unknown")); + } + + var typeId = funcimport.signature.value; + + if (!this.hasType(typeId)) { + throw new Error('this.hasType(typeId)' + " error: " + (undefined || "unknown")); + } + + var signature = this.getType(typeId); + this.funcs.push({ + args: signature.params.map(function (arg) { + return arg.valtype; + }), + result: signature.results + }); + } + + if (typeof funcimport.id !== "undefined") { + // imports are first, we can assume their index in the array + this.funcsOffsetByIdentifier[funcimport.id.value] = this.funcs.length - 1; + } + } + }, { + key: "hasFunction", + value: function hasFunction(index) { + return typeof this.getFunction(index) !== "undefined"; + } + }, { + key: "getFunction", + value: function getFunction(index) { + if (typeof index !== "number") { + throw new Error("getFunction only supported for number index"); + } + + return this.funcs[index]; + } + }, { + key: "getFunctionOffsetByIdentifier", + value: function getFunctionOffsetByIdentifier(name) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown")); + } + + return this.funcsOffsetByIdentifier[name]; + } + /** + * Labels + */ + + }, { + key: "addLabel", + value: function addLabel(result) { + this.labels.unshift(result); + } + }, { + key: "hasLabel", + value: function hasLabel(index) { + return this.labels.length > index && index >= 0; + } + }, { + key: "getLabel", + value: function getLabel(index) { + return this.labels[index]; + } + }, { + key: "popLabel", + value: function popLabel() { + this.labels.shift(); + } + /** + * Locals + */ + + }, { + key: "hasLocal", + value: function hasLocal(index) { + return typeof this.getLocal(index) !== "undefined"; + } + }, { + key: "getLocal", + value: function getLocal(index) { + return this.locals[index]; + } + }, { + key: "addLocal", + value: function addLocal(type) { + this.locals.push(type); + } + /** + * Types + */ + + }, { + key: "addType", + value: function addType(type) { + if (!(type.functype.type === "Signature")) { + throw new Error('type.functype.type === "Signature"' + " error: " + (undefined || "unknown")); + } + + this.types.push(type.functype); + } + }, { + key: "hasType", + value: function hasType(index) { + return this.types[index] !== undefined; + } + }, { + key: "getType", + value: function getType(index) { + return this.types[index]; + } + /** + * Globals + */ + + }, { + key: "hasGlobal", + value: function hasGlobal(index) { + return this.globals.length > index && index >= 0; + } + }, { + key: "getGlobal", + value: function getGlobal(index) { + return this.globals[index].type; + } + }, { + key: "getGlobalOffsetByIdentifier", + value: function getGlobalOffsetByIdentifier(name) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown")); + } + + return this.globalsOffsetByIdentifier[name]; + } + }, { + key: "defineGlobal", + value: function defineGlobal(global + /*: Global*/ + ) { + var type = global.globalType.valtype; + var mutability = global.globalType.mutability; + this.globals.push({ + type: type, + mutability: mutability + }); + + if (typeof global.name !== "undefined") { + this.globalsOffsetByIdentifier[global.name.value] = this.globals.length - 1; + } + } + }, { + key: "importGlobal", + value: function importGlobal(type, mutability) { + this.globals.push({ + type: type, + mutability: mutability + }); + } + }, { + key: "isMutableGlobal", + value: function isMutableGlobal(index) { + return this.globals[index].mutability === "var"; + } + }, { + key: "isImmutableGlobal", + value: function isImmutableGlobal(index) { + return this.globals[index].mutability === "const"; + } + /** + * Memories + */ + + }, { + key: "hasMemory", + value: function hasMemory(index) { + return this.mems.length > index && index >= 0; + } + }, { + key: "addMemory", + value: function addMemory(min, max) { + this.mems.push({ + min: min, + max: max + }); + } + }, { + key: "getMemory", + value: function getMemory(index) { + return this.mems[index]; + } + }]); + + return ModuleContext; +}(); + +exports.ModuleContext = ModuleContext; + +/***/ }), + +/***/ 97527: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "getSectionForNode", ({ + enumerable: true, + get: function get() { + return _section.getSectionForNode; + } +})); +exports.default = void 0; + +var _section = __webpack_require__(36996); + +var illegalop = "illegal"; +var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; +var moduleVersion = [0x01, 0x00, 0x00, 0x00]; + +function invertMap(obj) { + var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { + return k; + }; + var result = {}; + var keys = Object.keys(obj); + + for (var i = 0, length = keys.length; i < length; i++) { + result[keyModifierFn(obj[keys[i]])] = keys[i]; + } + + return result; +} + +function createSymbolObject(name +/*: string */ +, object +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + return { + name: name, + object: object, + numberOfArgs: numberOfArgs + }; +} + +function createSymbol(name +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return { + name: name, + numberOfArgs: numberOfArgs + }; +} + +var types = { + func: 0x60, + result: 0x40 +}; +var exportTypes = { + 0x00: "Func", + 0x01: "Table", + 0x02: "Mem", + 0x03: "Global" +}; +var exportTypesByName = invertMap(exportTypes); +var valtypes = { + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64", + 0x7b: "v128" +}; +var valtypesByString = invertMap(valtypes); +var tableTypes = { + 0x70: "anyfunc" +}; +var blockTypes = Object.assign({}, valtypes, { + // https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype + 0x40: null, + // https://webassembly.github.io/spec/core/binary/types.html#binary-valtype + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64" +}); +var globalTypes = { + 0x00: "const", + 0x01: "var" +}; +var globalTypesByString = invertMap(globalTypes); +var importTypes = { + 0x00: "func", + 0x01: "table", + 0x02: "mem", + 0x03: "global" +}; +var sections = { + custom: 0, + type: 1, + import: 2, + func: 3, + table: 4, + memory: 5, + global: 6, + export: 7, + start: 8, + element: 9, + code: 10, + data: 11 +}; +var symbolsByByte = { + 0x00: createSymbol("unreachable"), + 0x01: createSymbol("nop"), + 0x02: createSymbol("block"), + 0x03: createSymbol("loop"), + 0x04: createSymbol("if"), + 0x05: createSymbol("else"), + 0x06: illegalop, + 0x07: illegalop, + 0x08: illegalop, + 0x09: illegalop, + 0x0a: illegalop, + 0x0b: createSymbol("end"), + 0x0c: createSymbol("br", 1), + 0x0d: createSymbol("br_if", 1), + 0x0e: createSymbol("br_table"), + 0x0f: createSymbol("return"), + 0x10: createSymbol("call", 1), + 0x11: createSymbol("call_indirect", 2), + 0x12: illegalop, + 0x13: illegalop, + 0x14: illegalop, + 0x15: illegalop, + 0x16: illegalop, + 0x17: illegalop, + 0x18: illegalop, + 0x19: illegalop, + 0x1a: createSymbol("drop"), + 0x1b: createSymbol("select"), + 0x1c: illegalop, + 0x1d: illegalop, + 0x1e: illegalop, + 0x1f: illegalop, + 0x20: createSymbol("get_local", 1), + 0x21: createSymbol("set_local", 1), + 0x22: createSymbol("tee_local", 1), + 0x23: createSymbol("get_global", 1), + 0x24: createSymbol("set_global", 1), + 0x25: illegalop, + 0x26: illegalop, + 0x27: illegalop, + 0x28: createSymbolObject("load", "u32", 1), + 0x29: createSymbolObject("load", "u64", 1), + 0x2a: createSymbolObject("load", "f32", 1), + 0x2b: createSymbolObject("load", "f64", 1), + 0x2c: createSymbolObject("load8_s", "u32", 1), + 0x2d: createSymbolObject("load8_u", "u32", 1), + 0x2e: createSymbolObject("load16_s", "u32", 1), + 0x2f: createSymbolObject("load16_u", "u32", 1), + 0x30: createSymbolObject("load8_s", "u64", 1), + 0x31: createSymbolObject("load8_u", "u64", 1), + 0x32: createSymbolObject("load16_s", "u64", 1), + 0x33: createSymbolObject("load16_u", "u64", 1), + 0x34: createSymbolObject("load32_s", "u64", 1), + 0x35: createSymbolObject("load32_u", "u64", 1), + 0x36: createSymbolObject("store", "u32", 1), + 0x37: createSymbolObject("store", "u64", 1), + 0x38: createSymbolObject("store", "f32", 1), + 0x39: createSymbolObject("store", "f64", 1), + 0x3a: createSymbolObject("store8", "u32", 1), + 0x3b: createSymbolObject("store16", "u32", 1), + 0x3c: createSymbolObject("store8", "u64", 1), + 0x3d: createSymbolObject("store16", "u64", 1), + 0x3e: createSymbolObject("store32", "u64", 1), + 0x3f: createSymbolObject("current_memory"), + 0x40: createSymbolObject("grow_memory"), + 0x41: createSymbolObject("const", "i32", 1), + 0x42: createSymbolObject("const", "i64", 1), + 0x43: createSymbolObject("const", "f32", 1), + 0x44: createSymbolObject("const", "f64", 1), + 0x45: createSymbolObject("eqz", "i32"), + 0x46: createSymbolObject("eq", "i32"), + 0x47: createSymbolObject("ne", "i32"), + 0x48: createSymbolObject("lt_s", "i32"), + 0x49: createSymbolObject("lt_u", "i32"), + 0x4a: createSymbolObject("gt_s", "i32"), + 0x4b: createSymbolObject("gt_u", "i32"), + 0x4c: createSymbolObject("le_s", "i32"), + 0x4d: createSymbolObject("le_u", "i32"), + 0x4e: createSymbolObject("ge_s", "i32"), + 0x4f: createSymbolObject("ge_u", "i32"), + 0x50: createSymbolObject("eqz", "i64"), + 0x51: createSymbolObject("eq", "i64"), + 0x52: createSymbolObject("ne", "i64"), + 0x53: createSymbolObject("lt_s", "i64"), + 0x54: createSymbolObject("lt_u", "i64"), + 0x55: createSymbolObject("gt_s", "i64"), + 0x56: createSymbolObject("gt_u", "i64"), + 0x57: createSymbolObject("le_s", "i64"), + 0x58: createSymbolObject("le_u", "i64"), + 0x59: createSymbolObject("ge_s", "i64"), + 0x5a: createSymbolObject("ge_u", "i64"), + 0x5b: createSymbolObject("eq", "f32"), + 0x5c: createSymbolObject("ne", "f32"), + 0x5d: createSymbolObject("lt", "f32"), + 0x5e: createSymbolObject("gt", "f32"), + 0x5f: createSymbolObject("le", "f32"), + 0x60: createSymbolObject("ge", "f32"), + 0x61: createSymbolObject("eq", "f64"), + 0x62: createSymbolObject("ne", "f64"), + 0x63: createSymbolObject("lt", "f64"), + 0x64: createSymbolObject("gt", "f64"), + 0x65: createSymbolObject("le", "f64"), + 0x66: createSymbolObject("ge", "f64"), + 0x67: createSymbolObject("clz", "i32"), + 0x68: createSymbolObject("ctz", "i32"), + 0x69: createSymbolObject("popcnt", "i32"), + 0x6a: createSymbolObject("add", "i32"), + 0x6b: createSymbolObject("sub", "i32"), + 0x6c: createSymbolObject("mul", "i32"), + 0x6d: createSymbolObject("div_s", "i32"), + 0x6e: createSymbolObject("div_u", "i32"), + 0x6f: createSymbolObject("rem_s", "i32"), + 0x70: createSymbolObject("rem_u", "i32"), + 0x71: createSymbolObject("and", "i32"), + 0x72: createSymbolObject("or", "i32"), + 0x73: createSymbolObject("xor", "i32"), + 0x74: createSymbolObject("shl", "i32"), + 0x75: createSymbolObject("shr_s", "i32"), + 0x76: createSymbolObject("shr_u", "i32"), + 0x77: createSymbolObject("rotl", "i32"), + 0x78: createSymbolObject("rotr", "i32"), + 0x79: createSymbolObject("clz", "i64"), + 0x7a: createSymbolObject("ctz", "i64"), + 0x7b: createSymbolObject("popcnt", "i64"), + 0x7c: createSymbolObject("add", "i64"), + 0x7d: createSymbolObject("sub", "i64"), + 0x7e: createSymbolObject("mul", "i64"), + 0x7f: createSymbolObject("div_s", "i64"), + 0x80: createSymbolObject("div_u", "i64"), + 0x81: createSymbolObject("rem_s", "i64"), + 0x82: createSymbolObject("rem_u", "i64"), + 0x83: createSymbolObject("and", "i64"), + 0x84: createSymbolObject("or", "i64"), + 0x85: createSymbolObject("xor", "i64"), + 0x86: createSymbolObject("shl", "i64"), + 0x87: createSymbolObject("shr_s", "i64"), + 0x88: createSymbolObject("shr_u", "i64"), + 0x89: createSymbolObject("rotl", "i64"), + 0x8a: createSymbolObject("rotr", "i64"), + 0x8b: createSymbolObject("abs", "f32"), + 0x8c: createSymbolObject("neg", "f32"), + 0x8d: createSymbolObject("ceil", "f32"), + 0x8e: createSymbolObject("floor", "f32"), + 0x8f: createSymbolObject("trunc", "f32"), + 0x90: createSymbolObject("nearest", "f32"), + 0x91: createSymbolObject("sqrt", "f32"), + 0x92: createSymbolObject("add", "f32"), + 0x93: createSymbolObject("sub", "f32"), + 0x94: createSymbolObject("mul", "f32"), + 0x95: createSymbolObject("div", "f32"), + 0x96: createSymbolObject("min", "f32"), + 0x97: createSymbolObject("max", "f32"), + 0x98: createSymbolObject("copysign", "f32"), + 0x99: createSymbolObject("abs", "f64"), + 0x9a: createSymbolObject("neg", "f64"), + 0x9b: createSymbolObject("ceil", "f64"), + 0x9c: createSymbolObject("floor", "f64"), + 0x9d: createSymbolObject("trunc", "f64"), + 0x9e: createSymbolObject("nearest", "f64"), + 0x9f: createSymbolObject("sqrt", "f64"), + 0xa0: createSymbolObject("add", "f64"), + 0xa1: createSymbolObject("sub", "f64"), + 0xa2: createSymbolObject("mul", "f64"), + 0xa3: createSymbolObject("div", "f64"), + 0xa4: createSymbolObject("min", "f64"), + 0xa5: createSymbolObject("max", "f64"), + 0xa6: createSymbolObject("copysign", "f64"), + 0xa7: createSymbolObject("wrap/i64", "i32"), + 0xa8: createSymbolObject("trunc_s/f32", "i32"), + 0xa9: createSymbolObject("trunc_u/f32", "i32"), + 0xaa: createSymbolObject("trunc_s/f64", "i32"), + 0xab: createSymbolObject("trunc_u/f64", "i32"), + 0xac: createSymbolObject("extend_s/i32", "i64"), + 0xad: createSymbolObject("extend_u/i32", "i64"), + 0xae: createSymbolObject("trunc_s/f32", "i64"), + 0xaf: createSymbolObject("trunc_u/f32", "i64"), + 0xb0: createSymbolObject("trunc_s/f64", "i64"), + 0xb1: createSymbolObject("trunc_u/f64", "i64"), + 0xb2: createSymbolObject("convert_s/i32", "f32"), + 0xb3: createSymbolObject("convert_u/i32", "f32"), + 0xb4: createSymbolObject("convert_s/i64", "f32"), + 0xb5: createSymbolObject("convert_u/i64", "f32"), + 0xb6: createSymbolObject("demote/f64", "f32"), + 0xb7: createSymbolObject("convert_s/i32", "f64"), + 0xb8: createSymbolObject("convert_u/i32", "f64"), + 0xb9: createSymbolObject("convert_s/i64", "f64"), + 0xba: createSymbolObject("convert_u/i64", "f64"), + 0xbb: createSymbolObject("promote/f32", "f64"), + 0xbc: createSymbolObject("reinterpret/f32", "i32"), + 0xbd: createSymbolObject("reinterpret/f64", "i64"), + 0xbe: createSymbolObject("reinterpret/i32", "f32"), + 0xbf: createSymbolObject("reinterpret/i64", "f64") +}; +var symbolsByName = invertMap(symbolsByByte, function (obj) { + if (typeof obj.object === "string") { + return "".concat(obj.object, ".").concat(obj.name); + } + + return obj.name; +}); +var _default = { + symbolsByByte: symbolsByByte, + sections: sections, + magicModuleHeader: magicModuleHeader, + moduleVersion: moduleVersion, + types: types, + valtypes: valtypes, + exportTypes: exportTypes, + blockTypes: blockTypes, + tableTypes: tableTypes, + globalTypes: globalTypes, + importTypes: importTypes, + valtypesByString: valtypesByString, + globalTypesByString: globalTypesByString, + exportTypesByName: exportTypesByName, + symbolsByName: symbolsByName +}; +exports.default = _default; + +/***/ }), + +/***/ 36996: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getSectionForNode = getSectionForNode; + +function getSectionForNode(n) { + switch (n.type) { + case "ModuleImport": + return "import"; + + case "CallInstruction": + case "CallIndirectInstruction": + case "Func": + case "Instr": + return "code"; + + case "ModuleExport": + return "export"; + + case "Start": + return "start"; + + case "TypeInstruction": + return "type"; + + case "IndexInFuncSection": + return "func"; + + case "Global": + return "global"; + // No section + + default: + return; + } +} + +/***/ }), + +/***/ 30368: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createEmptySection = createEmptySection; + +var _wasmGen = __webpack_require__(62394); + +var _helperBuffer = __webpack_require__(57827); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(97527)); + +var t = _interopRequireWildcard(__webpack_require__(98688)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function findLastSection(ast, forSection) { + var targetSectionId = _helperWasmBytecode.default.sections[forSection]; // $FlowIgnore: metadata can not be empty + + var moduleSections = ast.body[0].metadata.sections; + var lastSection; + var lastId = 0; + + for (var i = 0, len = moduleSections.length; i < len; i++) { + var section = moduleSections[i]; // Ignore custom section since they can actually occur everywhere + + if (section.section === "custom") { + continue; + } + + var sectionId = _helperWasmBytecode.default.sections[section.section]; + + if (targetSectionId > lastId && targetSectionId < sectionId) { + return lastSection; + } + + lastId = sectionId; + lastSection = section; + } + + return lastSection; +} + +function createEmptySection(ast, uint8Buffer, section) { + // previous section after which we are going to insert our section + var lastSection = findLastSection(ast, section); + var start, end; + /** + * It's the first section + */ + + if (lastSection == null || lastSection.section === "custom") { + start = 8 + /* wasm header size */ + ; + end = start; + } else { + start = lastSection.startOffset + lastSection.size.value + 1; + end = start; + } // section id + + + start += 1; + var sizeStartLoc = { + line: -1, + column: start + }; + var sizeEndLoc = { + line: -1, + column: start + 1 + }; // 1 byte for the empty vector + + var size = t.withLoc(t.numberLiteralFromRaw(1), sizeEndLoc, sizeStartLoc); + var vectorOfSizeStartLoc = { + line: -1, + column: sizeEndLoc.column + }; + var vectorOfSizeEndLoc = { + line: -1, + column: sizeEndLoc.column + 1 + }; + var vectorOfSize = t.withLoc(t.numberLiteralFromRaw(0), vectorOfSizeEndLoc, vectorOfSizeStartLoc); + var sectionMetadata = t.sectionMetadata(section, start, size, vectorOfSize); + var sectionBytes = (0, _wasmGen.encodeNode)(sectionMetadata); + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start - 1, end, sectionBytes); // Add section into the AST for later lookups + + if (_typeof(ast.body[0].metadata) === "object") { + // $FlowIgnore: metadata can not be empty + ast.body[0].metadata.sections.push(sectionMetadata); + t.sortSectionMetadata(ast.body[0]); + } + /** + * Update AST + */ + // Once we hit our section every that is after needs to be shifted by the delta + + + var deltaBytes = +sectionBytes.length; + var encounteredSection = false; + t.traverse(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + t.shiftSection(ast, path.node, deltaBytes); + } + } + }); + return { + uint8Buffer: uint8Buffer, + sectionMetadata: sectionMetadata + }; +} + +/***/ }), + +/***/ 37427: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "resizeSectionByteSize", ({ + enumerable: true, + get: function get() { + return _resize.resizeSectionByteSize; + } +})); +Object.defineProperty(exports, "resizeSectionVecSize", ({ + enumerable: true, + get: function get() { + return _resize.resizeSectionVecSize; + } +})); +Object.defineProperty(exports, "createEmptySection", ({ + enumerable: true, + get: function get() { + return _create.createEmptySection; + } +})); +Object.defineProperty(exports, "removeSections", ({ + enumerable: true, + get: function get() { + return _remove.removeSections; + } +})); + +var _resize = __webpack_require__(32230); + +var _create = __webpack_require__(30368); + +var _remove = __webpack_require__(70140); + +/***/ }), + +/***/ 70140: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.removeSections = removeSections; + +var _ast = __webpack_require__(98688); + +var _helperBuffer = __webpack_require__(57827); + +function removeSections(ast, uint8Buffer, section) { + var sectionMetadatas = (0, _ast.getSectionMetadatas)(ast, section); + + if (sectionMetadatas.length === 0) { + throw new Error("Section metadata not found"); + } + + return sectionMetadatas.reverse().reduce(function (uint8Buffer, sectionMetadata) { + var startsIncludingId = sectionMetadata.startOffset - 1; + var ends = section === "start" ? sectionMetadata.size.loc.end.column + 1 : sectionMetadata.startOffset + sectionMetadata.size.value + 1; + var delta = -(ends - startsIncludingId); + /** + * update AST + */ + // Once we hit our section every that is after needs to be shifted by the delta + + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return path.remove(); + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, delta); + } + } + }); // replacement is nothing + + var replacement = []; + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, startsIncludingId, ends, replacement); + }, uint8Buffer); +} + +/***/ }), + +/***/ 32230: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.resizeSectionByteSize = resizeSectionByteSize; +exports.resizeSectionVecSize = resizeSectionVecSize; + +var _wasmGen = __webpack_require__(62394); + +var _ast = __webpack_require__(98688); + +var _helperBuffer = __webpack_require__(57827); + +function resizeSectionByteSize(ast, uint8Buffer, section, deltaBytes) { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section); + + if (typeof sectionMetadata === "undefined") { + throw new Error("Section metadata not found"); + } + + if (typeof sectionMetadata.size.loc === "undefined") { + throw new Error("SectionMetadata " + section + " has no loc"); + } // keep old node location to be overriden + + + var start = sectionMetadata.size.loc.start.column; + var end = sectionMetadata.size.loc.end.column; + var newSectionSize = sectionMetadata.size.value + deltaBytes; + var newBytes = (0, _wasmGen.encodeU32)(newSectionSize); + /** + * update AST + */ + + sectionMetadata.size.value = newSectionSize; + var oldu32EncodedLen = end - start; + var newu32EncodedLen = newBytes.length; // the new u32 has a different encoded length + + if (newu32EncodedLen !== oldu32EncodedLen) { + var deltaInSizeEncoding = newu32EncodedLen - oldu32EncodedLen; + sectionMetadata.size.loc.end.column = start + newu32EncodedLen; + deltaBytes += deltaInSizeEncoding; // move the vec size pointer size the section size is now smaller + + sectionMetadata.vectorOfSize.loc.start.column += deltaInSizeEncoding; + sectionMetadata.vectorOfSize.loc.end.column += deltaInSizeEncoding; + } // Once we hit our section every that is after needs to be shifted by the delta + + + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, deltaBytes); + } + } + }); + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes); +} + +function resizeSectionVecSize(ast, uint8Buffer, section, deltaElements) { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section); + + if (typeof sectionMetadata === "undefined") { + throw new Error("Section metadata not found"); + } + + if (typeof sectionMetadata.vectorOfSize.loc === "undefined") { + throw new Error("SectionMetadata " + section + " has no loc"); + } // Section has no vector + + + if (sectionMetadata.vectorOfSize.value === -1) { + return uint8Buffer; + } // keep old node location to be overriden + + + var start = sectionMetadata.vectorOfSize.loc.start.column; + var end = sectionMetadata.vectorOfSize.loc.end.column; + var newValue = sectionMetadata.vectorOfSize.value + deltaElements; + var newBytes = (0, _wasmGen.encodeU32)(newValue); // Update AST + + sectionMetadata.vectorOfSize.value = newValue; + sectionMetadata.vectorOfSize.loc.end.column = start + newBytes.length; + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes); +} + +/***/ }), + +/***/ 23408: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeF32 = encodeF32; +exports.encodeF64 = encodeF64; +exports.decodeF32 = decodeF32; +exports.decodeF64 = decodeF64; +exports.DOUBLE_PRECISION_MANTISSA = exports.SINGLE_PRECISION_MANTISSA = exports.NUMBER_OF_BYTE_F64 = exports.NUMBER_OF_BYTE_F32 = void 0; + +var _ieee = __webpack_require__(30848); + +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 32/8 + */ +var NUMBER_OF_BYTE_F32 = 4; +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 64/8 + */ + +exports.NUMBER_OF_BYTE_F32 = NUMBER_OF_BYTE_F32; +var NUMBER_OF_BYTE_F64 = 8; +exports.NUMBER_OF_BYTE_F64 = NUMBER_OF_BYTE_F64; +var SINGLE_PRECISION_MANTISSA = 23; +exports.SINGLE_PRECISION_MANTISSA = SINGLE_PRECISION_MANTISSA; +var DOUBLE_PRECISION_MANTISSA = 52; +exports.DOUBLE_PRECISION_MANTISSA = DOUBLE_PRECISION_MANTISSA; + +function encodeF32(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); + return buffer; +} + +function encodeF64(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); + return buffer; +} + +function decodeF32(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); +} + +function decodeF64(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); +} + +/***/ }), + +/***/ 83156: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * bits: Bitwise buffer utilities. The utilities here treat a buffer + * as a little-endian bigint, so the lowest-order bit is bit #0 of + * `buffer[0]`, and the highest-order bit is bit #7 of + * `buffer[buffer.length - 1]`. + */ + +/* + * Modules used + */ + +/* + * Exported bindings + */ + +/** + * Extracts the given number of bits from the buffer at the indicated + * index, returning a simple number as the result. If bits are requested + * that aren't covered by the buffer, the `defaultBit` is used as their + * value. + * + * The `bitLength` must be no more than 32. The `defaultBit` if not + * specified is taken to be `0`. + */ + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extract = extract; +exports.inject = inject; +exports.getSign = getSign; +exports.highOrder = highOrder; + +function extract(buffer, bitIndex, bitLength, defaultBit) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + if (defaultBit === undefined) { + defaultBit = 0; + } else if (defaultBit !== 0 && defaultBit !== 1) { + throw new Error("Bad value for defaultBit."); + } + + var defaultByte = defaultBit * 0xff; + var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but + // if endBit !== 0, then endByte is inclusive. + + var lastBit = bitIndex + bitLength; + var startByte = Math.floor(bitIndex / 8); + var startBit = bitIndex % 8; + var endByte = Math.floor(lastBit / 8); + var endBit = lastBit % 8; + + if (endBit !== 0) { + // `(1 << endBit) - 1` is the mask of all bits up to but not including + // the endBit. + result = get(endByte) & (1 << endBit) - 1; + } + + while (endByte > startByte) { + endByte--; + result = result << 8 | get(endByte); + } + + result >>>= startBit; + return result; + + function get(index) { + var result = buffer[index]; + return result === undefined ? defaultByte : result; + } +} +/** + * Injects the given bits into the given buffer at the given index. Any + * bits in the value beyond the length to set are ignored. + */ + + +function inject(buffer, bitIndex, bitLength, value) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); + + if (bitIndex < 0 || lastByte >= buffer.length) { + throw new Error("Index out of range."); + } // Just keeping it simple, until / unless profiling shows that this + // is a problem. + + + var atByte = Math.floor(bitIndex / 8); + var atBit = bitIndex % 8; + + while (bitLength > 0) { + if (value & 1) { + buffer[atByte] |= 1 << atBit; + } else { + buffer[atByte] &= ~(1 << atBit); + } + + value >>= 1; + bitLength--; + atBit = (atBit + 1) % 8; + + if (atBit === 0) { + atByte++; + } + } +} +/** + * Gets the sign bit of the given buffer. + */ + + +function getSign(buffer) { + return buffer[buffer.length - 1] >>> 7; +} +/** + * Gets the zero-based bit number of the highest-order bit with the + * given value in the given buffer. + * + * If the buffer consists entirely of the other bit value, then this returns + * `-1`. + */ + + +function highOrder(bit, buffer) { + var length = buffer.length; + var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte + + while (length > 0 && buffer[length - 1] === fullyWrongByte) { + length--; + } + + if (length === 0) { + // Degenerate case. The buffer consists entirely of ~bit. + return -1; + } + + var byteToCheck = buffer[length - 1]; + var result = length * 8 - 1; + + for (var i = 7; i > 0; i--) { + if ((byteToCheck >> i & 1) === bit) { + break; + } + + result--; + } + + return result; +} + +/***/ }), + +/***/ 84341: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.alloc = alloc; +exports.free = free; +exports.resize = resize; +exports.readInt = readInt; +exports.readUInt = readUInt; +exports.writeInt64 = writeInt64; +exports.writeUInt64 = writeUInt64; +// Copyright 2012 The Obvious Corporation. + +/* + * bufs: Buffer utilities. + */ + +/* + * Module variables + */ + +/** Pool of buffers, where `bufPool[x].length === x`. */ +var bufPool = []; +/** Maximum length of kept temporary buffers. */ + +var TEMP_BUF_MAXIMUM_LENGTH = 20; +/** Minimum exactly-representable 64-bit int. */ + +var MIN_EXACT_INT64 = -0x8000000000000000; +/** Maximum exactly-representable 64-bit int. */ + +var MAX_EXACT_INT64 = 0x7ffffffffffffc00; +/** Maximum exactly-representable 64-bit uint. */ + +var MAX_EXACT_UINT64 = 0xfffffffffffff800; +/** + * The int value consisting just of a 1 in bit #32 (that is, one more + * than the maximum 32-bit unsigned value). + */ + +var BIT_32 = 0x100000000; +/** + * The int value consisting just of a 1 in bit #64 (that is, one more + * than the maximum 64-bit unsigned value). + */ + +var BIT_64 = 0x10000000000000000; +/* + * Helper functions + */ + +/** + * Masks off all but the lowest bit set of the given number. + */ + +function lowestBit(num) { + return num & -num; +} +/** + * Gets whether trying to add the second number to the first is lossy + * (inexact). The first number is meant to be an accumulated result. + */ + + +function isLossyToAdd(accum, num) { + if (num === 0) { + return false; + } + + var lowBit = lowestBit(num); + var added = accum + lowBit; + + if (added === accum) { + return true; + } + + if (added - lowBit !== accum) { + return true; + } + + return false; +} +/* + * Exported functions + */ + +/** + * Allocates a buffer of the given length, which is initialized + * with all zeroes. This returns a buffer from the pool if it is + * available, or a freshly-allocated buffer if not. + */ + + +function alloc(length) { + var result = bufPool[length]; + + if (result) { + bufPool[length] = undefined; + } else { + result = new Buffer(length); + } + + result.fill(0); + return result; +} +/** + * Releases a buffer back to the pool. + */ + + +function free(buffer) { + var length = buffer.length; + + if (length < TEMP_BUF_MAXIMUM_LENGTH) { + bufPool[length] = buffer; + } +} +/** + * Resizes a buffer, returning a new buffer. Returns the argument if + * the length wouldn't actually change. This function is only safe to + * use if the given buffer was allocated within this module (since + * otherwise the buffer might possibly be shared externally). + */ + + +function resize(buffer, length) { + if (length === buffer.length) { + return buffer; + } + + var newBuf = alloc(length); + buffer.copy(newBuf); + free(buffer); + return newBuf; +} +/** + * Reads an arbitrary signed int from a buffer. + */ + + +function readInt(buffer) { + var length = buffer.length; + var positive = buffer[length - 1] < 0x80; + var result = positive ? 0 : -1; + var lossy = false; // Note: We can't use bit manipulation here, since that stops + // working if the result won't fit in a 32-bit int. + + if (length < 7) { + // Common case which can't possibly be lossy (because the result has + // no more than 48 bits, and loss only happens with 54 or more). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i = length - 1; _i >= 0; _i--) { + var one = buffer[_i]; + result *= 0x100; + + if (isLossyToAdd(result, one)) { + lossy = true; + } + + result += one; + } + } + + return { + value: result, + lossy: lossy + }; +} +/** + * Reads an arbitrary unsigned int from a buffer. + */ + + +function readUInt(buffer) { + var length = buffer.length; + var result = 0; + var lossy = false; // Note: See above in re bit manipulation. + + if (length < 7) { + // Common case which can't possibly be lossy (see above). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i2 = length - 1; _i2 >= 0; _i2--) { + var one = buffer[_i2]; + result *= 0x100; + + if (isLossyToAdd(result, one)) { + lossy = true; + } + + result += one; + } + } + + return { + value: result, + lossy: lossy + }; +} +/** + * Writes a little-endian 64-bit signed int into a buffer. + */ + + +function writeInt64(value, buffer) { + if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) { + throw new Error("Value out of range."); + } + + if (value < 0) { + value += BIT_64; + } + + writeUInt64(value, buffer); +} +/** + * Writes a little-endian 64-bit unsigned int into a buffer. + */ + + +function writeUInt64(value, buffer) { + if (value < 0 || value > MAX_EXACT_UINT64) { + throw new Error("Value out of range."); + } + + var lowWord = value % BIT_32; + var highWord = Math.floor(value / BIT_32); + buffer.writeUInt32LE(lowWord, 0); + buffer.writeUInt32LE(highWord, 4); +} + +/***/ }), + +/***/ 20942: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeInt64 = decodeInt64; +exports.decodeUInt64 = decodeUInt64; +exports.decodeInt32 = decodeInt32; +exports.decodeUInt32 = decodeUInt32; +exports.encodeU32 = encodeU32; +exports.encodeI32 = encodeI32; +exports.encodeI64 = encodeI64; +exports.MAX_NUMBER_OF_BYTE_U64 = exports.MAX_NUMBER_OF_BYTE_U32 = void 0; + +var _leb = _interopRequireDefault(__webpack_require__(39210)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(32/7) + */ +var MAX_NUMBER_OF_BYTE_U32 = 5; +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(64/7) + */ + +exports.MAX_NUMBER_OF_BYTE_U32 = MAX_NUMBER_OF_BYTE_U32; +var MAX_NUMBER_OF_BYTE_U64 = 10; +exports.MAX_NUMBER_OF_BYTE_U64 = MAX_NUMBER_OF_BYTE_U64; + +function decodeInt64(encodedBuffer, index) { + return _leb.default.decodeInt64(encodedBuffer, index); +} + +function decodeUInt64(encodedBuffer, index) { + return _leb.default.decodeUInt64(encodedBuffer, index); +} + +function decodeInt32(encodedBuffer, index) { + return _leb.default.decodeInt32(encodedBuffer, index); +} + +function decodeUInt32(encodedBuffer, index) { + return _leb.default.decodeUInt32(encodedBuffer, index); +} + +function encodeU32(v) { + return _leb.default.encodeUInt32(v); +} + +function encodeI32(v) { + return _leb.default.encodeInt32(v); +} + +function encodeI64(v) { + return _leb.default.encodeInt64(v); +} + +/***/ }), + +/***/ 39210: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * leb: LEB128 utilities. + */ + +/* + * Modules used + */ + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +var bits = _interopRequireWildcard(__webpack_require__(83156)); + +var bufs = _interopRequireWildcard(__webpack_require__(84341)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + * Module variables + */ + +/** The minimum possible 32-bit signed int. */ +var MIN_INT32 = -0x80000000; +/** The maximum possible 32-bit signed int. */ + +var MAX_INT32 = 0x7fffffff; +/** The maximum possible 32-bit unsigned int. */ + +var MAX_UINT32 = 0xffffffff; +/** The minimum possible 64-bit signed int. */ +// const MIN_INT64 = -0x8000000000000000; + +/** + * The maximum possible 64-bit signed int that is representable as a + * JavaScript number. + */ +// const MAX_INT64 = 0x7ffffffffffffc00; + +/** + * The maximum possible 64-bit unsigned int that is representable as a + * JavaScript number. + */ +// const MAX_UINT64 = 0xfffffffffffff800; + +/* + * Helper functions + */ + +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as a signed value. The buffer is + * taken to represent a signed number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order non-sign-matching bit, plus two. For example: + * + * 11111011 01110101 + * high low + * + * The sign bit here is 1 (that is, it's a negative number). The highest + * bit number that doesn't match the sign is bit #10 (where the lowest-order + * bit is bit #0). So, we have to encode at least 12 bits total. + * + * As a special degenerate case, the numbers 0 and -1 each require just one bit. + */ + +function signedBitCount(buffer) { + return bits.highOrder(bits.getSign(buffer) ^ 1, buffer) + 2; +} +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as an unsigned value. The buffer is + * taken to represent an unsigned number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order 1 bit, plus one. For example: + * + * 00011000 01010011 + * high low + * + * The highest-order 1 bit here is bit #12 (where the lowest-order bit + * is bit #0). So, we have to encode at least 13 bits total. + * + * As a special degenerate case, the number 0 requires 1 bit. + */ + + +function unsignedBitCount(buffer) { + var result = bits.highOrder(1, buffer) + 1; + return result ? result : 1; +} +/** + * Common encoder for both signed and unsigned ints. This takes a + * bigint-ish buffer, returning an LEB128-encoded buffer. + */ + + +function encodeBufferCommon(buffer, signed) { + var signBit; + var bitCount; + + if (signed) { + signBit = bits.getSign(buffer); + bitCount = signedBitCount(buffer); + } else { + signBit = 0; + bitCount = unsignedBitCount(buffer); + } + + var byteCount = Math.ceil(bitCount / 7); + var result = bufs.alloc(byteCount); + + for (var i = 0; i < byteCount; i++) { + var payload = bits.extract(buffer, i * 7, 7, signBit); + result[i] = payload | 0x80; + } // Mask off the top bit of the last byte, to indicate the end of the + // encoding. + + + result[byteCount - 1] &= 0x7f; + return result; +} +/** + * Gets the byte-length of the value encoded in the given buffer at + * the given index. + */ + + +function encodedLength(encodedBuffer, index) { + var result = 0; + + while (encodedBuffer[index + result] >= 0x80) { + result++; + } + + result++; // to account for the last byte + + if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives + // throw new Error("integer representation too long"); + } + + return result; +} +/** + * Common decoder for both signed and unsigned ints. This takes an + * LEB128-encoded buffer, returning a bigint-ish buffer. + */ + + +function decodeBufferCommon(encodedBuffer, index, signed) { + index = index === undefined ? 0 : index; + var length = encodedLength(encodedBuffer, index); + var bitLength = length * 7; + var byteLength = Math.ceil(bitLength / 8); + var result = bufs.alloc(byteLength); + var outIndex = 0; + + while (length > 0) { + bits.inject(result, outIndex, 7, encodedBuffer[index]); + outIndex += 7; + index++; + length--; + } + + var signBit; + var signByte; + + if (signed) { + // Sign-extend the last byte. + var lastByte = result[byteLength - 1]; + var endBit = outIndex % 8; + + if (endBit !== 0) { + var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. + + lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff; + } + + signBit = lastByte >> 7; + signByte = signBit * 0xff; + } else { + signBit = 0; + signByte = 0; + } // Slice off any superfluous bytes, that is, ones that add no meaningful + // bits (because the value would be the same if they were removed). + + + while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) { + byteLength--; + } + + result = bufs.resize(result, byteLength); + return { + value: result, + nextIndex: index + }; +} +/* + * Exported bindings + */ + + +function encodeIntBuffer(buffer) { + return encodeBufferCommon(buffer, true); +} + +function decodeIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, true); +} + +function encodeInt32(num) { + var buf = bufs.alloc(4); + buf.writeInt32LE(num, 0); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeInt32(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + var parsed = bufs.readInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value < MIN_INT32 || value > MAX_INT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex + }; +} + +function encodeInt64(num) { + var buf = bufs.alloc(8); + bufs.writeInt64(num, buf); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeInt64(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, false); + + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false + }; +} + +function encodeUIntBuffer(buffer) { + return encodeBufferCommon(buffer, false); +} + +function decodeUIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, false); +} + +function encodeUInt32(num) { + var buf = bufs.alloc(4); + buf.writeUInt32LE(num, 0); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt32(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + var parsed = bufs.readUInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value > MAX_UINT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex + }; +} + +function encodeUInt64(num) { + var buf = bufs.alloc(8); + bufs.writeUInt64(num, buf); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt64(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, true); + + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false + }; +} + +var _default = { + decodeInt32: decodeInt32, + decodeInt64: decodeInt64, + decodeIntBuffer: decodeIntBuffer, + decodeUInt32: decodeUInt32, + decodeUInt64: decodeUInt64, + decodeUIntBuffer: decodeUIntBuffer, + encodeInt32: encodeInt32, + encodeInt64: encodeInt64, + encodeIntBuffer: encodeIntBuffer, + encodeUInt32: encodeUInt32, + encodeUInt64: encodeUInt64, + encodeUIntBuffer: encodeUIntBuffer +}; +exports.default = _default; + +/***/ }), + +/***/ 63202: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + +function con(b) { + if ((b & 0xc0) === 0x80) { + return b & 0x3f; + } else { + throw new Error("invalid UTF-8 encoding"); + } +} + +function code(min, n) { + if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { + throw new Error("invalid UTF-8 encoding"); + } else { + return n; + } +} + +function decode(bytes) { + return _decode(bytes).map(function (x) { + return String.fromCharCode(x); + }).join(""); +} + +function _decode(bytes) { + if (bytes.length === 0) { + return []; + } + /** + * 1 byte + */ + + + { + var _bytes = _toArray(bytes), + b1 = _bytes[0], + bs = _bytes.slice(1); + + if (b1 < 0x80) { + return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); + } + + if (b1 < 0xc0) { + throw new Error("invalid UTF-8 encoding"); + } + } + /** + * 2 bytes + */ + + { + var _bytes2 = _toArray(bytes), + _b = _bytes2[0], + b2 = _bytes2[1], + _bs = _bytes2.slice(2); + + if (_b < 0xe0) { + return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); + } + } + /** + * 3 bytes + */ + + { + var _bytes3 = _toArray(bytes), + _b2 = _bytes3[0], + _b3 = _bytes3[1], + b3 = _bytes3[2], + _bs2 = _bytes3.slice(3); + + if (_b2 < 0xf0) { + return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); + } + } + /** + * 4 bytes + */ + + { + var _bytes4 = _toArray(bytes), + _b4 = _bytes4[0], + _b5 = _bytes4[1], + _b6 = _bytes4[2], + b4 = _bytes4[3], + _bs3 = _bytes4.slice(4); + + if (_b4 < 0xf8) { + return [code(0x10000, (((_b4 & 0x07) << 18) + con(_b5) << 12) + (con(_b6) << 6) + con(b4))].concat(_toConsumableArray(_decode(_bs3))); + } + } + throw new Error("invalid UTF-8 encoding"); +} + +/***/ }), + +/***/ 71812: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encode = encode; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + +function con(n) { + return 0x80 | n & 0x3f; +} + +function encode(str) { + var arr = str.split("").map(function (x) { + return x.charCodeAt(0); + }); + return _encode(arr); +} + +function _encode(arr) { + if (arr.length === 0) { + return []; + } + + var _arr = _toArray(arr), + n = _arr[0], + ns = _arr.slice(1); + + if (n < 0) { + throw new Error("utf8"); + } + + if (n < 0x80) { + return [n].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x800) { + return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x10000) { + return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x110000) { + return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + throw new Error("utf8"); +} + +/***/ }), + +/***/ 17715: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "decode", ({ + enumerable: true, + get: function get() { + return _decoder.decode; + } +})); +Object.defineProperty(exports, "encode", ({ + enumerable: true, + get: function get() { + return _encoder.encode; + } +})); + +var _decoder = __webpack_require__(63202); + +var _encoder = __webpack_require__(71812); + +/***/ }), + +/***/ 56550: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.applyOperations = applyOperations; + +var _wasmGen = __webpack_require__(62394); + +var _encoder = __webpack_require__(94261); + +var _ast = __webpack_require__(98688); + +var _helperWasmSection = __webpack_require__(37427); + +var _helperBuffer = __webpack_require__(57827); + +var _helperWasmBytecode = __webpack_require__(97527); + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function shiftLocNodeByDelta(node, delta) { + (0, _ast.assertHasLoc)(node); // $FlowIgnore: assertHasLoc ensures that + + node.loc.start.column += delta; // $FlowIgnore: assertHasLoc ensures that + + node.loc.end.column += delta; +} + +function applyUpdate(ast, uint8Buffer, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + oldNode = _ref2[0], + newNode = _ref2[1]; + + var deltaElements = 0; + (0, _ast.assertHasLoc)(oldNode); + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(newNode); + var replacementByteArray = (0, _wasmGen.encodeNode)(newNode); + /** + * Replace new node as bytes + */ + + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.start.column, // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.end.column, replacementByteArray); + /** + * Update function body size if needed + */ + + if (sectionName === "code") { + // Find the parent func + (0, _ast.traverse)(ast, { + Func: function Func(_ref3) { + var node = _ref3.node; + var funcHasThisIntr = node.body.find(function (n) { + return n === newNode; + }) !== undefined; // Update func's body size if needed + + if (funcHasThisIntr === true) { + // These are the old functions locations informations + (0, _ast.assertHasLoc)(node); + var oldNodeSize = (0, _wasmGen.encodeNode)(oldNode).length; + var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize; + + if (bodySizeDeltaBytes !== 0) { + var newValue = node.metadata.bodySize + bodySizeDeltaBytes; + var newByteArray = (0, _encoder.encodeU32)(newValue); // function body size byte + // FIXME(sven): only handles one byte u32 + + var start = node.loc.start.column; + var end = start + 1; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray); + } + } + } + }); + } + /** + * Update section size + */ + + + var deltaBytes = replacementByteArray.length - ( // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.end.column - oldNode.loc.start.column); // Init location informations + + newNode.loc = { + start: { + line: -1, + column: -1 + }, + end: { + line: -1, + column: -1 + } + }; // Update new node end position + // $FlowIgnore: assertHasLoc ensures that + + newNode.loc.start.column = oldNode.loc.start.column; // $FlowIgnore: assertHasLoc ensures that + + newNode.loc.end.column = // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.start.column + replacementByteArray.length; + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyDelete(ast, uint8Buffer, node) { + var deltaElements = -1; // since we removed an element + + (0, _ast.assertHasLoc)(node); + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node); + + if (sectionName === "start") { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, "start"); + /** + * The start section only contains one element, + * we need to remove the whole section + */ + + uint8Buffer = (0, _helperWasmSection.removeSections)(ast, uint8Buffer, "start"); + + var _deltaBytes = -(sectionMetadata.size.value + 1); + /* section id */ + + + return { + uint8Buffer: uint8Buffer, + deltaBytes: _deltaBytes, + deltaElements: deltaElements + }; + } // replacement is nothing + + + var replacement = []; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that + node.loc.start.column, // $FlowIgnore: assertHasLoc ensures that + node.loc.end.column, replacement); + /** + * Update section + */ + // $FlowIgnore: assertHasLoc ensures that + + var deltaBytes = -(node.loc.end.column - node.loc.start.column); + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyAdd(ast, uint8Buffer, node) { + var deltaElements = +1; // since we added an element + + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node); + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, sectionName); // Section doesn't exists, we create an empty one + + if (typeof sectionMetadata === "undefined") { + var res = (0, _helperWasmSection.createEmptySection)(ast, uint8Buffer, sectionName); + uint8Buffer = res.uint8Buffer; + sectionMetadata = res.sectionMetadata; + } + /** + * check that the expressions were ended + */ + + + if ((0, _ast.isFunc)(node)) { + // $FlowIgnore + var body = node.body; + + if (body.length === 0 || body[body.length - 1].id !== "end") { + throw new Error("expressions must be ended"); + } + } + + if ((0, _ast.isGlobal)(node)) { + // $FlowIgnore + var body = node.init; + + if (body.length === 0 || body[body.length - 1].id !== "end") { + throw new Error("expressions must be ended"); + } + } + /** + * Add nodes + */ + + + var newByteArray = (0, _wasmGen.encodeNode)(node); // The size of the section doesn't include the storage of the size itself + // we need to manually add it here + + var start = (0, _ast.getEndOfSection)(sectionMetadata); + var end = start; + /** + * Update section + */ + + var deltaBytes = newByteArray.length; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray); + node.loc = { + start: { + line: -1, + column: start + }, + end: { + line: -1, + column: start + deltaBytes + } + }; // for func add the additional metadata in the AST + + if (node.type === "Func") { + // the size is the first byte + // FIXME(sven): handle LEB128 correctly here + var bodySize = newByteArray[0]; + node.metadata = { + bodySize: bodySize + }; + } + + if (node.type !== "IndexInFuncSection") { + (0, _ast.orderedInsertNode)(ast.body[0], node); + } + + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyOperations(ast, uint8Buffer, ops) { + ops.forEach(function (op) { + var state; + var sectionName; + + switch (op.kind) { + case "update": + state = applyUpdate(ast, uint8Buffer, [op.oldNode, op.node]); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + case "delete": + state = applyDelete(ast, uint8Buffer, op.node); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + case "add": + state = applyAdd(ast, uint8Buffer, op.node); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + default: + throw new Error("Unknown operation"); + } + /** + * Resize section vec size. + * If the length of the LEB-encoded size changes, this can change + * the byte length of the section and the offset for nodes in the + * section. So we do this first before resizing section byte size + * or shifting following operations' nodes. + */ + + + if (state.deltaElements !== 0 && sectionName !== "start") { + var oldBufferLength = state.uint8Buffer.length; + state.uint8Buffer = (0, _helperWasmSection.resizeSectionVecSize)(ast, state.uint8Buffer, sectionName, state.deltaElements); // Infer bytes added/removed by comparing buffer lengths + + state.deltaBytes += state.uint8Buffer.length - oldBufferLength; + } + /** + * Resize section byte size. + * If the length of the LEB-encoded size changes, this can change + * the offset for nodes in the section. So we do this before + * shifting following operations' nodes. + */ + + + if (state.deltaBytes !== 0 && sectionName !== "start") { + var _oldBufferLength = state.uint8Buffer.length; + state.uint8Buffer = (0, _helperWasmSection.resizeSectionByteSize)(ast, state.uint8Buffer, sectionName, state.deltaBytes); // Infer bytes added/removed by comparing buffer lengths + + state.deltaBytes += state.uint8Buffer.length - _oldBufferLength; + } + /** + * Shift following operation's nodes + */ + + + if (state.deltaBytes !== 0) { + ops.forEach(function (op) { + // We don't need to handle add ops, they are positioning independent + switch (op.kind) { + case "update": + shiftLocNodeByDelta(op.oldNode, state.deltaBytes); + break; + + case "delete": + shiftLocNodeByDelta(op.node, state.deltaBytes); + break; + } + }); + } + + uint8Buffer = state.uint8Buffer; + }); + return uint8Buffer; +} + +/***/ }), + +/***/ 65584: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.edit = edit; +exports.editWithAST = editWithAST; +exports.add = add; +exports.addWithAST = addWithAST; + +var _wasmParser = __webpack_require__(8062); + +var _ast = __webpack_require__(98688); + +var _clone = __webpack_require__(95373); + +var _wasmOpt = __webpack_require__(46421); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(97527)); + +var _apply = __webpack_require__(56550); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function hashNode(node) { + return JSON.stringify(node); +} + +function preprocess(ab) { + var optBin = (0, _wasmOpt.shrinkPaddedLEB128)(new Uint8Array(ab)); + return optBin.buffer; +} + +function sortBySectionOrder(nodes) { + var originalOrder = new Map(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _node = _step.value; + originalOrder.set(_node, originalOrder.size); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + nodes.sort(function (a, b) { + var sectionA = (0, _helperWasmBytecode.getSectionForNode)(a); + var sectionB = (0, _helperWasmBytecode.getSectionForNode)(b); + var aId = _helperWasmBytecode.default.sections[sectionA]; + var bId = _helperWasmBytecode.default.sections[sectionB]; + + if (typeof aId !== "number" || typeof bId !== "number") { + throw new Error("Section id not found"); + } + + if (aId === bId) { + // $FlowIgnore originalOrder is filled for all nodes + return originalOrder.get(a) - originalOrder.get(b); + } + + return aId - bId; + }); +} + +function edit(ab, visitors) { + ab = preprocess(ab); + var ast = (0, _wasmParser.decode)(ab); + return editWithAST(ast, ab, visitors); +} + +function editWithAST(ast, ab, visitors) { + var operations = []; + var uint8Buffer = new Uint8Array(ab); + var nodeBefore; + + function before(type, path) { + nodeBefore = (0, _clone.cloneNode)(path.node); + } + + function after(type, path) { + if (path.node._deleted === true) { + operations.push({ + kind: "delete", + node: path.node + }); // $FlowIgnore + } else if (hashNode(nodeBefore) !== hashNode(path.node)) { + operations.push({ + kind: "update", + oldNode: nodeBefore, + node: path.node + }); + } + } + + (0, _ast.traverse)(ast, visitors, before, after); + uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations); + return uint8Buffer.buffer; +} + +function add(ab, newNodes) { + ab = preprocess(ab); + var ast = (0, _wasmParser.decode)(ab); + return addWithAST(ast, ab, newNodes); +} + +function addWithAST(ast, ab, newNodes) { + // Sort nodes by insertion order + sortBySectionOrder(newNodes); + var uint8Buffer = new Uint8Array(ab); // Map node into operations + + var operations = newNodes.map(function (n) { + return { + kind: "add", + node: n + }; + }); + uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations); + return uint8Buffer.buffer; +} + +/***/ }), + +/***/ 94261: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeVersion = encodeVersion; +exports.encodeHeader = encodeHeader; +exports.encodeU32 = encodeU32; +exports.encodeI32 = encodeI32; +exports.encodeI64 = encodeI64; +exports.encodeVec = encodeVec; +exports.encodeValtype = encodeValtype; +exports.encodeMutability = encodeMutability; +exports.encodeUTF8Vec = encodeUTF8Vec; +exports.encodeLimits = encodeLimits; +exports.encodeModuleImport = encodeModuleImport; +exports.encodeSectionMetadata = encodeSectionMetadata; +exports.encodeCallInstruction = encodeCallInstruction; +exports.encodeCallIndirectInstruction = encodeCallIndirectInstruction; +exports.encodeModuleExport = encodeModuleExport; +exports.encodeTypeInstruction = encodeTypeInstruction; +exports.encodeInstr = encodeInstr; +exports.encodeStringLiteral = encodeStringLiteral; +exports.encodeGlobal = encodeGlobal; +exports.encodeFuncBody = encodeFuncBody; +exports.encodeIndexInFuncSection = encodeIndexInFuncSection; +exports.encodeElem = encodeElem; + +var leb = _interopRequireWildcard(__webpack_require__(20942)); + +var ieee754 = _interopRequireWildcard(__webpack_require__(23408)); + +var utf8 = _interopRequireWildcard(__webpack_require__(17715)); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(97527)); + +var _index = __webpack_require__(62394); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function assertNotIdentifierNode(n) { + if (n.type === "Identifier") { + throw new Error("Unsupported node Identifier"); + } +} + +function encodeVersion(v) { + var bytes = _helperWasmBytecode.default.moduleVersion; + bytes[0] = v; + return bytes; +} + +function encodeHeader() { + return _helperWasmBytecode.default.magicModuleHeader; +} + +function encodeU32(v) { + var uint8view = new Uint8Array(leb.encodeU32(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeI32(v) { + var uint8view = new Uint8Array(leb.encodeI32(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeI64(v) { + var uint8view = new Uint8Array(leb.encodeI64(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeVec(elements) { + var size = encodeU32(elements.length); + return _toConsumableArray(size).concat(_toConsumableArray(elements)); +} + +function encodeValtype(v) { + var byte = _helperWasmBytecode.default.valtypesByString[v]; + + if (typeof byte === "undefined") { + throw new Error("Unknown valtype: " + v); + } + + return parseInt(byte, 10); +} + +function encodeMutability(v) { + var byte = _helperWasmBytecode.default.globalTypesByString[v]; + + if (typeof byte === "undefined") { + throw new Error("Unknown mutability: " + v); + } + + return parseInt(byte, 10); +} + +function encodeUTF8Vec(str) { + return encodeVec(utf8.encode(str)); +} + +function encodeLimits(n) { + var out = []; + + if (typeof n.max === "number") { + out.push(0x01); + out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof + + out.push.apply(out, _toConsumableArray(encodeU32(n.max))); + } else { + out.push(0x00); + out.push.apply(out, _toConsumableArray(encodeU32(n.min))); + } + + return out; +} + +function encodeModuleImport(n) { + var out = []; + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module))); + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name))); + + switch (n.descr.type) { + case "GlobalType": + { + out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists + + out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists + + out.push(encodeMutability(n.descr.mutability)); + break; + } + + case "Memory": + { + out.push(0x02); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits))); + break; + } + + case "Table": + { + out.push(0x01); + out.push(0x70); // element type + // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits))); + break; + } + + case "FuncImportDescr": + { + out.push(0x00); // $FlowIgnore + + assertNotIdentifierNode(n.descr.id); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value))); + break; + } + + default: + throw new Error("Unsupport operation: encode module import of type: " + n.descr.type); + } + + return out; +} + +function encodeSectionMetadata(n) { + var out = []; + var sectionId = _helperWasmBytecode.default.sections[n.section]; + + if (typeof sectionId === "undefined") { + throw new Error("Unknown section: " + n.section); + } + + if (n.section === "start") { + /** + * This is not implemented yet because it's a special case which + * doesn't have a vector in its section. + */ + throw new Error("Unsupported section encoding of type start"); + } + + out.push(sectionId); + out.push.apply(out, _toConsumableArray(encodeU32(n.size.value))); + out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value))); + return out; +} + +function encodeCallInstruction(n) { + var out = []; + assertNotIdentifierNode(n.index); + out.push(0x10); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); + return out; +} + +function encodeCallIndirectInstruction(n) { + var out = []; // $FlowIgnore + + assertNotIdentifierNode(n.index); + out.push(0x11); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte + + out.push(0x00); + return out; +} + +function encodeModuleExport(n) { + var out = []; + assertNotIdentifierNode(n.descr.id); + var exportTypeByteString = _helperWasmBytecode.default.exportTypesByName[n.descr.exportType]; + + if (typeof exportTypeByteString === "undefined") { + throw new Error("Unknown export of type: " + n.descr.exportType); + } + + var exportTypeByte = parseInt(exportTypeByteString, 10); + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name))); + out.push(exportTypeByte); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value))); + return out; +} + +function encodeTypeInstruction(n) { + var out = [0x60]; + var params = n.functype.params.map(function (x) { + return x.valtype; + }).map(encodeValtype); + var results = n.functype.results.map(encodeValtype); + out.push.apply(out, _toConsumableArray(encodeVec(params))); + out.push.apply(out, _toConsumableArray(encodeVec(results))); + return out; +} + +function encodeInstr(n) { + var out = []; + var instructionName = n.id; + + if (typeof n.object === "string") { + instructionName = "".concat(n.object, ".").concat(String(n.id)); + } + + var byteString = _helperWasmBytecode.default.symbolsByName[instructionName]; + + if (typeof byteString === "undefined") { + throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName)); + } + + var byte = parseInt(byteString, 10); + out.push(byte); + + if (n.args) { + n.args.forEach(function (arg) { + var encoder = encodeU32; // find correct encoder + + if (n.object === "i32") { + encoder = encodeI32; + } + + if (n.object === "i64") { + encoder = encodeI64; + } + + if (n.object === "f32") { + encoder = ieee754.encodeF32; + } + + if (n.object === "f64") { + encoder = ieee754.encodeF64; + } + + if (arg.type === "NumberLiteral" || arg.type === "FloatLiteral" || arg.type === "LongNumberLiteral") { + // $FlowIgnore + out.push.apply(out, _toConsumableArray(encoder(arg.value))); + } else { + throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type)); + } + }); + } + + return out; +} + +function encodeExpr(instrs) { + var out = []; + instrs.forEach(function (instr) { + // $FlowIgnore + var n = (0, _index.encodeNode)(instr); + out.push.apply(out, _toConsumableArray(n)); + }); + return out; +} + +function encodeStringLiteral(n) { + return encodeUTF8Vec(n.value); +} + +function encodeGlobal(n) { + var out = []; + var _n$globalType = n.globalType, + valtype = _n$globalType.valtype, + mutability = _n$globalType.mutability; + out.push(encodeValtype(valtype)); + out.push(encodeMutability(mutability)); + out.push.apply(out, _toConsumableArray(encodeExpr(n.init))); + return out; +} + +function encodeFuncBody(n) { + var out = []; + out.push(-1); // temporary function body size + // FIXME(sven): get the func locals? + + var localBytes = encodeVec([]); + out.push.apply(out, _toConsumableArray(localBytes)); + var funcBodyBytes = encodeExpr(n.body); + out[0] = funcBodyBytes.length + localBytes.length; + out.push.apply(out, _toConsumableArray(funcBodyBytes)); + return out; +} + +function encodeIndexInFuncSection(n) { + assertNotIdentifierNode(n.index); // $FlowIgnore + + return encodeU32(n.index.value); +} + +function encodeElem(n) { + var out = []; + assertNotIdentifierNode(n.table); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.table.value))); + out.push.apply(out, _toConsumableArray(encodeExpr(n.offset))); // $FlowIgnore + + var funcs = n.funcs.reduce(function (acc, x) { + return _toConsumableArray(acc).concat(_toConsumableArray(encodeU32(x.value))); + }, []); + out.push.apply(out, _toConsumableArray(encodeVec(funcs))); + return out; +} + +/***/ }), + +/***/ 62394: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeNode = encodeNode; +exports.encodeU32 = void 0; + +var encoder = _interopRequireWildcard(__webpack_require__(94261)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function encodeNode(n) { + switch (n.type) { + case "ModuleImport": + // $FlowIgnore: ModuleImport ensure that the node is well formated + return encoder.encodeModuleImport(n); + + case "SectionMetadata": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeSectionMetadata(n); + + case "CallInstruction": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeCallInstruction(n); + + case "CallIndirectInstruction": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeCallIndirectInstruction(n); + + case "TypeInstruction": + return encoder.encodeTypeInstruction(n); + + case "Instr": + // $FlowIgnore + return encoder.encodeInstr(n); + + case "ModuleExport": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeModuleExport(n); + + case "Global": + // $FlowIgnore + return encoder.encodeGlobal(n); + + case "Func": + return encoder.encodeFuncBody(n); + + case "IndexInFuncSection": + return encoder.encodeIndexInFuncSection(n); + + case "StringLiteral": + return encoder.encodeStringLiteral(n); + + case "Elem": + return encoder.encodeElem(n); + + default: + throw new Error("Unsupported encoding for node of type: " + JSON.stringify(n.type)); + } +} + +var encodeU32 = encoder.encodeU32; +exports.encodeU32 = encodeU32; + +/***/ }), + +/***/ 46421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.shrinkPaddedLEB128 = shrinkPaddedLEB128; + +var _wasmParser = __webpack_require__(8062); + +var _leb = __webpack_require__(15829); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var OptimizerError = +/*#__PURE__*/ +function (_Error) { + _inherits(OptimizerError, _Error); + + function OptimizerError(name, initalError) { + var _this; + + _classCallCheck(this, OptimizerError); + + _this = _possibleConstructorReturn(this, (OptimizerError.__proto__ || Object.getPrototypeOf(OptimizerError)).call(this, "Error while optimizing: " + name + ": " + initalError.message)); + _this.stack = initalError.stack; + return _this; + } + + return OptimizerError; +}(Error); + +var decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true +}; + +function shrinkPaddedLEB128(uint8Buffer) { + try { + var ast = (0, _wasmParser.decode)(uint8Buffer.buffer, decoderOpts); + return (0, _leb.shrinkPaddedLEB128)(ast, uint8Buffer); + } catch (e) { + throw new OptimizerError("shrinkPaddedLEB128", e); + } +} + +/***/ }), + +/***/ 15829: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.shrinkPaddedLEB128 = shrinkPaddedLEB128; + +var _ast = __webpack_require__(98688); + +var _encoder = __webpack_require__(94261); + +var _helperBuffer = __webpack_require__(57827); + +function shiftFollowingSections(ast, _ref, deltaInSizeEncoding) { + var section = _ref.section; + // Once we hit our section every that is after needs to be shifted by the delta + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, deltaInSizeEncoding); + } + } + }); +} + +function shrinkPaddedLEB128(ast, uint8Buffer) { + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(_ref2) { + var node = _ref2.node; + + /** + * Section size + */ + { + var newu32Encoded = (0, _encoder.encodeU32)(node.size.value); + var newu32EncodedLen = newu32Encoded.length; + var start = node.size.loc.start.column; + var end = node.size.loc.end.column; + var oldu32EncodedLen = end - start; + + if (newu32EncodedLen !== oldu32EncodedLen) { + var deltaInSizeEncoding = oldu32EncodedLen - newu32EncodedLen; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newu32Encoded); + shiftFollowingSections(ast, node, -deltaInSizeEncoding); + } + } + } + }); + return uint8Buffer; +} + +/***/ }), + +/***/ 72856: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +var _helperApiError = __webpack_require__(36194); + +var ieee754 = _interopRequireWildcard(__webpack_require__(23408)); + +var utf8 = _interopRequireWildcard(__webpack_require__(17715)); + +var t = _interopRequireWildcard(__webpack_require__(98688)); + +var _leb = __webpack_require__(20942); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(97527)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function toHex(n) { + return "0x" + Number(n).toString(16); +} + +function byteArrayEq(l, r) { + if (l.length !== r.length) { + return false; + } + + for (var i = 0; i < l.length; i++) { + if (l[i] !== r[i]) { + return false; + } + } + + return true; +} + +function decode(ab, opts) { + var buf = new Uint8Array(ab); + var getUniqueName = t.getUniqueNameGenerator(); + var offset = 0; + + function getPosition() { + return { + line: -1, + column: offset + }; + } + + function dump(b, msg) { + if (opts.dump === false) return; + var pad = "\t\t\t\t\t\t\t\t\t\t"; + var str = ""; + + if (b.length < 5) { + str = b.map(toHex).join(" "); + } else { + str = "..."; + } + + console.log(toHex(offset) + ":\t", str, pad, ";", msg); + } + + function dumpSep(msg) { + if (opts.dump === false) return; + console.log(";", msg); + } + /** + * TODO(sven): we can atually use a same structure + * we are adding incrementally new features + */ + + + var state = { + elementsInFuncSection: [], + elementsInExportSection: [], + elementsInCodeSection: [], + + /** + * Decode memory from: + * - Memory section + */ + memoriesInModule: [], + + /** + * Decoded types from: + * - Type section + */ + typesInModule: [], + + /** + * Decoded functions from: + * - Function section + * - Import section + */ + functionsInModule: [], + + /** + * Decoded tables from: + * - Table section + */ + tablesInModule: [], + + /** + * Decoded globals from: + * - Global section + */ + globalsInModule: [] + }; + + function isEOF() { + return offset >= buf.length; + } + + function eatBytes(n) { + offset = offset + n; + } + + function readBytesAtOffset(_offset, numberOfBytes) { + var arr = []; + + for (var i = 0; i < numberOfBytes; i++) { + arr.push(buf[_offset + i]); + } + + return arr; + } + + function readBytes(numberOfBytes) { + return readBytesAtOffset(offset, numberOfBytes); + } + + function readF64() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64); + var value = ieee754.decodeF64(bytes); + + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; + + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } + + mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + function readF32() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32); + var value = ieee754.decodeF32(bytes); + + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; + + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } + + mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + function readUTF8String() { + var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using + // readBytesAtOffset below. This keeps readUTF8String neutral with respect + // to the current offset, just like the other readX functions. + + var strlen = lenu32.value; + dump([strlen], "string length"); + var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen); + var value = utf8.decode(bytes); + return { + value: value, + nextIndex: strlen + lenu32.nextIndex + }; + } + /** + * Decode an unsigned 32bits integer + * + * The length will be handled by the leb librairy, we pass the max number of + * byte. + */ + + + function readU32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + + function readVaruint32() { + // where 32 bits = max 4 bytes + var bytes = readBytes(4); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + + function readVaruint7() { + // where 7 bits = max 1 bytes + var bytes = readBytes(1); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + /** + * Decode a signed 32bits interger + */ + + + function read32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt32)(buffer); + } + /** + * Decode a signed 64bits integer + */ + + + function read64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt64)(buffer); + } + + function readU64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt64)(buffer); + } + + function readByte() { + return readBytes(1)[0]; + } + + function parseModuleHeader() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } + + var header = readBytes(4); + + if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { + throw new _helperApiError.CompileError("magic header not detected"); + } + + dump(header, "wasm magic header"); + eatBytes(4); + } + + function parseVersion() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } + + var version = readBytes(4); + + if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) { + throw new _helperApiError.CompileError("unknown binary version"); + } + + dump(version, "wasm version"); + eatBytes(4); + } + + function parseVec(cast) { + var u32 = readU32(); + var length = u32.value; + eatBytes(u32.nextIndex); + dump([length], "number"); + + if (length === 0) { + return []; + } + + var elements = []; + + for (var i = 0; i < length; i++) { + var byte = readByte(); + eatBytes(1); + var value = cast(byte); + dump([byte], value); + + if (typeof value === "undefined") { + throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value"); + } + + elements.push(value); + } + + return elements; + } // Type section + // https://webassembly.github.io/spec/binary/modules.html#binary-typesec + + + function parseTypeSection(numberOfTypes) { + var typeInstructionNodes = []; + dump([numberOfTypes], "num types"); + + for (var i = 0; i < numberOfTypes; i++) { + var _startLoc = getPosition(); + + dumpSep("type " + i); + var type = readByte(); + eatBytes(1); + + if (type == _helperWasmBytecode.default.types.func) { + dump([type], "func"); + var paramValtypes = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + var params = paramValtypes.map(function (v) { + return t.funcParam( + /*valtype*/ + v); + }); + var result = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + typeInstructionNodes.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc); + }()); + state.typesInModule.push({ + params: params, + result: result + }); + } else { + throw new Error("Unsupported type: " + toHex(type)); + } + } + + return typeInstructionNodes; + } // Import section + // https://webassembly.github.io/spec/binary/modules.html#binary-importsec + + + function parseImportSection(numberOfImports) { + var imports = []; + + for (var i = 0; i < numberOfImports; i++) { + dumpSep("import header " + i); + + var _startLoc2 = getPosition(); + /** + * Module name + */ + + + var moduleName = readUTF8String(); + eatBytes(moduleName.nextIndex); + dump([], "module name (".concat(moduleName.value, ")")); + /** + * Name + */ + + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "name (".concat(name.value, ")")); + /** + * Import descr + */ + + var descrTypeByte = readByte(); + eatBytes(1); + var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte]; + dump([descrTypeByte], "import kind"); + + if (typeof descrType === "undefined") { + throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte)); + } + + var importDescr = void 0; + + if (descrType === "func") { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } + + var id = getUniqueName("func"); + importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result)); + state.functionsInModule.push({ + id: t.identifier(name.value), + signature: signature, + isExternal: true + }); + } else if (descrType === "global") { + importDescr = parseGlobalType(); + var globalNode = t.global(importDescr, []); + state.globalsInModule.push(globalNode); + } else if (descrType === "table") { + importDescr = parseTableType(i); + } else if (descrType === "mem") { + var memoryNode = parseMemoryType(0); + state.memoriesInModule.push(memoryNode); + importDescr = memoryNode; + } else { + throw new _helperApiError.CompileError("Unsupported import of type: " + descrType); + } + + imports.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2); + }()); + } + + return imports; + } // Function section + // https://webassembly.github.io/spec/binary/modules.html#function-section + + + function parseFuncSection(numberOfFunctions) { + dump([numberOfFunctions], "num funcs"); + + for (var i = 0; i < numberOfFunctions; i++) { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } // preserve anonymous, a name might be resolved later + + + var id = t.withRaw(t.identifier(getUniqueName("func")), ""); + state.functionsInModule.push({ + id: id, + signature: signature, + isExternal: false + }); + } + } // Export section + // https://webassembly.github.io/spec/binary/modules.html#export-section + + + function parseExportSection(numberOfExport) { + dump([numberOfExport], "num exports"); // Parse vector of exports + + for (var i = 0; i < numberOfExport; i++) { + var _startLoc3 = getPosition(); + /** + * Name + */ + + + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "export name (".concat(name.value, ")")); + /** + * exportdescr + */ + + var typeIndex = readByte(); + eatBytes(1); + dump([typeIndex], "export kind"); + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "export index"); + var id = void 0, + signature = void 0; + + if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") { + var func = state.functionsInModule[index]; + + if (typeof func === "undefined") { + throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = func.signature; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { + var table = state.tablesInModule[index]; + + if (typeof table === "undefined") { + throw new _helperApiError.CompileError("unknown table ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { + var memNode = state.memoriesInModule[index]; + + if (typeof memNode === "undefined") { + throw new _helperApiError.CompileError("unknown memory ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { + var global = state.globalsInModule[index]; + + if (typeof global === "undefined") { + throw new _helperApiError.CompileError("unknown global ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else { + console.warn("Unsupported export type: " + toHex(typeIndex)); + return; + } + + var endLoc = getPosition(); + state.elementsInExportSection.push({ + name: name.value, + type: _helperWasmBytecode.default.exportTypes[typeIndex], + signature: signature, + id: id, + index: index, + endLoc: endLoc, + startLoc: _startLoc3 + }); + } + } // Code section + // https://webassembly.github.io/spec/binary/modules.html#code-section + + + function parseCodeSection(numberOfFuncs) { + dump([numberOfFuncs], "number functions"); // Parse vector of function + + for (var i = 0; i < numberOfFuncs; i++) { + var _startLoc4 = getPosition(); + + dumpSep("function body " + i); // the u32 size of the function code in bytes + // Ignore it for now + + var bodySizeU32 = readU32(); + eatBytes(bodySizeU32.nextIndex); + dump([bodySizeU32.value], "function body size"); + var code = []; + /** + * Parse locals + */ + + var funcLocalNumU32 = readU32(); + var funcLocalNum = funcLocalNumU32.value; + eatBytes(funcLocalNumU32.nextIndex); + dump([funcLocalNum], "num locals"); + var locals = []; + + for (var _i = 0; _i < funcLocalNum; _i++) { + var _startLoc5 = getPosition(); + + var localCountU32 = readU32(); + var localCount = localCountU32.value; + eatBytes(localCountU32.nextIndex); + dump([localCount], "num local"); + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + var args = []; + + for (var _i2 = 0; _i2 < localCount; _i2++) { + args.push(t.valtypeLiteral(type)); + } + + var localNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); + }(); + + locals.push(localNode); + dump([valtypeByte], type); + + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); + } + } + + code.push.apply(code, locals); // Decode instructions until the end + + parseInstructionBlock(code); + var endLoc = getPosition(); + state.elementsInCodeSection.push({ + code: code, + locals: locals, + endLoc: endLoc, + startLoc: _startLoc4, + bodySize: bodySizeU32.value + }); + } + } + + function parseInstructionBlock(code) { + while (true) { + var _startLoc6 = getPosition(); + + var instructionAlreadyCreated = false; + var instructionByte = readByte(); + eatBytes(1); + + if (instructionByte === 0xfe) { + throw new _helperApiError.CompileError("Atomic instructions are not implemented"); + } + + var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; + + if (typeof instruction === "undefined") { + throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); + } + + if (typeof instruction.object === "string") { + dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); + } else { + dump([instructionByte], instruction.name); + } + /** + * End of the function + */ + + + if (instruction.name === "end") { + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); + }(); + + code.push(node); + break; + } + + var args = []; + + if (instruction.name === "loop") { + var _startLoc7 = getPosition(); + + var blocktypeByte = readByte(); + eatBytes(1); + var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte]; + dump([blocktypeByte], "blocktype"); + + if (typeof blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte)); + } + + var instr = []; + parseInstructionBlock(instr); // preserve anonymous + + var label = t.withRaw(t.identifier(getUniqueName("loop")), ""); + + var loopNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); + }(); + + code.push(loopNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "if") { + var _startLoc8 = getPosition(); + + var _blocktypeByte = readByte(); + + eatBytes(1); + var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; + dump([_blocktypeByte], "blocktype"); + + if (typeof _blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); + } + + var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); + var ifBody = []; + parseInstructionBlock(ifBody); // Defaults to no alternate + + var elseIndex = 0; + + for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { + var _instr = ifBody[elseIndex]; + + if (_instr.type === "Instr" && _instr.id === "else") { + break; + } + } + + var consequentInstr = ifBody.slice(0, elseIndex); + var alternate = ifBody.slice(elseIndex + 1); // wast sugar + + var testInstrs = []; + + var ifNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); + }(); + + code.push(ifNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "block") { + var _startLoc9 = getPosition(); + + var _blocktypeByte2 = readByte(); + + eatBytes(1); + var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; + dump([_blocktypeByte2], "blocktype"); + + if (typeof _blocktype2 === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); + } + + var _instr2 = []; + parseInstructionBlock(_instr2); // preserve anonymous + + var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); + + var blockNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); + }(); + + code.push(blockNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call") { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); + + var callNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6); + }(); + + code.push(callNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call_indirect") { + var _startLoc10 = getPosition(); + + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")")); + } + + var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []); + + var flagU32 = readU32(); + var flag = flagU32.value; // 0x00 - reserved byte + + eatBytes(flagU32.nextIndex); + + if (flag !== 0) { + throw new _helperApiError.CompileError("zero flag expected"); + } + + code.push(function () { + var endLoc = getPosition(); + return t.withLoc(_callNode, endLoc, _startLoc10); + }()); + instructionAlreadyCreated = true; + } else if (instruction.name === "br_table") { + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + + for (var i = 0; i <= indices; i++) { + var _indexu = readU32(); + + var _index = _indexu.value; + eatBytes(_indexu.nextIndex); + dump([_index], "index"); + args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32")); + } + } else if (instructionByte >= 0x28 && instructionByte <= 0x40) { + /** + * Memory instructions + */ + if (instruction.name === "grow_memory" || instruction.name === "current_memory") { + var _indexU = readU32(); + + var _index2 = _indexU.value; + eatBytes(_indexU.nextIndex); + + if (_index2 !== 0) { + throw new Error("zero flag expected"); + } + + dump([_index2], "index"); + } else { + var aligun32 = readU32(); + var align = aligun32.value; + eatBytes(aligun32.nextIndex); + dump([align], "align"); + var offsetu32 = readU32(); + var _offset2 = offsetu32.value; + eatBytes(offsetu32.nextIndex); + dump([_offset2], "offset"); + } + } else if (instructionByte >= 0x41 && instructionByte <= 0x44) { + /** + * Numeric instructions + */ + if (instruction.object === "i32") { + var value32 = read32(); + var value = value32.value; + eatBytes(value32.nextIndex); + dump([value], "i32 value"); + args.push(t.numberLiteralFromRaw(value)); + } + + if (instruction.object === "u32") { + var valueu32 = readU32(); + var _value = valueu32.value; + eatBytes(valueu32.nextIndex); + dump([_value], "u32 value"); + args.push(t.numberLiteralFromRaw(_value)); + } + + if (instruction.object === "i64") { + var value64 = read64(); + var _value2 = value64.value; + eatBytes(value64.nextIndex); + dump([Number(_value2.toString())], "i64 value"); + var high = _value2.high, + low = _value2.low; + var _node = { + type: "LongNumberLiteral", + value: { + high: high, + low: low + } + }; + args.push(_node); + } + + if (instruction.object === "u64") { + var valueu64 = readU64(); + var _value3 = valueu64.value; + eatBytes(valueu64.nextIndex); + dump([Number(_value3.toString())], "u64 value"); + var _high = _value3.high, + _low = _value3.low; + var _node2 = { + type: "LongNumberLiteral", + value: { + high: _high, + low: _low + } + }; + args.push(_node2); + } + + if (instruction.object === "f32") { + var valuef32 = readF32(); + var _value4 = valuef32.value; + eatBytes(valuef32.nextIndex); + dump([_value4], "f32 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4))); + } + + if (instruction.object === "f64") { + var valuef64 = readF64(); + var _value5 = valuef64.value; + eatBytes(valuef64.nextIndex); + dump([_value5], "f64 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5))); + } + } else { + for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) { + var u32 = readU32(); + eatBytes(u32.nextIndex); + dump([u32.value], "argument " + _i3); + args.push(t.numberLiteralFromRaw(u32.value)); + } + } + + if (instructionAlreadyCreated === false) { + if (typeof instruction.object === "string") { + var _node3 = function () { + var endLoc = getPosition(); + return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6); + }(); + + code.push(_node3); + } else { + var _node4 = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); + }(); + + code.push(_node4); + } + } + } + } // https://webassembly.github.io/spec/core/binary/types.html#limits + + + function parseLimits() { + var limitType = readByte(); + eatBytes(1); + dump([limitType], "limit type"); + var min, max; + + if (limitType === 0x01 || limitType === 0x03 // shared limits + ) { + var u32min = readU32(); + min = parseInt(u32min.value); + eatBytes(u32min.nextIndex); + dump([min], "min"); + var u32max = readU32(); + max = parseInt(u32max.value); + eatBytes(u32max.nextIndex); + dump([max], "max"); + } + + if (limitType === 0x00) { + var _u32min = readU32(); + + min = parseInt(_u32min.value); + eatBytes(_u32min.nextIndex); + dump([min], "min"); + } + + return t.limit(min, max); + } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype + + + function parseTableType(index) { + var name = t.withRaw(t.identifier(getUniqueName("table")), String(index)); + var elementTypeByte = readByte(); + eatBytes(1); + dump([elementTypeByte], "element type"); + var elementType = _helperWasmBytecode.default.tableTypes[elementTypeByte]; + + if (typeof elementType === "undefined") { + throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType)); + } + + var limits = parseLimits(); + return t.table(elementType, limits, name); + } // https://webassembly.github.io/spec/binary/types.html#global-types + + + function parseGlobalType() { + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + dump([valtypeByte], type); + + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte)); + } + + var globalTypeByte = readByte(); + eatBytes(1); + var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte]; + dump([globalTypeByte], "global type (".concat(globalType, ")")); + + if (typeof globalType === "undefined") { + throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte)); + } + + return t.globalType(type, globalType); + } // function parseNameModule() { + // const lenu32 = readVaruint32(); + // eatBytes(lenu32.nextIndex); + // console.log("len", lenu32); + // const strlen = lenu32.value; + // dump([strlen], "string length"); + // const bytes = readBytes(strlen); + // eatBytes(strlen); + // const value = utf8.decode(bytes); + // return [t.moduleNameMetadata(value)]; + // } + // this section contains an array of function names and indices + + + function parseNameSectionFunctions() { + var functionNames = []; + var numberOfFunctionsu32 = readU32(); + var numbeOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); + + for (var i = 0; i < numbeOfFunctions; i++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + functionNames.push(t.functionNameMetadata(name.value, index)); + } + + return functionNames; + } + + function parseNameSectionLocals() { + var localNames = []; + var numbeOfFunctionsu32 = readU32(); + var numbeOfFunctions = numbeOfFunctionsu32.value; + eatBytes(numbeOfFunctionsu32.nextIndex); + + for (var i = 0; i < numbeOfFunctions; i++) { + var functionIndexu32 = readU32(); + var functionIndex = functionIndexu32.value; + eatBytes(functionIndexu32.nextIndex); + var numLocalsu32 = readU32(); + var numLocals = numLocalsu32.value; + eatBytes(numLocalsu32.nextIndex); + + for (var _i4 = 0; _i4 < numLocals; _i4++) { + var localIndexu32 = readU32(); + var localIndex = localIndexu32.value; + eatBytes(localIndexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex)); + } + } + + return localNames; + } // this is a custom section used for name resolution + // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section + + + function parseNameSection(remainingBytes) { + var nameMetadata = []; + var initialOffset = offset; + + while (offset - initialOffset < remainingBytes) { + // name_type + var sectionTypeByte = readVaruint7(); + eatBytes(sectionTypeByte.nextIndex); // name_payload_len + + var subSectionSizeInBytesu32 = readVaruint32(); + eatBytes(subSectionSizeInBytesu32.nextIndex); + + switch (sectionTypeByte.value) { + // case 0: { + // TODO(sven): re-enable that + // Current status: it seems that when we decode the module's name + // no name_payload_len is used. + // + // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section + // + // nameMetadata.push(...parseNameModule()); + // break; + // } + case 1: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions())); + break; + } + + case 2: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals())); + break; + } + + default: + { + // skip unknown subsection + eatBytes(subSectionSizeInBytesu32.value); + } + } + } + + return nameMetadata; + } // this is a custom section used for information about the producers + // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md + + + function parseProducersSection() { + var metadata = t.producersSectionMetadata([]); // field_count + + var sectionTypeByte = readVaruint32(); + eatBytes(sectionTypeByte.nextIndex); + dump([sectionTypeByte.value], "num of producers"); + var fields = { + language: [], + "processed-by": [], + sdk: [] + }; // fields + + for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) { + // field_name + var fieldName = readUTF8String(); + eatBytes(fieldName.nextIndex); // field_value_count + + var valueCount = readVaruint32(); + eatBytes(valueCount.nextIndex); // field_values + + for (var producerI = 0; producerI < valueCount.value; producerI++) { + var producerName = readUTF8String(); + eatBytes(producerName.nextIndex); + var producerVersion = readUTF8String(); + eatBytes(producerVersion.nextIndex); + fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value)); + } + + metadata.producers.push(fields[fieldName.value]); + } + + return metadata; + } + + function parseGlobalSection(numberOfGlobals) { + var globals = []; + dump([numberOfGlobals], "num globals"); + + for (var i = 0; i < numberOfGlobals; i++) { + var _startLoc11 = getPosition(); + + var globalType = parseGlobalType(); + /** + * Global expressions + */ + + var init = []; + parseInstructionBlock(init); + + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.global(globalType, init), endLoc, _startLoc11); + }(); + + globals.push(node); + state.globalsInModule.push(node); + } + + return globals; + } + + function parseElemSection(numberOfElements) { + var elems = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var _startLoc12 = getPosition(); + + var tableindexu32 = readU32(); + var tableindex = tableindexu32.value; + eatBytes(tableindexu32.nextIndex); + dump([tableindex], "table index"); + /** + * Parse instructions + */ + + var instr = []; + parseInstructionBlock(instr); + /** + * Parse ( vector function index ) * + */ + + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + var indexValues = []; + + for (var _i5 = 0; _i5 < indices; _i5++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); + indexValues.push(t.indexLiteral(index)); + } + + var elemNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); + }(); + + elems.push(elemNode); + } + + return elems; + } // https://webassembly.github.io/spec/core/binary/types.html#memory-types + + + function parseMemoryType(i) { + var limits = parseLimits(); + return t.memory(limits, t.indexLiteral(i)); + } // https://webassembly.github.io/spec/binary/modules.html#table-section + + + function parseTableSection(numberOfElements) { + var tables = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var tablesNode = parseTableType(i); + state.tablesInModule.push(tablesNode); + tables.push(tablesNode); + } + + return tables; + } // https://webassembly.github.io/spec/binary/modules.html#memory-section + + + function parseMemorySection(numberOfElements) { + var memories = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var memoryNode = parseMemoryType(i); + state.memoriesInModule.push(memoryNode); + memories.push(memoryNode); + } + + return memories; + } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec + + + function parseStartSection() { + var startLoc = getPosition(); + var u32 = readU32(); + var startFuncIndex = u32.value; + eatBytes(u32.nextIndex); + dump([startFuncIndex], "index"); + return function () { + var endLoc = getPosition(); + return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc); + }(); + } // https://webassembly.github.io/spec/binary/modules.html#data-section + + + function parseDataSection(numberOfElements) { + var dataEntries = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var memoryIndexu32 = readU32(); + var memoryIndex = memoryIndexu32.value; + eatBytes(memoryIndexu32.nextIndex); + dump([memoryIndex], "memory index"); + var instrs = []; + parseInstructionBlock(instrs); + var hasExtraInstrs = instrs.filter(function (i) { + return i.id !== "end"; + }).length !== 1; + + if (hasExtraInstrs) { + throw new _helperApiError.CompileError("data section offset must be a single instruction"); + } + + var bytes = parseVec(function (b) { + return b; + }); + dump([], "init"); + dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); + } + + return dataEntries; + } // https://webassembly.github.io/spec/binary/modules.html#binary-section + + + function parseSection(sectionIndex) { + var sectionId = readByte(); + eatBytes(1); + + if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode.default.sections.custom) { + sectionIndex = sectionId + 1; + } else { + if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); + } + + var nextSectionIndex = sectionIndex; + var startOffset = offset; + var startLoc = getPosition(); + var u32 = readU32(); + var sectionSizeInBytes = u32.value; + eatBytes(u32.nextIndex); + + var sectionSizeInBytesNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); + }(); + + switch (sectionId) { + case _helperWasmBytecode.default.sections.type: + { + dumpSep("section Type"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc13 = getPosition(); + + var _u = readU32(); + + var numberOfTypes = _u.value; + eatBytes(_u.nextIndex); + + var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13); + }()); + + var _nodes = parseTypeSection(numberOfTypes); + + return { + nodes: _nodes, + metadata: _metadata, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.table: + { + dumpSep("section Table"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc14 = getPosition(); + + var _u2 = readU32(); + + var numberOfTable = _u2.value; + eatBytes(_u2.nextIndex); + dump([numberOfTable], "num tables"); + + var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); + }()); + + var _nodes2 = parseTableSection(numberOfTable); + + return { + nodes: _nodes2, + metadata: _metadata2, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.import: + { + dumpSep("section Import"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc15 = getPosition(); + + var numberOfImportsu32 = readU32(); + var numberOfImports = numberOfImportsu32.value; + eatBytes(numberOfImportsu32.nextIndex); + dump([numberOfImports], "number of imports"); + + var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); + }()); + + var _nodes3 = parseImportSection(numberOfImports); + + return { + nodes: _nodes3, + metadata: _metadata3, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.func: + { + dumpSep("section Function"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc16 = getPosition(); + + var numberOfFunctionsu32 = readU32(); + var numberOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); + + var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); + }()); + + parseFuncSection(numberOfFunctions); + var _nodes4 = []; + return { + nodes: _nodes4, + metadata: _metadata4, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.export: + { + dumpSep("section Export"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc17 = getPosition(); + + var _u3 = readU32(); + + var numberOfExport = _u3.value; + eatBytes(_u3.nextIndex); + + var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17); + }()); + + parseExportSection(numberOfExport); + var _nodes5 = []; + return { + nodes: _nodes5, + metadata: _metadata5, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.code: + { + dumpSep("section Code"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc18 = getPosition(); + + var _u4 = readU32(); + + var numberOfFuncs = _u4.value; + eatBytes(_u4.nextIndex); + + var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); + }()); + + if (opts.ignoreCodeSection === true) { + var remainingBytes = sectionSizeInBytes - _u4.nextIndex; + eatBytes(remainingBytes); // eat the entire section + } else { + parseCodeSection(numberOfFuncs); + } + + var _nodes6 = []; + return { + nodes: _nodes6, + metadata: _metadata6, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.start: + { + dumpSep("section Start"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); + + var _nodes7 = [parseStartSection()]; + return { + nodes: _nodes7, + metadata: _metadata7, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.element: + { + dumpSep("section Element"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc19 = getPosition(); + + var numberOfElementsu32 = readU32(); + var numberOfElements = numberOfElementsu32.value; + eatBytes(numberOfElementsu32.nextIndex); + + var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); + }()); + + var _nodes8 = parseElemSection(numberOfElements); + + return { + nodes: _nodes8, + metadata: _metadata8, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.global: + { + dumpSep("section Global"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc20 = getPosition(); + + var numberOfGlobalsu32 = readU32(); + var numberOfGlobals = numberOfGlobalsu32.value; + eatBytes(numberOfGlobalsu32.nextIndex); + + var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); + }()); + + var _nodes9 = parseGlobalSection(numberOfGlobals); + + return { + nodes: _nodes9, + metadata: _metadata9, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.memory: + { + dumpSep("section Memory"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc21 = getPosition(); + + var _numberOfElementsu = readU32(); + + var _numberOfElements = _numberOfElementsu.value; + eatBytes(_numberOfElementsu.nextIndex); + + var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); + }()); + + var _nodes10 = parseMemorySection(_numberOfElements); + + return { + nodes: _nodes10, + metadata: _metadata10, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.data: + { + dumpSep("section Data"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode); + + var _startLoc22 = getPosition(); + + var _numberOfElementsu2 = readU32(); + + var _numberOfElements2 = _numberOfElementsu2.value; + eatBytes(_numberOfElementsu2.nextIndex); + + _metadata11.vectorOfSize = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22); + }(); + + if (opts.ignoreDataSection === true) { + var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex; + + eatBytes(_remainingBytes); // eat the entire section + + dumpSep("ignore data (" + sectionSizeInBytes + " bytes)"); + return { + nodes: [], + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } else { + var _nodes11 = parseDataSection(_numberOfElements2); + + return { + nodes: _nodes11, + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } + } + + case _helperWasmBytecode.default.sections.custom: + { + dumpSep("section Custom"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + var _metadata12 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)]; + var sectionName = readUTF8String(); + eatBytes(sectionName.nextIndex); + dump([], "section name (".concat(sectionName.value, ")")); + + var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex; + + if (sectionName.value === "name") { + var initialOffset = offset; + + try { + _metadata12.push.apply(_metadata12, _toConsumableArray(parseNameSection(_remainingBytes2))); + } catch (e) { + console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (initialOffset + _remainingBytes2)); + } + } else if (sectionName.value === "producers") { + var _initialOffset = offset; + + try { + _metadata12.push(parseProducersSection()); + } catch (e) { + console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (_initialOffset + _remainingBytes2)); + } + } else { + // We don't parse the custom section + eatBytes(_remainingBytes2); + dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)"); + } + + return { + nodes: [], + metadata: _metadata12, + nextSectionIndex: nextSectionIndex + }; + } + } + + throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); + } + + parseModuleHeader(); + parseVersion(); + var moduleFields = []; + var sectionIndex = 0; + var moduleMetadata = { + sections: [], + functionNames: [], + localNames: [], + producers: [] + }; + /** + * All the generate declaration are going to be stored in our state + */ + + while (offset < buf.length) { + var _parseSection = parseSection(sectionIndex), + _nodes12 = _parseSection.nodes, + _metadata13 = _parseSection.metadata, + nextSectionIndex = _parseSection.nextSectionIndex; + + moduleFields.push.apply(moduleFields, _toConsumableArray(_nodes12)); + var metadataArray = Array.isArray(_metadata13) ? _metadata13 : [_metadata13]; + metadataArray.forEach(function (metadataItem) { + if (metadataItem.type === "FunctionNameMetadata") { + moduleMetadata.functionNames.push(metadataItem); + } else if (metadataItem.type === "LocalNameMetadata") { + moduleMetadata.localNames.push(metadataItem); + } else if (metadataItem.type === "ProducersSectionMetadata") { + moduleMetadata.producers.push(metadataItem); + } else { + moduleMetadata.sections.push(metadataItem); + } + }); // Ignore custom section + + if (nextSectionIndex) { + sectionIndex = nextSectionIndex; + } + } + /** + * Transform the state into AST nodes + */ + + + var funcIndex = 0; + state.functionsInModule.forEach(function (func) { + var params = func.signature.params; + var result = func.signature.result; + var body = []; // External functions doesn't provide any code, can skip it here + + if (func.isExternal === true) { + return; + } + + var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex]; + + if (opts.ignoreCodeSection === false) { + if (typeof decodedElementInCodeSection === "undefined") { + throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found"); + } + + body = decodedElementInCodeSection.code; + } + + funcIndex++; + var funcNode = t.func(func.id, t.signature(params, result), body); + + if (func.isExternal === true) { + funcNode.isExternal = func.isExternal; + } // Add function position in the binary if possible + + + if (opts.ignoreCodeSection === false) { + var _startLoc23 = decodedElementInCodeSection.startLoc, + endLoc = decodedElementInCodeSection.endLoc, + bodySize = decodedElementInCodeSection.bodySize; + funcNode = t.withLoc(funcNode, endLoc, _startLoc23); + funcNode.metadata = { + bodySize: bodySize + }; + } + + moduleFields.push(funcNode); + }); + state.elementsInExportSection.forEach(function (moduleExport) { + /** + * If the export has no id, we won't be able to call it from the outside + * so we can omit it + */ + if (moduleExport.id != null) { + moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc)); + } + }); + dumpSep("end of program"); + var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers)); + return t.program([module]); +} + +/***/ }), + +/***/ 8062: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +var decoder = _interopRequireWildcard(__webpack_require__(72856)); + +var t = _interopRequireWildcard(__webpack_require__(98688)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +/** + * TODO(sven): I added initial props, but we should rather fix + * https://github.com/xtuc/webassemblyjs/issues/405 + */ +var defaultDecoderOpts = { + dump: false, + ignoreCodeSection: false, + ignoreDataSection: false, + ignoreCustomNameSection: false +}; // traverses the AST, locating function name metadata, which is then +// used to update index-based identifiers with function names + +function restoreFunctionNames(ast) { + var functionNames = []; + t.traverse(ast, { + FunctionNameMetadata: function FunctionNameMetadata(_ref) { + var node = _ref.node; + functionNames.push({ + name: node.value, + index: node.index + }); + } + }); + + if (functionNames.length === 0) { + return; + } + + t.traverse(ast, { + Func: function (_Func) { + function Func(_x) { + return _Func.apply(this, arguments); + } + + Func.toString = function () { + return _Func.toString(); + }; + + return Func; + }(function (_ref2) { + var node = _ref2.node; + // $FlowIgnore + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + var oldValue = nodeName.value; + nodeName.value = functionName.name; + nodeName.numeric = oldValue; // $FlowIgnore + + delete nodeName.raw; + } + }), + // Also update the reference in the export + ModuleExport: function (_ModuleExport) { + function ModuleExport(_x2) { + return _ModuleExport.apply(this, arguments); + } + + ModuleExport.toString = function () { + return _ModuleExport.toString(); + }; + + return ModuleExport; + }(function (_ref3) { + var node = _ref3.node; + + if (node.descr.exportType === "Func") { + // $FlowIgnore + var nodeName = node.descr.id; + var index = nodeName.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + node.descr.id = t.identifier(functionName.name); + } + } + }), + ModuleImport: function (_ModuleImport) { + function ModuleImport(_x3) { + return _ModuleImport.apply(this, arguments); + } + + ModuleImport.toString = function () { + return _ModuleImport.toString(); + }; + + return ModuleImport; + }(function (_ref4) { + var node = _ref4.node; + + if (node.descr.type === "FuncImportDescr") { + // $FlowIgnore + var indexBasedFunctionName = node.descr.id; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + // $FlowIgnore + node.descr.id = t.identifier(functionName.name); + } + } + }), + CallInstruction: function (_CallInstruction) { + function CallInstruction(_x4) { + return _CallInstruction.apply(this, arguments); + } + + CallInstruction.toString = function () { + return _CallInstruction.toString(); + }; + + return CallInstruction; + }(function (nodePath) { + var node = nodePath.node; + var index = node.index.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + var oldValue = node.index; + node.index = t.identifier(functionName.name); + node.numeric = oldValue; // $FlowIgnore + + delete node.raw; + } + }) + }); +} + +function restoreLocalNames(ast) { + var localNames = []; + t.traverse(ast, { + LocalNameMetadata: function LocalNameMetadata(_ref5) { + var node = _ref5.node; + localNames.push({ + name: node.value, + localIndex: node.localIndex, + functionIndex: node.functionIndex + }); + } + }); + + if (localNames.length === 0) { + return; + } + + t.traverse(ast, { + Func: function (_Func2) { + function Func(_x5) { + return _Func2.apply(this, arguments); + } + + Func.toString = function () { + return _Func2.toString(); + }; + + return Func; + }(function (_ref6) { + var node = _ref6.node; + var signature = node.signature; + + if (signature.type !== "Signature") { + return; + } // $FlowIgnore + + + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var functionIndex = Number(indexBasedFunctionName.replace("func_", "")); + signature.params.forEach(function (param, paramIndex) { + var paramName = localNames.find(function (f) { + return f.localIndex === paramIndex && f.functionIndex === functionIndex; + }); + + if (paramName && paramName.name !== "") { + param.id = paramName.name; + } + }); + }) + }); +} + +function restoreModuleName(ast) { + t.traverse(ast, { + ModuleNameMetadata: function (_ModuleNameMetadata) { + function ModuleNameMetadata(_x6) { + return _ModuleNameMetadata.apply(this, arguments); + } + + ModuleNameMetadata.toString = function () { + return _ModuleNameMetadata.toString(); + }; + + return ModuleNameMetadata; + }(function (moduleNameMetadataPath) { + // update module + t.traverse(ast, { + Module: function (_Module) { + function Module(_x7) { + return _Module.apply(this, arguments); + } + + Module.toString = function () { + return _Module.toString(); + }; + + return Module; + }(function (_ref7) { + var node = _ref7.node; + var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser + + if (name === "") { + name = null; + } + + node.id = name; + }) + }); + }) + }); +} + +function decode(buf, customOpts) { + var opts = Object.assign({}, defaultDecoderOpts, customOpts); + var ast = decoder.decode(buf, opts); + + if (opts.ignoreCustomNameSection === false) { + restoreFunctionNames(ast); + restoreLocalNames(ast); + restoreModuleName(ast); + } + + return ast; +} + +/***/ }), + +/***/ 68693: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parse = parse; + +var _helperCodeFrame = __webpack_require__(48333); + +var t = _interopRequireWildcard(__webpack_require__(98688)); + +var _numberLiterals = __webpack_require__(3425); + +var _stringLiterals = __webpack_require__(27481); + +var _tokenizer = __webpack_require__(57261); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function hasPlugin(name) { + if (name !== "wast") throw new Error("unknow plugin"); + return true; +} + +function isKeyword(token, id) { + return token.type === _tokenizer.tokens.keyword && token.value === id; +} + +function tokenToString(token) { + if (token.type === "keyword") { + return "keyword (".concat(token.value, ")"); + } + + return token.type; +} + +function identifierFromToken(token) { + var _token$loc = token.loc, + end = _token$loc.end, + start = _token$loc.start; + return t.withLoc(t.identifier(token.value), end, start); +} + +function parse(tokensList, source) { + var current = 0; + var getUniqueName = t.getUniqueNameGenerator(); + var state = { + registredExportedElements: [] + }; // But this time we're going to use recursion instead of a `while` loop. So we + // define a `walk` function. + + function walk() { + var token = tokensList[current]; + + function eatToken() { + token = tokensList[++current]; + } + + function getEndLoc() { + var currentToken = token; + + if (typeof currentToken === "undefined") { + var lastToken = tokensList[tokensList.length - 1]; + currentToken = lastToken; + } + + return currentToken.loc.end; + } + + function getStartLoc() { + return token.loc.start; + } + + function eatTokenOfType(type) { + if (token.type !== type) { + throw new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "Assertion error: expected token of type " + type + ", given " + tokenToString(token)); + } + + eatToken(); + } + + function parseExportIndex(token) { + if (token.type === _tokenizer.tokens.identifier) { + var index = identifierFromToken(token); + eatToken(); + return index; + } else if (token.type === _tokenizer.tokens.number) { + var _index = t.numberLiteralFromRaw(token.value); + + eatToken(); + return _index; + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "unknown export index" + ", given " + tokenToString(token)); + }(); + } + } + + function lookaheadAndCheck() { + var len = arguments.length; + + for (var i = 0; i < len; i++) { + var tokenAhead = tokensList[current + i]; + var expectedToken = i < 0 || arguments.length <= i ? undefined : arguments[i]; + + if (tokenAhead.type === "keyword") { + if (isKeyword(tokenAhead, expectedToken) === false) { + return false; + } + } else if (expectedToken !== tokenAhead.type) { + return false; + } + } + + return true; + } // TODO(sven): there is probably a better way to do this + // can refactor it if it get out of hands + + + function maybeIgnoreComment() { + if (typeof token === "undefined") { + // Ignore + return; + } + + while (token.type === _tokenizer.tokens.comment) { + eatToken(); + + if (typeof token === "undefined") { + // Hit the end + break; + } + } + } + /** + * Parses a memory instruction + * + * WAST: + * + * memory: ( memory ? ) + * ( memory ? ( export ) <...> ) + * ( memory ? ( import ) ) + * ( memory ? ( export )* ( data * ) + * memory_sig: ? + * + */ + + + function parseMemory() { + var id = t.identifier(getUniqueName("memory")); + var limits = t.limit(0); + + if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) { + id = t.identifier(token.value); + eatToken(); + } else { + id = t.withRaw(id, ""); // preserve anonymous + } + /** + * Maybe data + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.data)) { + eatToken(); // ( + + eatToken(); // data + // TODO(sven): do something with the data collected here + + var stringInitializer = token.value; + eatTokenOfType(_tokenizer.tokens.string); // Update limits accordingly + + limits = t.limit(stringInitializer.length); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * Maybe export + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token)); + }(); + } + + var _name = token.value; + eatToken(); + state.registredExportedElements.push({ + exportType: "Memory", + name: _name, + id: id + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * Memory signature + */ + + + if (token.type === _tokenizer.tokens.number) { + limits = t.limit((0, _numberLiterals.parse32I)(token.value)); + eatToken(); + + if (token.type === _tokenizer.tokens.number) { + limits.max = (0, _numberLiterals.parse32I)(token.value); + eatToken(); + } + } + + return t.memory(limits, id); + } + /** + * Parses a data section + * https://webassembly.github.io/spec/core/text/modules.html#data-segments + * + * WAST: + * + * data: ( data ? ) + */ + + + function parseData() { + // optional memory index + var memidx = 0; + + if (token.type === _tokenizer.tokens.number) { + memidx = token.value; + eatTokenOfType(_tokenizer.tokens.number); // . + } + + eatTokenOfType(_tokenizer.tokens.openParen); + var offset; + + if (token.type === _tokenizer.tokens.valtype) { + eatTokenOfType(_tokenizer.tokens.valtype); // i32 + + eatTokenOfType(_tokenizer.tokens.dot); // . + + if (token.value !== "const") { + throw new Error("constant expression required"); + } + + eatTokenOfType(_tokenizer.tokens.name); // const + + var numberLiteral = t.numberLiteralFromRaw(token.value, "i32"); + offset = t.objectInstruction("const", "i32", [numberLiteral]); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + eatTokenOfType(_tokenizer.tokens.name); // get_global + + var _numberLiteral = t.numberLiteralFromRaw(token.value, "i32"); + + offset = t.instruction("get_global", [_numberLiteral]); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + var byteArray = (0, _stringLiterals.parseString)(token.value); + eatToken(); // "string" + + return t.data(t.memIndexLiteral(memidx), offset, t.byteArray(byteArray)); + } + /** + * Parses a table instruction + * + * WAST: + * + * table: ( table ? ) + * ( table ? ( export ) <...> ) + * ( table ? ( import ) ) + * ( table ? ( export )* ( elem * ) ) + * + * table_type: ? + * elem_type: anyfunc + * + * elem: ( elem ? (offset * ) * ) + * ( elem ? * ) + */ + + + function parseTable() { + var name = t.identifier(getUniqueName("table")); + var limit = t.limit(0); + var elemIndices = []; + var elemType = "anyfunc"; + + if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) { + name = identifierFromToken(token); + eatToken(); + } else { + name = t.withRaw(name, ""); // preserve anonymous + } + + while (token.type !== _tokenizer.tokens.closeParen) { + /** + * Maybe export + */ + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.elem)) { + eatToken(); // ( + + eatToken(); // elem + + while (token.type === _tokenizer.tokens.identifier) { + elemIndices.push(t.identifier(token.value)); + eatToken(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token)); + }(); + } + + var exportName = token.value; + eatToken(); + state.registredExportedElements.push({ + exportType: "Table", + name: exportName, + id: name + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (isKeyword(token, _tokenizer.keywords.anyfunc)) { + // It's the default value, we can ignore it + eatToken(); // anyfunc + } else if (token.type === _tokenizer.tokens.number) { + /** + * Table type + */ + var min = parseInt(token.value); + eatToken(); + + if (token.type === _tokenizer.tokens.number) { + var max = parseInt(token.value); + eatToken(); + limit = t.limit(min, max); + } else { + limit = t.limit(min); + } + + eatToken(); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token" + ", given " + tokenToString(token)); + }(); + } + } + + if (elemIndices.length > 0) { + return t.table(elemType, limit, name, elemIndices); + } else { + return t.table(elemType, limit, name); + } + } + /** + * Parses an import statement + * + * WAST: + * + * import: ( import ) + * imkind: ( func ? ) + * ( global ? ) + * ( table ? ) + * ( memory ? ) + * + * global_sig: | ( mut ) + */ + + + function parseImport() { + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected a string, " + token.type + " given."); + } + + var moduleName = token.value; + eatToken(); + + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected a string, " + token.type + " given."); + } + + var name = token.value; + eatToken(); + eatTokenOfType(_tokenizer.tokens.openParen); + var descr; + + if (isKeyword(token, _tokenizer.keywords.func)) { + eatToken(); // keyword + + var fnParams = []; + var fnResult = []; + var typeRef; + var fnName = t.identifier(getUniqueName("func")); + + if (token.type === _tokenizer.tokens.identifier) { + fnName = identifierFromToken(token); + eatToken(); + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.type) === true) { + eatToken(); + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.keywords.param) === true) { + eatToken(); + fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam())); + } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult())); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in import of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (typeof fnName === "undefined") { + throw new Error("Imported function must have a name"); + } + + descr = t.funcImportDescr(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult)); + } else if (isKeyword(token, _tokenizer.keywords.global)) { + eatToken(); // keyword + + if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + eatTokenOfType(_tokenizer.tokens.keyword); // mut keyword + + var valtype = token.value; + eatToken(); + descr = t.globalType(valtype, "var"); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + var _valtype = token.value; + eatTokenOfType(_tokenizer.tokens.valtype); + descr = t.globalType(_valtype, "const"); + } + } else if (isKeyword(token, _tokenizer.keywords.memory) === true) { + eatToken(); // Keyword + + descr = parseMemory(); + } else if (isKeyword(token, _tokenizer.keywords.table) === true) { + eatToken(); // Keyword + + descr = parseTable(); + } else { + throw new Error("Unsupported import type: " + tokenToString(token)); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.moduleImport(moduleName, name, descr); + } + /** + * Parses a block instruction + * + * WAST: + * + * expr: ( block ? * ) + * instr: block ? * end ? + * block_sig : ( result * )* + * + */ + + + function parseBlock() { + var label = t.identifier(getUniqueName("block")); + var blockResult = null; + var instr = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatToken(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + instr.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in block body of type" + ", given " + tokenToString(token)); + }(); + } + + maybeIgnoreComment(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.blockInstruction(label, instr, blockResult); + } + /** + * Parses a if instruction + * + * WAST: + * + * expr: + * ( if ? ( then * ) ( else * )? ) + * ( if ? + ( then * ) ( else * )? ) + * + * instr: + * if ? * end ? + * if ? * else ? * end ? + * + * block_sig : ( result * )* + * + */ + + + function parseIf() { + var blockResult = null; + var label = t.identifier(getUniqueName("if")); + var testInstrs = []; + var consequent = []; + var alternate = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + /** + * Block signature + */ + + if (isKeyword(token, _tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatTokenOfType(_tokenizer.tokens.valtype); + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Then + */ + + + if (isKeyword(token, _tokenizer.keywords.then) === true) { + eatToken(); // then + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + consequent.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in consequent body of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Alternate + */ + + + if (isKeyword(token, _tokenizer.keywords.else)) { + eatToken(); // else + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + alternate.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in alternate body of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Test instruction + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + testInstrs.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in if body" + ", given " + tokenToString(token)); + }(); + } + + return t.ifInstruction(label, testInstrs, blockResult, consequent, alternate); + } + /** + * Parses a loop instruction + * + * WAT: + * + * blockinstr :: 'loop' I:label rt:resulttype (in:instr*) 'end' id? + * + * WAST: + * + * instr :: loop ? * end ? + * expr :: ( loop ? * ) + * block_sig :: ( result * )* + * + */ + + + function parseLoop() { + var label = t.identifier(getUniqueName("loop")); + var blockResult; + var instr = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatToken(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + instr.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in loop body" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.loopInstruction(label, blockResult, instr); + } + + function parseCallIndirect() { + var typeRef; + var params = []; + var results = []; + var instrs = []; + + while (token.type !== _tokenizer.tokens.closeParen) { + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.type)) { + eatToken(); // ( + + eatToken(); // type + + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) { + eatToken(); // ( + + eatToken(); // param + + /** + * Params can be empty: + * (params)` + */ + + if (token.type !== _tokenizer.tokens.closeParen) { + params.push.apply(params, _toConsumableArray(parseFuncParam())); + } + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) { + eatToken(); // ( + + eatToken(); // result + + /** + * Results can be empty: + * (result)` + */ + + if (token.type !== _tokenizer.tokens.closeParen) { + results.push.apply(results, _toConsumableArray(parseFuncResult())); + } + } else { + eatTokenOfType(_tokenizer.tokens.openParen); + instrs.push(parseFuncInstr()); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.callIndirectInstruction(typeRef !== undefined ? typeRef : t.signature(params, results), instrs); + } + /** + * Parses an export instruction + * + * WAT: + * + * export: ( export ) + * exkind: ( func ) + * ( global ) + * ( table ) + * ( memory ) + * var: | + * + */ + + + function parseExport() { + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected string after export, got: " + token.type); + } + + var name = token.value; + eatToken(); + var moduleExportDescr = parseModuleExportDescr(); + return t.moduleExport(name, moduleExportDescr); + } + + function parseModuleExportDescr() { + var startLoc = getStartLoc(); + var type = ""; + var index; + eatTokenOfType(_tokenizer.tokens.openParen); + + while (token.type !== _tokenizer.tokens.closeParen) { + if (isKeyword(token, _tokenizer.keywords.func)) { + type = "Func"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.table)) { + type = "Table"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.global)) { + type = "Global"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.memory)) { + type = "Memory"; + eatToken(); + index = parseExportIndex(token); + } + + eatToken(); + } + + if (type === "") { + throw new Error("Unknown export type"); + } + + if (index === undefined) { + throw new Error("Exported function must have a name"); + } + + var node = t.moduleExportDescr(type, index); + var endLoc = getEndLoc(); + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(node, endLoc, startLoc); + } + + function parseModule() { + var name = null; + var isBinary = false; + var isQuote = false; + var moduleFields = []; + + if (token.type === _tokenizer.tokens.identifier) { + name = token.value; + eatToken(); + } + + if (hasPlugin("wast") && token.type === _tokenizer.tokens.name && token.value === "binary") { + eatToken(); + isBinary = true; + } + + if (hasPlugin("wast") && token.type === _tokenizer.tokens.name && token.value === "quote") { + eatToken(); + isQuote = true; + } + + if (isBinary === true) { + var blob = []; + + while (token.type === _tokenizer.tokens.string) { + blob.push(token.value); + eatToken(); + maybeIgnoreComment(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.binaryModule(name, blob); + } + + if (isQuote === true) { + var string = []; + + while (token.type === _tokenizer.tokens.string) { + string.push(token.value); + eatToken(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.quoteModule(name, string); + } + + while (token.type !== _tokenizer.tokens.closeParen) { + moduleFields.push(walk()); + + if (state.registredExportedElements.length > 0) { + state.registredExportedElements.forEach(function (decl) { + moduleFields.push(t.moduleExport(decl.name, t.moduleExportDescr(decl.exportType, decl.id))); + }); + state.registredExportedElements = []; + } + + token = tokensList[current]; + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.module(name, moduleFields); + } + /** + * Parses the arguments of an instruction + */ + + + function parseFuncInstrArguments(signature) { + var args = []; + var namedArgs = {}; + var signaturePtr = 0; + + while (token.type === _tokenizer.tokens.name || isKeyword(token, _tokenizer.keywords.offset)) { + var key = token.value; + eatToken(); + eatTokenOfType(_tokenizer.tokens.equal); + var value = void 0; + + if (token.type === _tokenizer.tokens.number) { + value = t.numberLiteralFromRaw(token.value); + } else { + throw new Error("Unexpected type for argument: " + token.type); + } + + namedArgs[key] = value; + eatToken(); + } // $FlowIgnore + + + var signatureLength = signature.vector ? Infinity : signature.length; + + while (token.type !== _tokenizer.tokens.closeParen && ( // $FlowIgnore + token.type === _tokenizer.tokens.openParen || signaturePtr < signatureLength)) { + if (token.type === _tokenizer.tokens.identifier) { + args.push(t.identifier(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.valtype) { + // Handle locals + args.push(t.valtypeLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.string) { + args.push(t.stringLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + args.push( // TODO(sven): refactor the type signature handling + // https://github.com/xtuc/webassemblyjs/pull/129 is a good start + t.numberLiteralFromRaw(token.value, // $FlowIgnore + signature[signaturePtr] || "f64")); // $FlowIgnore + + if (!signature.vector) { + ++signaturePtr; + } + + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + /** + * Maybe some nested instructions + */ + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // $FlowIgnore + args.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in nested instruction" + ", given " + tokenToString(token)); + }(); + } + + if (token.type === _tokenizer.tokens.closeParen) { + eatToken(); + } + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in instruction argument" + ", given " + tokenToString(token)); + }(); + } + } + + return { + args: args, + namedArgs: namedArgs + }; + } + /** + * Parses an instruction + * + * WAT: + * + * instr :: plaininst + * blockinstr + * + * blockinstr :: 'block' I:label rt:resulttype (in:instr*) 'end' id? + * 'loop' I:label rt:resulttype (in:instr*) 'end' id? + * 'if' I:label rt:resulttype (in:instr*) 'else' id? (in2:intr*) 'end' id? + * + * plaininst :: 'unreachable' + * 'nop' + * 'br' l:labelidx + * 'br_if' l:labelidx + * 'br_table' l*:vec(labelidx) ln:labelidx + * 'return' + * 'call' x:funcidx + * 'call_indirect' x, I:typeuse + * + * WAST: + * + * instr: + * + * + * block ? * end ? + * loop ? * end ? + * if ? * end ? + * if ? * else ? * end ? + * + * expr: + * ( ) + * ( + ) + * ( block ? * ) + * ( loop ? * ) + * ( if ? ( then * ) ( else * )? ) + * ( if ? + ( then * ) ( else * )? ) + * + * op: + * unreachable + * nop + * br + * br_if + * br_table + + * return + * call + * call_indirect + * drop + * select + * get_local + * set_local + * tee_local + * get_global + * set_global + * .load((8|16|32)_)? ? ? + * .store(8|16|32)? ? ? + * current_memory + * grow_memory + * .const + * . + * . + * . + * . + * ./ + * + * func_type: ( type )? * * + */ + + + function parseFuncInstr() { + var startLoc = getStartLoc(); + maybeIgnoreComment(); + /** + * A simple instruction + */ + + if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + var _name2 = token.value; + var object; + eatToken(); + + if (token.type === _tokenizer.tokens.dot) { + object = _name2; + eatToken(); + + if (token.type !== _tokenizer.tokens.name) { + throw new TypeError("Unknown token: " + token.type + ", name expected"); + } + + _name2 = token.value; + eatToken(); + } + + if (token.type === _tokenizer.tokens.closeParen) { + var _endLoc = token.loc.end; + + if (typeof object === "undefined") { + return t.withLoc(t.instruction(_name2), _endLoc, startLoc); + } else { + return t.withLoc(t.objectInstruction(_name2, object, []), _endLoc, startLoc); + } + } + + var signature = t.signatureForOpcode(object || "", _name2); + + var _parseFuncInstrArgume = parseFuncInstrArguments(signature), + _args = _parseFuncInstrArgume.args, + _namedArgs = _parseFuncInstrArgume.namedArgs; + + var endLoc = token.loc.end; + + if (typeof object === "undefined") { + return t.withLoc(t.instruction(_name2, _args, _namedArgs), endLoc, startLoc); + } else { + return t.withLoc(t.objectInstruction(_name2, object, _args, _namedArgs), endLoc, startLoc); + } + } else if (isKeyword(token, _tokenizer.keywords.loop)) { + /** + * Else a instruction with a keyword (loop or block) + */ + eatToken(); // keyword + + return parseLoop(); + } else if (isKeyword(token, _tokenizer.keywords.block)) { + eatToken(); // keyword + + return parseBlock(); + } else if (isKeyword(token, _tokenizer.keywords.call_indirect)) { + eatToken(); // keyword + + return parseCallIndirect(); + } else if (isKeyword(token, _tokenizer.keywords.call)) { + eatToken(); // keyword + + var index; + + if (token.type === _tokenizer.tokens.identifier) { + index = identifierFromToken(token); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + index = t.indexLiteral(token.value); + eatToken(); + } + + var instrArgs = []; // Nested instruction + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + instrArgs.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (typeof index === "undefined") { + throw new Error("Missing argument in call instruciton"); + } + + if (instrArgs.length > 0) { + return t.callInstruction(index, instrArgs); + } else { + return t.callInstruction(index); + } + } else if (isKeyword(token, _tokenizer.keywords.if)) { + eatToken(); // Keyword + + return parseIf(); + } else if (isKeyword(token, _tokenizer.keywords.module) && hasPlugin("wast")) { + eatToken(); // In WAST you can have a module as an instruction's argument + // we will cast it into a instruction to not break the flow + // $FlowIgnore + + var module = parseModule(); + return module; + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected instruction in function body" + ", given " + tokenToString(token)); + }(); + } + } + /* + * Parses a function + * + * WAT: + * + * functype :: ( 'func' t1:vec(param) t2:vec(result) ) + * param :: ( 'param' id? t:valtype ) + * result :: ( 'result' t:valtype ) + * + * WAST: + * + * func :: ( func ? * * ) + * ( func ? ( export ) <...> ) + * ( func ? ( import ) ) + * func_sig :: ( type )? * * + * param :: ( param * ) | ( param ) + * result :: ( result * ) + * local :: ( local * ) | ( local ) + * + */ + + + function parseFunc() { + var fnName = t.identifier(getUniqueName("func")); + var typeRef; + var fnBody = []; + var fnParams = []; + var fnResult = []; // name + + if (token.type === _tokenizer.tokens.identifier) { + fnName = identifierFromToken(token); + eatToken(); + } else { + fnName = t.withRaw(fnName, ""); // preserve anonymous + } + + maybeIgnoreComment(); + + while (token.type === _tokenizer.tokens.openParen || token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + // Instructions without parens + if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + fnBody.push(parseFuncInstr()); + continue; + } + + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.param) === true) { + eatToken(); + fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam())); + } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult())); + } else if (lookaheadAndCheck(_tokenizer.keywords.export) === true) { + eatToken(); + parseFuncExport(fnName); + } else if (lookaheadAndCheck(_tokenizer.keywords.type) === true) { + eatToken(); + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + fnBody.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in func body" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.func(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult), fnBody); + } + /** + * Parses shorthand export in func + * + * export :: ( export ) + */ + + + function parseFuncExport(funcId) { + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Function export expected a string" + ", given " + tokenToString(token)); + }(); + } + + var name = token.value; + eatToken(); + /** + * Func export shorthand, we trait it as a syntaxic sugar. + * A export ModuleField will be added later. + * + * We give the anonymous function a generated name and export it. + */ + + var id = t.identifier(funcId.value); + state.registredExportedElements.push({ + exportType: "Func", + name: name, + id: id + }); + } + /** + * Parses a type instruction + * + * WAST: + * + * typedef: ( type ? ( func * * ) ) + */ + + + function parseType() { + var id; + var params = []; + var result = []; + + if (token.type === _tokenizer.tokens.identifier) { + id = identifierFromToken(token); + eatToken(); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) { + eatToken(); // ( + + eatToken(); // func + + if (token.type === _tokenizer.tokens.closeParen) { + eatToken(); // function with an empty signature, we can abort here + + return t.typeInstruction(id, t.signature([], [])); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) { + eatToken(); // ( + + eatToken(); // param + + params = parseFuncParam(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) { + eatToken(); // ( + + eatToken(); // result + + result = parseFuncResult(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.typeInstruction(id, t.signature(params, result)); + } + /** + * Parses a function result + * + * WAST: + * + * result :: ( result * ) + */ + + + function parseFuncResult() { + var results = []; + + while (token.type !== _tokenizer.tokens.closeParen) { + if (token.type !== _tokenizer.tokens.valtype) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in func result" + ", given " + tokenToString(token)); + }(); + } + + var valtype = token.value; + eatToken(); + results.push(valtype); + } + + return results; + } + /** + * Parses a type reference + * + */ + + + function parseTypeReference() { + var ref; + + if (token.type === _tokenizer.tokens.identifier) { + ref = identifierFromToken(token); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + ref = t.numberLiteralFromRaw(token.value); + eatToken(); + } + + return ref; + } + /** + * Parses a global instruction + * + * WAST: + * + * global: ( global ? * ) + * ( global ? ( export ) <...> ) + * ( global ? ( import ) ) + * + * global_sig: | ( mut ) + * + */ + + + function parseGlobal() { + var name = t.identifier(getUniqueName("global")); + var type; // Keep informations in case of a shorthand import + + var importing = null; + maybeIgnoreComment(); + + if (token.type === _tokenizer.tokens.identifier) { + name = identifierFromToken(token); + eatToken(); + } else { + name = t.withRaw(name, ""); // preserve anonymous + } + /** + * maybe export + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + var exportName = token.value; + eatTokenOfType(_tokenizer.tokens.string); + state.registredExportedElements.push({ + exportType: "Global", + name: exportName, + id: name + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * maybe import + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.import)) { + eatToken(); // ( + + eatToken(); // import + + var moduleName = token.value; + eatTokenOfType(_tokenizer.tokens.string); + var _name3 = token.value; + eatTokenOfType(_tokenizer.tokens.string); + importing = { + module: moduleName, + name: _name3, + descr: undefined + }; + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * global_sig + */ + + + if (token.type === _tokenizer.tokens.valtype) { + type = t.globalType(token.value, "const"); + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + if (isKeyword(token, _tokenizer.keywords.mut) === false) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unsupported global type, expected mut" + ", given " + tokenToString(token)); + }(); + } + + eatToken(); // mut + + type = t.globalType(token.value, "var"); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (type === undefined) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Could not determine global type" + ", given " + tokenToString(token)); + }(); + } + + maybeIgnoreComment(); + var init = []; + + if (importing != null) { + importing.descr = type; + init.push(t.moduleImport(importing.module, importing.name, importing.descr)); + } + /** + * instr* + */ + + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + init.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.global(type, init, name); + } + /** + * Parses a function param + * + * WAST: + * + * param :: ( param * ) | ( param ) + */ + + + function parseFuncParam() { + var params = []; + var id; + var valtype; + + if (token.type === _tokenizer.tokens.identifier) { + id = token.value; + eatToken(); + } + + if (token.type === _tokenizer.tokens.valtype) { + valtype = token.value; + eatToken(); + params.push({ + id: id, + valtype: valtype + }); + /** + * Shorthand notation for multiple anonymous parameters + * @see https://webassembly.github.io/spec/core/text/types.html#function-types + * @see https://github.com/xtuc/webassemblyjs/issues/6 + */ + + if (id === undefined) { + while (token.type === _tokenizer.tokens.valtype) { + valtype = token.value; + eatToken(); + params.push({ + id: undefined, + valtype: valtype + }); + } + } + } else {// ignore + } + + return params; + } + /** + * Parses an element segments instruction + * + * WAST: + * + * elem: ( elem ? (offset * ) * ) + * ( elem ? * ) + * + * var: | + */ + + + function parseElem() { + var tableIndex = t.indexLiteral(0); + var offset = []; + var funcs = []; + + if (token.type === _tokenizer.tokens.identifier) { + tableIndex = identifierFromToken(token); + eatToken(); + } + + if (token.type === _tokenizer.tokens.number) { + tableIndex = t.indexLiteral(token.value); + eatToken(); + } + + while (token.type !== _tokenizer.tokens.closeParen) { + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.offset)) { + eatToken(); // ( + + eatToken(); // offset + + while (token.type !== _tokenizer.tokens.closeParen) { + eatTokenOfType(_tokenizer.tokens.openParen); + offset.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (token.type === _tokenizer.tokens.identifier) { + funcs.push(t.identifier(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + funcs.push(t.indexLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + offset.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unsupported token in elem" + ", given " + tokenToString(token)); + }(); + } + } + + return t.elem(tableIndex, offset, funcs); + } + /** + * Parses the start instruction in a module + * + * WAST: + * + * start: ( start ) + * var: | + * + * WAT: + * start ::= ‘(’ ‘start’ x:funcidx ‘)’ + */ + + + function parseStart() { + if (token.type === _tokenizer.tokens.identifier) { + var index = identifierFromToken(token); + eatToken(); + return t.start(index); + } + + if (token.type === _tokenizer.tokens.number) { + var _index2 = t.indexLiteral(token.value); + + eatToken(); + return t.start(_index2); + } + + throw new Error("Unknown start, token: " + tokenToString(token)); + } + + if (token.type === _tokenizer.tokens.openParen) { + eatToken(); + var startLoc = getStartLoc(); + + if (isKeyword(token, _tokenizer.keywords.export)) { + eatToken(); + var node = parseExport(); + + var _endLoc2 = getEndLoc(); + + return t.withLoc(node, _endLoc2, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.loop)) { + eatToken(); + + var _node = parseLoop(); + + var _endLoc3 = getEndLoc(); + + return t.withLoc(_node, _endLoc3, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.func)) { + eatToken(); + + var _node2 = parseFunc(); + + var _endLoc4 = getEndLoc(); + + maybeIgnoreComment(); + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node2, _endLoc4, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.module)) { + eatToken(); + + var _node3 = parseModule(); + + var _endLoc5 = getEndLoc(); + + return t.withLoc(_node3, _endLoc5, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.import)) { + eatToken(); + + var _node4 = parseImport(); + + var _endLoc6 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node4, _endLoc6, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.block)) { + eatToken(); + + var _node5 = parseBlock(); + + var _endLoc7 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node5, _endLoc7, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.memory)) { + eatToken(); + + var _node6 = parseMemory(); + + var _endLoc8 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node6, _endLoc8, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.data)) { + eatToken(); + + var _node7 = parseData(); + + var _endLoc9 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node7, _endLoc9, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.table)) { + eatToken(); + + var _node8 = parseTable(); + + var _endLoc10 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node8, _endLoc10, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.global)) { + eatToken(); + + var _node9 = parseGlobal(); + + var _endLoc11 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node9, _endLoc11, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.type)) { + eatToken(); + + var _node10 = parseType(); + + var _endLoc12 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node10, _endLoc12, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.start)) { + eatToken(); + + var _node11 = parseStart(); + + var _endLoc13 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node11, _endLoc13, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.elem)) { + eatToken(); + + var _node12 = parseElem(); + + var _endLoc14 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node12, _endLoc14, startLoc); + } + + var instruction = parseFuncInstr(); + var endLoc = getEndLoc(); + maybeIgnoreComment(); + + if (_typeof(instruction) === "object") { + if (typeof token !== "undefined") { + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.withLoc(instruction, endLoc, startLoc); + } + } + + if (token.type === _tokenizer.tokens.comment) { + var _startLoc = getStartLoc(); + + var builder = token.opts.type === "leading" ? t.leadingComment : t.blockComment; + + var _node13 = builder(token.value); + + eatToken(); // comment + + var _endLoc15 = getEndLoc(); + + return t.withLoc(_node13, _endLoc15, _startLoc); + } + + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unknown token" + ", given " + tokenToString(token)); + }(); + } + + var body = []; + + while (current < tokensList.length) { + body.push(walk()); + } + + return t.program(body); +} + +/***/ }), + +/***/ 9016: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + parse: true +}; +exports.parse = parse; + +var parser = _interopRequireWildcard(__webpack_require__(68693)); + +var _tokenizer = __webpack_require__(57261); + +var _numberLiterals = __webpack_require__(3425); + +Object.keys(_numberLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numberLiterals[key]; + } + }); +}); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function parse(source) { + var tokens = (0, _tokenizer.tokenize)(source); // We pass the source here to show code frames + + var ast = parser.parse(tokens, source); + return ast; +} + +/***/ }), + +/***/ 3425: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parse32F = parse32F; +exports.parse64F = parse64F; +exports.parse32I = parse32I; +exports.parseU32 = parseU32; +exports.parse64I = parse64I; +exports.isInfLiteral = isInfLiteral; +exports.isNanLiteral = isNanLiteral; + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +var _floatingPointHexParser = _interopRequireDefault(__webpack_require__(83268)); + +var _helperApiError = __webpack_require__(36194); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse32F(sourceString) { + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + if (isInfLiteral(sourceString)) { + return sourceString[0] === "-" ? -1 : 1; + } + + if (isNanLiteral(sourceString)) { + return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x400000); + } + + return parseFloat(sourceString); +} + +function parse64F(sourceString) { + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + if (isInfLiteral(sourceString)) { + return sourceString[0] === "-" ? -1 : 1; + } + + if (isNanLiteral(sourceString)) { + return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x8000000000000); + } + + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + return parseFloat(sourceString); +} + +function parse32I(sourceString) { + var value = 0; + + if (isHexLiteral(sourceString)) { + value = ~~parseInt(sourceString, 16); + } else if (isDecimalExponentLiteral(sourceString)) { + throw new Error("This number literal format is yet to be implemented."); + } else { + value = parseInt(sourceString, 10); + } + + return value; +} + +function parseU32(sourceString) { + var value = parse32I(sourceString); + + if (value < 0) { + throw new _helperApiError.CompileError("Illegal value for u32: " + sourceString); + } + + return value; +} + +function parse64I(sourceString) { + var long; + + if (isHexLiteral(sourceString)) { + long = _long.default.fromString(sourceString, false, 16); + } else if (isDecimalExponentLiteral(sourceString)) { + throw new Error("This number literal format is yet to be implemented."); + } else { + long = _long.default.fromString(sourceString); + } + + return { + high: long.high, + low: long.low + }; +} + +var NAN_WORD = /^\+?-?nan/; +var INF_WORD = /^\+?-?inf/; + +function isInfLiteral(sourceString) { + return INF_WORD.test(sourceString.toLowerCase()); +} + +function isNanLiteral(sourceString) { + return NAN_WORD.test(sourceString.toLowerCase()); +} + +function isDecimalExponentLiteral(sourceString) { + return !isHexLiteral(sourceString) && sourceString.toUpperCase().includes("E"); +} + +function isHexLiteral(sourceString) { + return sourceString.substring(0, 2).toUpperCase() === "0X" || sourceString.substring(0, 3).toUpperCase() === "-0X"; +} + +/***/ }), + +/***/ 27481: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parseString = parseString; +// string literal characters cannot contain control codes +var CONTROL_CODES = [0, // null +7, // bell +8, // backspace +9, // horizontal +10, // line feed +11, // vertical tab +12, // form feed +13, // carriage return +26, // Control-Z +27, // escape +127 // delete +]; // escaped sequences can either be a two character hex value, or one of the +// following single character codes + +function decodeControlCharacter(char) { + switch (char) { + case "t": + return 0x09; + + case "n": + return 0x0a; + + case "r": + return 0x0d; + + case '"': + return 0x22; + + case "′": + return 0x27; + + case "\\": + return 0x5c; + } + + return -1; +} + +var ESCAPE_CHAR = 92; // backslash + +var QUOTE_CHAR = 34; // backslash +// parse string as per the spec: +// https://webassembly.github.io/spec/core/multipage/text/values.html#text-string + +function parseString(value) { + var byteArray = []; + var index = 0; + + while (index < value.length) { + var charCode = value.charCodeAt(index); + + if (CONTROL_CODES.indexOf(charCode) !== -1) { + throw new Error("ASCII control characters are not permitted within string literals"); + } + + if (charCode === QUOTE_CHAR) { + throw new Error("quotes are not permitted within string literals"); + } + + if (charCode === ESCAPE_CHAR) { + var firstChar = value.substr(index + 1, 1); + var decodedControlChar = decodeControlCharacter(firstChar); + + if (decodedControlChar !== -1) { + // single character escaped values, e.g. \r + byteArray.push(decodedControlChar); + index += 2; + } else { + // hex escaped values, e.g. \2a + var hexValue = value.substr(index + 1, 2); + + if (!/^[0-9A-F]{2}$/i.test(hexValue)) { + throw new Error("invalid character encoding"); + } + + byteArray.push(parseInt(hexValue, 16)); + index += 3; + } + } else { + // ASCII encoded values + byteArray.push(charCode); + index++; + } + } + + return byteArray; +} + +/***/ }), + +/***/ 57261: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.tokenize = tokenize; +exports.tokens = exports.keywords = void 0; + +var _helperFsm = __webpack_require__(38902); + +var _helperCodeFrame = __webpack_require__(48333); + +// eslint-disable-next-line +function getCodeFrame(source, line, column) { + var loc = { + start: { + line: line, + column: column + } + }; + return "\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, loc) + "\n"; +} + +var WHITESPACE = /\s/; +var PARENS = /\(|\)/; +var LETTERS = /[a-z0-9_/]/i; +var idchar = /[a-z0-9!#$%&*+./:<=>?@\\[\]^_`|~-]/i; +var valtypes = ["i32", "i64", "f32", "f64"]; +var NUMBERS = /[0-9|.|_]/; +var NUMBER_KEYWORDS = /nan|inf/; + +function isNewLine(char) { + return char.charCodeAt(0) === 10 || char.charCodeAt(0) === 13; +} + +function Token(type, value, start, end) { + var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var token = { + type: type, + value: value, + loc: { + start: start, + end: end + } + }; + + if (Object.keys(opts).length > 0) { + // $FlowIgnore + token["opts"] = opts; + } + + return token; +} + +var tokenTypes = { + openParen: "openParen", + closeParen: "closeParen", + number: "number", + string: "string", + name: "name", + identifier: "identifier", + valtype: "valtype", + dot: "dot", + comment: "comment", + equal: "equal", + keyword: "keyword" +}; +var keywords = { + module: "module", + func: "func", + param: "param", + result: "result", + export: "export", + loop: "loop", + block: "block", + if: "if", + then: "then", + else: "else", + call: "call", + call_indirect: "call_indirect", + import: "import", + memory: "memory", + table: "table", + global: "global", + anyfunc: "anyfunc", + mut: "mut", + data: "data", + type: "type", + elem: "elem", + start: "start", + offset: "offset" +}; +exports.keywords = keywords; +var NUMERIC_SEPARATOR = "_"; +/** + * Build the FSM for number literals + */ + +var numberLiteralFSM = new _helperFsm.FSM({ + START: [(0, _helperFsm.makeTransition)(/-|\+/, "AFTER_SIGN"), (0, _helperFsm.makeTransition)(/nan:0x/, "NAN_HEX", { + n: 6 + }), (0, _helperFsm.makeTransition)(/nan|inf/, "STOP", { + n: 3 + }), (0, _helperFsm.makeTransition)(/0x/, "HEX", { + n: 2 + }), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC"), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC")], + AFTER_SIGN: [(0, _helperFsm.makeTransition)(/nan:0x/, "NAN_HEX", { + n: 6 + }), (0, _helperFsm.makeTransition)(/nan|inf/, "STOP", { + n: 3 + }), (0, _helperFsm.makeTransition)(/0x/, "HEX", { + n: 2 + }), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC"), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC")], + DEC_FRAC: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC_FRAC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/e|E/, "DEC_SIGNED_EXP")], + DEC: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC"), (0, _helperFsm.makeTransition)(/e|E/, "DEC_SIGNED_EXP")], + DEC_SIGNED_EXP: [(0, _helperFsm.makeTransition)(/\+|-/, "DEC_EXP"), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC_EXP")], + DEC_EXP: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC_EXP", { + allowedSeparator: NUMERIC_SEPARATOR + })], + HEX: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "HEX", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/\./, "HEX_FRAC"), (0, _helperFsm.makeTransition)(/p|P/, "HEX_SIGNED_EXP")], + HEX_FRAC: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "HEX_FRAC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/p|P|/, "HEX_SIGNED_EXP")], + HEX_SIGNED_EXP: [(0, _helperFsm.makeTransition)(/[0-9|+|-]/, "HEX_EXP")], + HEX_EXP: [(0, _helperFsm.makeTransition)(/[0-9]/, "HEX_EXP", { + allowedSeparator: NUMERIC_SEPARATOR + })], + NAN_HEX: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "NAN_HEX", { + allowedSeparator: NUMERIC_SEPARATOR + })], + STOP: [] +}, "START", "STOP"); + +function tokenize(input) { + var current = 0; + var char = input[current]; // Used by SourceLocation + + var column = 1; + var line = 1; + var tokens = []; + /** + * Creates a pushToken function for a given type + */ + + function pushToken(type) { + return function (v) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var startColumn = opts.startColumn || column - String(v).length; + delete opts.startColumn; + var endColumn = opts.endColumn || startColumn + String(v).length - 1; + delete opts.endColumn; + var start = { + line: line, + column: startColumn + }; + var end = { + line: line, + column: endColumn + }; + tokens.push(Token(type, v, start, end, opts)); + }; + } + /** + * Functions to save newly encountered tokens + */ + + + var pushCloseParenToken = pushToken(tokenTypes.closeParen); + var pushOpenParenToken = pushToken(tokenTypes.openParen); + var pushNumberToken = pushToken(tokenTypes.number); + var pushValtypeToken = pushToken(tokenTypes.valtype); + var pushNameToken = pushToken(tokenTypes.name); + var pushIdentifierToken = pushToken(tokenTypes.identifier); + var pushKeywordToken = pushToken(tokenTypes.keyword); + var pushDotToken = pushToken(tokenTypes.dot); + var pushStringToken = pushToken(tokenTypes.string); + var pushCommentToken = pushToken(tokenTypes.comment); + var pushEqualToken = pushToken(tokenTypes.equal); + /** + * Can be used to look at the next character(s). + * + * The default behavior `lookahead()` simply returns the next character without consuming it. + * Letters are always returned in lowercase. + * + * @param {number} length How many characters to query. Default = 1 + * @param {number} offset How many characters to skip forward from current one. Default = 1 + * + */ + + function lookahead() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return input.substring(current + offset, current + offset + length).toLowerCase(); + } + /** + * Advances the cursor in the input by a certain amount + * + * @param {number} amount How many characters to consume. Default = 1 + */ + + + function eatCharacter() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + column += amount; + current += amount; + char = input[current]; + } + + while (current < input.length) { + // ;; + if (char === ";" && lookahead() === ";") { + var startColumn = column; + eatCharacter(2); + var text = ""; + + while (!isNewLine(char)) { + text += char; + eatCharacter(); + + if (char === undefined) { + break; + } + } + + var endColumn = column; + pushCommentToken(text, { + type: "leading", + startColumn: startColumn, + endColumn: endColumn + }); + continue; + } // (; + + + if (char === "(" && lookahead() === ";") { + var _startColumn = column; + eatCharacter(2); + var _text = ""; // ;) + + while (true) { + char = input[current]; + + if (char === ";" && lookahead() === ")") { + eatCharacter(2); + break; + } + + _text += char; + eatCharacter(); + + if (isNewLine(char)) { + line++; + column = 0; + } + } + + var _endColumn = column; + pushCommentToken(_text, { + type: "block", + startColumn: _startColumn, + endColumn: _endColumn + }); + continue; + } + + if (char === "(") { + pushOpenParenToken(char); + eatCharacter(); + continue; + } + + if (char === "=") { + pushEqualToken(char); + eatCharacter(); + continue; + } + + if (char === ")") { + pushCloseParenToken(char); + eatCharacter(); + continue; + } + + if (isNewLine(char)) { + line++; + eatCharacter(); + column = 0; + continue; + } + + if (WHITESPACE.test(char)) { + eatCharacter(); + continue; + } + + if (char === "$") { + var _startColumn2 = column; + eatCharacter(); + var value = ""; + + while (idchar.test(char)) { + value += char; + eatCharacter(); + } + + var _endColumn2 = column; + pushIdentifierToken(value, { + startColumn: _startColumn2, + endColumn: _endColumn2 + }); + continue; + } + + if (NUMBERS.test(char) || NUMBER_KEYWORDS.test(lookahead(3, 0)) || char === "-" || char === "+") { + var _startColumn3 = column; + + var _value = numberLiteralFSM.run(input.slice(current)); + + if (_value === "") { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + pushNumberToken(_value, { + startColumn: _startColumn3 + }); + eatCharacter(_value.length); + + if (char && !PARENS.test(char) && !WHITESPACE.test(char)) { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + continue; + } + + if (char === '"') { + var _startColumn4 = column; + var _value2 = ""; + eatCharacter(); // " + + while (char !== '"') { + if (isNewLine(char)) { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + _value2 += char; + eatCharacter(); // char + } + + eatCharacter(); // " + + var _endColumn3 = column; + pushStringToken(_value2, { + startColumn: _startColumn4, + endColumn: _endColumn3 + }); + continue; + } + + if (LETTERS.test(char)) { + var _value3 = ""; + var _startColumn5 = column; + + while (char && LETTERS.test(char)) { + _value3 += char; + eatCharacter(); + } + /* + * Handle MemberAccess + */ + + + if (char === ".") { + var dotStartColumn = column; + + if (valtypes.indexOf(_value3) !== -1) { + pushValtypeToken(_value3, { + startColumn: _startColumn5 + }); + } else { + pushNameToken(_value3); + } + + eatCharacter(); + _value3 = ""; + var nameStartColumn = column; + + while (LETTERS.test(char)) { + _value3 += char; + eatCharacter(); + } + + pushDotToken(".", { + startColumn: dotStartColumn + }); + pushNameToken(_value3, { + startColumn: nameStartColumn + }); + continue; + } + /* + * Handle keywords + */ + // $FlowIgnore + + + if (typeof keywords[_value3] === "string") { + pushKeywordToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + /* + * Handle types + */ + + + if (valtypes.indexOf(_value3) !== -1) { + pushValtypeToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + /* + * Handle literals + */ + + + pushNameToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + return tokens; +} + +var tokens = tokenTypes; +exports.tokens = tokens; + +/***/ }), + +/***/ 45378: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.print = print; + +var _ast = __webpack_require__(98688); + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +var compact = false; +var space = " "; + +var quote = function quote(str) { + return "\"".concat(str, "\""); +}; + +function indent(nb) { + return Array(nb).fill(space + space).join(""); +} // TODO(sven): allow arbitrary ast nodes + + +function print(n) { + if (n.type === "Program") { + return printProgram(n, 0); + } else { + throw new Error("Unsupported node in print of type: " + String(n.type)); + } +} + +function printProgram(n, depth) { + return n.body.reduce(function (acc, child) { + if (child.type === "Module") { + acc += printModule(child, depth + 1); + } + + if (child.type === "Func") { + acc += printFunc(child, depth + 1); + } + + if (child.type === "BlockComment") { + acc += printBlockComment(child); + } + + if (child.type === "LeadingComment") { + acc += printLeadingComment(child); + } + + if (compact === false) { + acc += "\n"; + } + + return acc; + }, ""); +} + +function printTypeInstruction(n) { + var out = ""; + out += "("; + out += "type"; + out += space; + + if (n.id != null) { + out += printIndex(n.id); + out += space; + } + + out += "("; + out += "func"; + n.functype.params.forEach(function (param) { + out += space; + out += "("; + out += "param"; + out += space; + out += printFuncParam(param); + out += ")"; + }); + n.functype.results.forEach(function (result) { + out += space; + out += "("; + out += "result"; + out += space; + out += result; + out += ")"; + }); + out += ")"; // func + + out += ")"; + return out; +} + +function printModule(n, depth) { + var out = "("; + out += "module"; + + if (typeof n.id === "string") { + out += space; + out += n.id; + } + + if (compact === false) { + out += "\n"; + } else { + out += space; + } + + n.fields.forEach(function (field) { + if (compact === false) { + out += indent(depth); + } + + switch (field.type) { + case "Func": + { + out += printFunc(field, depth + 1); + break; + } + + case "TypeInstruction": + { + out += printTypeInstruction(field); + break; + } + + case "Table": + { + out += printTable(field); + break; + } + + case "Global": + { + out += printGlobal(field, depth + 1); + break; + } + + case "ModuleExport": + { + out += printModuleExport(field); + break; + } + + case "ModuleImport": + { + out += printModuleImport(field); + break; + } + + case "Memory": + { + out += printMemory(field); + break; + } + + case "BlockComment": + { + out += printBlockComment(field); + break; + } + + case "LeadingComment": + { + out += printLeadingComment(field); + break; + } + + case "Start": + { + out += printStart(field); + break; + } + + case "Elem": + { + out += printElem(field, depth); + break; + } + + case "Data": + { + out += printData(field, depth); + break; + } + + default: + throw new Error("Unsupported node in printModule: " + String(field.type)); + } + + if (compact === false) { + out += "\n"; + } + }); + out += ")"; + return out; +} + +function printData(n, depth) { + var out = ""; + out += "("; + out += "data"; + out += space; + out += printIndex(n.memoryIndex); + out += space; + out += printInstruction(n.offset, depth); + out += space; + out += '"'; + n.init.values.forEach(function (byte) { + // Avoid non-displayable characters + if (byte <= 31 || byte == 34 || byte == 92 || byte >= 127) { + out += "\\"; + out += ("00" + byte.toString(16)).substr(-2); + } else if (byte > 255) { + throw new Error("Unsupported byte in data segment: " + byte); + } else { + out += String.fromCharCode(byte); + } + }); + out += '"'; + out += ")"; + return out; +} + +function printElem(n, depth) { + var out = ""; + out += "("; + out += "elem"; + out += space; + out += printIndex(n.table); + + var _n$offset = _slicedToArray(n.offset, 1), + firstOffset = _n$offset[0]; + + out += space; + out += "("; + out += "offset"; + out += space; + out += printInstruction(firstOffset, depth); + out += ")"; + n.funcs.forEach(function (func) { + out += space; + out += printIndex(func); + }); + out += ")"; + return out; +} + +function printStart(n) { + var out = ""; + out += "("; + out += "start"; + out += space; + out += printIndex(n.index); + out += ")"; + return out; +} + +function printLeadingComment(n) { + // Don't print leading comments in compact mode + if (compact === true) { + return ""; + } + + var out = ""; + out += ";;"; + out += n.value; + out += "\n"; + return out; +} + +function printBlockComment(n) { + // Don't print block comments in compact mode + if (compact === true) { + return ""; + } + + var out = ""; + out += "(;"; + out += n.value; + out += ";)"; + out += "\n"; + return out; +} + +function printSignature(n) { + var out = ""; + n.params.forEach(function (param) { + out += space; + out += "("; + out += "param"; + out += space; + out += printFuncParam(param); + out += ")"; + }); + n.results.forEach(function (result) { + out += space; + out += "("; + out += "result"; + out += space; + out += result; + out += ")"; + }); + return out; +} + +function printModuleImportDescr(n) { + var out = ""; + + if (n.type === "FuncImportDescr") { + out += "("; + out += "func"; + + if ((0, _ast.isAnonymous)(n.id) === false) { + out += space; + out += printIdentifier(n.id); + } + + out += printSignature(n.signature); + out += ")"; + } + + if (n.type === "GlobalType") { + out += "("; + out += "global"; + out += space; + out += printGlobalType(n); + out += ")"; + } + + if (n.type === "Table") { + out += printTable(n); + } + + return out; +} + +function printModuleImport(n) { + var out = ""; + out += "("; + out += "import"; + out += space; + out += quote(n.module); + out += space; + out += quote(n.name); + out += space; + out += printModuleImportDescr(n.descr); + out += ")"; + return out; +} + +function printGlobalType(n) { + var out = ""; + + if (n.mutability === "var") { + out += "("; + out += "mut"; + out += space; + out += n.valtype; + out += ")"; + } else { + out += n.valtype; + } + + return out; +} + +function printGlobal(n, depth) { + var out = ""; + out += "("; + out += "global"; + out += space; + + if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) { + out += printIdentifier(n.name); + out += space; + } + + out += printGlobalType(n.globalType); + out += space; + n.init.forEach(function (i) { + out += printInstruction(i, depth + 1); + }); + out += ")"; + return out; +} + +function printTable(n) { + var out = ""; + out += "("; + out += "table"; + out += space; + + if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) { + out += printIdentifier(n.name); + out += space; + } + + out += printLimit(n.limits); + out += space; + out += n.elementType; + out += ")"; + return out; +} + +function printFuncParam(n) { + var out = ""; + + if (typeof n.id === "string") { + out += "$" + n.id; + out += space; + } + + out += n.valtype; + return out; +} + +function printFunc(n, depth) { + var out = ""; + out += "("; + out += "func"; + + if (n.name != null) { + if (n.name.type === "Identifier" && (0, _ast.isAnonymous)(n.name) === false) { + out += space; + out += printIdentifier(n.name); + } + } + + if (n.signature.type === "Signature") { + out += printSignature(n.signature); + } else { + var index = n.signature; + out += space; + out += "("; + out += "type"; + out += space; + out += printIndex(index); + out += ")"; + } + + if (n.body.length > 0) { + // func is empty since we ignore the default end instruction + if (n.body.length === 1 && n.body[0].id === "end") { + out += ")"; + return out; + } + + if (compact === false) { + out += "\n"; + } + + n.body.forEach(function (i) { + if (i.id !== "end") { + out += indent(depth); + out += printInstruction(i, depth); + + if (compact === false) { + out += "\n"; + } + } + }); + out += indent(depth - 1) + ")"; + } else { + out += ")"; + } + + return out; +} + +function printInstruction(n, depth) { + switch (n.type) { + case "Instr": + // $FlowIgnore + return printGenericInstruction(n, depth + 1); + + case "BlockInstruction": + // $FlowIgnore + return printBlockInstruction(n, depth + 1); + + case "IfInstruction": + // $FlowIgnore + return printIfInstruction(n, depth + 1); + + case "CallInstruction": + // $FlowIgnore + return printCallInstruction(n, depth + 1); + + case "CallIndirectInstruction": + // $FlowIgnore + return printCallIndirectIntruction(n, depth + 1); + + case "LoopInstruction": + // $FlowIgnore + return printLoopInstruction(n, depth + 1); + + default: + throw new Error("Unsupported instruction: " + JSON.stringify(n.type)); + } +} + +function printCallIndirectIntruction(n, depth) { + var out = ""; + out += "("; + out += "call_indirect"; + + if (n.signature.type === "Signature") { + out += printSignature(n.signature); + } else if (n.signature.type === "Identifier") { + out += space; + out += "("; + out += "type"; + out += space; + out += printIdentifier(n.signature); + out += ")"; + } else { + throw new Error("CallIndirectInstruction: unsupported signature " + JSON.stringify(n.signature.type)); + } + + out += space; + + if (n.intrs != null) { + // $FlowIgnore + n.intrs.forEach(function (i, index) { + // $FlowIgnore + out += printInstruction(i, depth + 1); // $FlowIgnore + + if (index !== n.intrs.length - 1) { + out += space; + } + }); + } + + out += ")"; + return out; +} + +function printLoopInstruction(n, depth) { + var out = ""; + out += "("; + out += "loop"; + + if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) { + out += space; + out += printIdentifier(n.label); + } + + if (typeof n.resulttype === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.resulttype; + out += ")"; + } + + if (n.instr.length > 0) { + n.instr.forEach(function (e) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(e, depth + 1); + }); + + if (compact === false) { + out += "\n"; + out += indent(depth - 1); + } + } + + out += ")"; + return out; +} + +function printCallInstruction(n, depth) { + var out = ""; + out += "("; + out += "call"; + out += space; + out += printIndex(n.index); + + if (_typeof(n.instrArgs) === "object") { + // $FlowIgnore + n.instrArgs.forEach(function (arg) { + out += space; + out += printFuncInstructionArg(arg, depth + 1); + }); + } + + out += ")"; + return out; +} + +function printIfInstruction(n, depth) { + var out = ""; + out += "("; + out += "if"; + + if (n.testLabel != null && (0, _ast.isAnonymous)(n.testLabel) === false) { + out += space; + out += printIdentifier(n.testLabel); + } + + if (typeof n.result === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.result; + out += ")"; + } + + if (n.test.length > 0) { + out += space; + n.test.forEach(function (i) { + out += printInstruction(i, depth + 1); + }); + } + + if (n.consequent.length > 0) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += "("; + out += "then"; + depth++; + n.consequent.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + depth--; + + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += ")"; + } else { + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += "("; + out += "then"; + out += ")"; + } + + if (n.alternate.length > 0) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += "("; + out += "else"; + depth++; + n.alternate.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + depth--; + + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += ")"; + } else { + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += "("; + out += "else"; + out += ")"; + } + + if (compact === false) { + out += "\n"; + out += indent(depth - 1); + } + + out += ")"; + return out; +} + +function printBlockInstruction(n, depth) { + var out = ""; + out += "("; + out += "block"; + + if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) { + out += space; + out += printIdentifier(n.label); + } + + if (typeof n.result === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.result; + out += ")"; + } + + if (n.instr.length > 0) { + n.instr.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + + if (compact === false) { + out += "\n"; + } + + out += indent(depth - 1); + out += ")"; + } else { + out += ")"; + } + + return out; +} + +function printGenericInstruction(n, depth) { + var out = ""; + out += "("; + + if (typeof n.object === "string") { + out += n.object; + out += "."; + } + + out += n.id; + n.args.forEach(function (arg) { + out += space; + out += printFuncInstructionArg(arg, depth + 1); + }); + out += ")"; + return out; +} + +function printLongNumberLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + var _n$value = n.value, + low = _n$value.low, + high = _n$value.high; + var v = new _long.default(low, high); + return v.toString(); +} + +function printFloatLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + return String(n.value); +} + +function printFuncInstructionArg(n, depth) { + var out = ""; + + if (n.type === "NumberLiteral") { + out += printNumberLiteral(n); + } + + if (n.type === "LongNumberLiteral") { + out += printLongNumberLiteral(n); + } + + if (n.type === "Identifier" && (0, _ast.isAnonymous)(n) === false) { + out += printIdentifier(n); + } + + if (n.type === "ValtypeLiteral") { + out += n.name; + } + + if (n.type === "FloatLiteral") { + out += printFloatLiteral(n); + } + + if ((0, _ast.isInstruction)(n)) { + out += printInstruction(n, depth + 1); + } + + return out; +} + +function printNumberLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + return String(n.value); +} + +function printModuleExport(n) { + var out = ""; + out += "("; + out += "export"; + out += space; + out += quote(n.name); + + if (n.descr.exportType === "Func") { + out += space; + out += "("; + out += "func"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Global") { + out += space; + out += "("; + out += "global"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Memory" || n.descr.exportType === "Mem") { + out += space; + out += "("; + out += "memory"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Table") { + out += space; + out += "("; + out += "table"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else { + throw new Error("printModuleExport: unknown type: " + n.descr.exportType); + } + + out += ")"; + return out; +} + +function printIdentifier(n) { + return "$" + n.value; +} + +function printIndex(n) { + if (n.type === "Identifier") { + return printIdentifier(n); + } else if (n.type === "NumberLiteral") { + return printNumberLiteral(n); + } else { + throw new Error("Unsupported index: " + n.type); + } +} + +function printMemory(n) { + var out = ""; + out += "("; + out += "memory"; + + if (n.id != null) { + out += space; + out += printIndex(n.id); + out += space; + } + + out += printLimit(n.limits); + out += ")"; + return out; +} + +function printLimit(n) { + var out = ""; + out += n.min + ""; + + if (n.max != null) { + out += space; + out += String(n.max); + } + + return out; +} + +/***/ }), + +/***/ 30848: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.read = read; +exports.write = write; + +function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +} + +function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + + +/***/ }), + +/***/ 77960: +/***/ ((module) => { + +module.exports = Long; + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = null; + +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ + 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11 + ])), {}).exports; +} catch (e) { + // no wasm support :( +} + +/** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * @exports Long + * @class A Long class for representing a 64 bit two's-complement integer value. + * @param {number} low The low (signed) 32 bits of the long + * @param {number} high The high (signed) 32 bits of the long + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @constructor + */ +function Long(low, high, unsigned) { + + /** + * The low 32 bits as a signed value. + * @type {number} + */ + this.low = low | 0; + + /** + * The high 32 bits as a signed value. + * @type {number} + */ + this.high = high | 0; + + /** + * Whether unsigned or not. + * @type {boolean} + */ + this.unsigned = !!unsigned; +} + +// The internal representation of a long is the two given signed, 32-bit values. +// We use 32-bit pieces because these are the size of integers on which +// Javascript performs bit-operations. For operations like addition and +// multiplication, we split each number into 16 bit pieces, which can easily be +// multiplied within Javascript's floating-point representation without overflow +// or change in sign. +// +// In the algorithms below, we frequently reduce the negative case to the +// positive case by negating the input(s) and then post-processing the result. +// Note that we must ALWAYS check specially whether those values are MIN_VALUE +// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as +// a positive number, it overflows back into a negative). Not handling this +// case would often result in infinite recursion. +// +// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* +// methods on which they depend. + +/** + * An indicator used to reliably determine if an object is a Long or not. + * @type {boolean} + * @const + * @private + */ +Long.prototype.__isLong__; + +Object.defineProperty(Long.prototype, "__isLong__", { value: true }); + +/** + * @function + * @param {*} obj Object + * @returns {boolean} + * @inner + */ +function isLong(obj) { + return (obj && obj["__isLong__"]) === true; +} + +/** + * Tests if the specified object is a Long. + * @function + * @param {*} obj Object + * @returns {boolean} + */ +Long.isLong = isLong; + +/** + * A cache of the Long representations of small integer values. + * @type {!Object} + * @inner + */ +var INT_CACHE = {}; + +/** + * A cache of the Long representations of small unsigned integer values. + * @type {!Object} + * @inner + */ +var UINT_CACHE = {}; + +/** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if (cache = (0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = (-128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } +} + +/** + * Returns a Long representing the given 32 bit integer value. + * @function + * @param {number} value The 32 bit integer in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromInt = fromInt; + +/** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) + return UZERO; + if (value >= TWO_PWR_64_DBL) + return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) + return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return MAX_VALUE; + } + if (value < 0) + return fromNumber(-value, unsigned).neg(); + return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); +} + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @function + * @param {number} value The number in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromNumber = fromNumber; + +/** + * @param {number} lowBits + * @param {number} highBits + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); +} + +/** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @function + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromBits = fromBits; + +/** + * @function + * @param {number} base + * @param {number} exponent + * @returns {number} + * @inner + */ +var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) + +/** + * @param {string} str + * @param {(boolean|number)=} unsigned + * @param {number=} radix + * @returns {!Long} + * @inner + */ +function fromString(str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + radix = unsigned, + unsigned = false; + } else { + unsigned = !! unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 8)); + + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; +} + +/** + * Returns a Long representation of the given string, written using the specified radix. + * @function + * @param {string} str The textual representation of the Long + * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Long} The corresponding Long value + */ +Long.fromString = fromString; + +/** + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromValue(val, unsigned) { + if (typeof val === 'number') + return fromNumber(val, unsigned); + if (typeof val === 'string') + return fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); +} + +/** + * Converts the specified value to a Long using the appropriate from* function for its type. + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} + */ +Long.fromValue = fromValue; + +// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be +// no runtime penalty for these. + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_16_DBL = 1 << 16; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_24_DBL = 1 << 24; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** + * @type {!Long} + * @const + * @inner + */ +var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + +/** + * @type {!Long} + * @inner + */ +var ZERO = fromInt(0); + +/** + * Signed zero. + * @type {!Long} + */ +Long.ZERO = ZERO; + +/** + * @type {!Long} + * @inner + */ +var UZERO = fromInt(0, true); + +/** + * Unsigned zero. + * @type {!Long} + */ +Long.UZERO = UZERO; + +/** + * @type {!Long} + * @inner + */ +var ONE = fromInt(1); + +/** + * Signed one. + * @type {!Long} + */ +Long.ONE = ONE; + +/** + * @type {!Long} + * @inner + */ +var UONE = fromInt(1, true); + +/** + * Unsigned one. + * @type {!Long} + */ +Long.UONE = UONE; + +/** + * @type {!Long} + * @inner + */ +var NEG_ONE = fromInt(-1); + +/** + * Signed negative one. + * @type {!Long} + */ +Long.NEG_ONE = NEG_ONE; + +/** + * @type {!Long} + * @inner + */ +var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false); + +/** + * Maximum signed value. + * @type {!Long} + */ +Long.MAX_VALUE = MAX_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true); + +/** + * Maximum unsigned value. + * @type {!Long} + */ +Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MIN_VALUE = fromBits(0, 0x80000000|0, false); + +/** + * Minimum signed value. + * @type {!Long} + */ +Long.MIN_VALUE = MIN_VALUE; + +/** + * @alias Long.prototype + * @inner + */ +var LongPrototype = Long.prototype; + +/** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + * @this {!Long} + * @returns {number} + */ +LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; +}; + +/** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @this {!Long} + * @returns {number} + */ +LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); +}; + +/** + * Converts the Long to a string written in the specified radix. + * @this {!Long} + * @param {number=} radix Radix (2-36), defaults to 10 + * @returns {string} + * @override + * @throws {RangeError} If `radix` is out of range + */ +LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { // Unsigned Longs are never negative + if (this.eq(MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else + return '-' + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), + rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower), + intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, + digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) + return digits + result; + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } +}; + +/** + * Gets the high 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed high bits + */ +LongPrototype.getHighBits = function getHighBits() { + return this.high; +}; + +/** + * Gets the high 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned high bits + */ +LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; +}; + +/** + * Gets the low 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed low bits + */ +LongPrototype.getLowBits = function getLowBits() { + return this.low; +}; + +/** + * Gets the low 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned low bits + */ +LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; +}; + +/** + * Gets the number of bits needed to represent the absolute value of this Long. + * @this {!Long} + * @returns {number} + */ +LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) // Unsigned Longs are never negative + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) != 0) + break; + return this.high != 0 ? bit + 33 : bit + 1; +}; + +/** + * Tests if this Long's value equals zero. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; +}; + +/** + * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. + * @returns {boolean} + */ +LongPrototype.eqz = LongPrototype.isZero; + +/** + * Tests if this Long's value is negative. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; +}; + +/** + * Tests if this Long's value is positive. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; +}; + +/** + * Tests if this Long's value is odd. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; +}; + +/** + * Tests if this Long's value is even. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; +}; + +/** + * Tests if this Long's value equals the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.equals = function equals(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1) + return false; + return this.high === other.high && this.low === other.low; +}; + +/** + * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.eq = LongPrototype.equals; + +/** + * Tests if this Long's value differs from the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.notEquals = function notEquals(other) { + return !this.eq(/* validates */ other); +}; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.neq = LongPrototype.notEquals; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.ne = LongPrototype.notEquals; + +/** + * Tests if this Long's value is less than the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThan = function lessThan(other) { + return this.comp(/* validates */ other) < 0; +}; + +/** + * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lt = LongPrototype.lessThan; + +/** + * Tests if this Long's value is less than or equal the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(/* validates */ other) <= 0; +}; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lte = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.le = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is greater than the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(/* validates */ other) > 0; +}; + +/** + * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.gt = LongPrototype.greaterThan; + +/** + * Tests if this Long's value is greater than or equal the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(/* validates */ other) >= 0; +}; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.gte = LongPrototype.greaterThanOrEqual; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.ge = LongPrototype.greaterThanOrEqual; + +/** + * Compares this Long's value with the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.compare = function compare(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1; +}; + +/** + * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. + * @function + * @param {!Long|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.comp = LongPrototype.compare; + +/** + * Negates this Long's value. + * @this {!Long} + * @returns {!Long} Negated Long + */ +LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) + return MIN_VALUE; + return this.not().add(ONE); +}; + +/** + * Negates this Long's value. This is an alias of {@link Long#negate}. + * @function + * @returns {!Long} Negated Long + */ +LongPrototype.neg = LongPrototype.negate; + +/** + * Returns the sum of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} addend Addend + * @returns {!Long} Sum + */ +LongPrototype.add = function add(addend) { + if (!isLong(addend)) + addend = fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xFFFF; + var a16 = this.low >>> 16; + var a00 = this.low & 0xFFFF; + + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xFFFF; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the difference of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) + subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); +}; + +/** + * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. + * @function + * @param {!Long|number|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.sub = LongPrototype.subtract; + +/** + * Returns the product of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) + return ZERO; + if (!isLong(multiplier)) + multiplier = fromValue(multiplier); + + // use wasm support if present + if (wasm) { + var low = wasm["mul"](this.low, + this.high, + multiplier.low, + multiplier.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (multiplier.isZero()) + return ZERO; + if (this.eq(MIN_VALUE)) + return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) + return this.isOdd() ? MIN_VALUE : ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xFFFF; + var a16 = this.low >>> 16; + var a00 = this.low & 0xFFFF; + + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xFFFF; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. + * @function + * @param {!Long|number|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.mul = LongPrototype.multiply; + +/** + * Returns this Long divided by the specified. The result is signed if this Long is signed or + * unsigned if this Long is unsigned. + * @this {!Long} + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (this.isZero()) + return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(MIN_VALUE)) + return ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) + return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return UZERO; + if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true + return UONE; + res = UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2), + delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48), + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + approxRes = fromNumber(approx), + approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; +}; + +/** + * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.div = LongPrototype.divide; + +/** + * Returns this Long modulo the specified. + * @this {!Long} + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); +}; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.mod = LongPrototype.modulo; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.rem = LongPrototype.modulo; + +/** + * Returns the bitwise NOT of this Long. + * @this {!Long} + * @returns {!Long} + */ +LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); +}; + +/** + * Returns the bitwise AND of this Long and the specified. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.and = function and(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); +}; + +/** + * Returns the bitwise OR of this Long and the specified. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.or = function or(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); +}; + +/** + * Returns the bitwise XOR of this Long and the given one. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.xor = function xor(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return fromBits(0, this.low << (numBits - 32), this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shl = LongPrototype.shiftLeft; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); +}; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr = LongPrototype.shiftRight; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits < 32) return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >>> numBits, this.unsigned); + if (numBits === 32) return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); +}; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shru = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits rotated to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.low << numBits) | (this.high >>> b)), ((this.high << numBits) | (this.low >>> b)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.high << numBits) | (this.low >>> b)), ((this.low << numBits) | (this.high >>> b)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotl = LongPrototype.rotateLeft; + +/** + * Returns this Long with bits rotated to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.high << b) | (this.low >>> numBits)), ((this.low << b) | (this.high >>> numBits)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.low << b) | (this.high >>> numBits)), ((this.high << b) | (this.low >>> numBits)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotr = LongPrototype.rotateRight; + +/** + * Converts this Long to signed. + * @this {!Long} + * @returns {!Long} Signed long + */ +LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) + return this; + return fromBits(this.low, this.high, false); +}; + +/** + * Converts this Long to unsigned. + * @this {!Long} + * @returns {!Long} Unsigned long + */ +LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) + return this; + return fromBits(this.low, this.high, true); +}; + +/** + * Converts this Long to its byte representation. + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @this {!Long} + * @returns {!Array.} Byte representation + */ +LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); +}; + +/** + * Converts this Long to its little endian byte representation. + * @this {!Long} + * @returns {!Array.} Little endian byte representation + */ +LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, + lo = this.low; + return [ + lo & 0xff, + lo >>> 8 & 0xff, + lo >>> 16 & 0xff, + lo >>> 24 , + hi & 0xff, + hi >>> 8 & 0xff, + hi >>> 16 & 0xff, + hi >>> 24 + ]; +}; + +/** + * Converts this Long to its big endian byte representation. + * @this {!Long} + * @returns {!Array.} Big endian byte representation + */ +LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, + lo = this.low; + return [ + hi >>> 24 , + hi >>> 16 & 0xff, + hi >>> 8 & 0xff, + hi & 0xff, + lo >>> 24 , + lo >>> 16 & 0xff, + lo >>> 8 & 0xff, + lo & 0xff + ]; +}; + +/** + * Creates a Long from its byte representation. + * @param {!Array.} bytes Byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @returns {Long} The corresponding Long value + */ +Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); +}; + +/** + * Creates a Long from its little endian byte representation. + * @param {!Array.} bytes Little endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long( + bytes[0] | + bytes[1] << 8 | + bytes[2] << 16 | + bytes[3] << 24, + bytes[4] | + bytes[5] << 8 | + bytes[6] << 16 | + bytes[7] << 24, + unsigned + ); +}; + +/** + * Creates a Long from its big endian byte representation. + * @param {!Array.} bytes Big endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long( + bytes[4] << 24 | + bytes[5] << 16 | + bytes[6] << 8 | + bytes[7], + bytes[0] << 24 | + bytes[1] << 16 | + bytes[2] << 8 | + bytes[3], + unsigned + ); +}; + + +/***/ }), + +/***/ 82133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var KEYWORDS = __webpack_require__(72670); + +module.exports = defineKeywords; + + +/** + * Defines one or several keywords in ajv instance + * @param {Ajv} ajv validator instance + * @param {String|Array|undefined} keyword keyword(s) to define + * @return {Ajv} ajv instance (for chaining) + */ +function defineKeywords(ajv, keyword) { + if (Array.isArray(keyword)) { + for (var i=0; i { + +"use strict"; + + +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i; +var DATE_TIME_SEPARATOR = /t|\s/i; + +var COMPARE_FORMATS = { + date: compareDate, + time: compareTime, + 'date-time': compareDateTime +}; + +var $dataMetaSchema = { + type: 'object', + required: [ '$data' ], + properties: { + $data: { + type: 'string', + anyOf: [ + { format: 'relative-json-pointer' }, + { format: 'json-pointer' } + ] + } + }, + additionalProperties: false +}; + +module.exports = function (minMax) { + var keyword = 'format' + minMax; + return function defFunc(ajv) { + defFunc.definition = { + type: 'string', + inline: __webpack_require__(67194), + statements: true, + errors: 'full', + dependencies: ['format'], + metaSchema: { + anyOf: [ + {type: 'string'}, + $dataMetaSchema + ] + } + }; + + ajv.addKeyword(keyword, defFunc.definition); + ajv.addKeyword('formatExclusive' + minMax, { + dependencies: ['format' + minMax], + metaSchema: { + anyOf: [ + {type: 'boolean'}, + $dataMetaSchema + ] + } + }); + extendFormats(ajv); + return ajv; + }; +}; + + +function extendFormats(ajv) { + var formats = ajv._formats; + for (var name in COMPARE_FORMATS) { + var format = formats[name]; + // the last condition is needed if it's RegExp from another window + if (typeof format != 'object' || format instanceof RegExp || !format.validate) + format = formats[name] = { validate: format }; + if (!format.compare) + format.compare = COMPARE_FORMATS[name]; + } +} + + +function compareDate(d1, d2) { + if (!(d1 && d2)) return; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + if (d1 === d2) return 0; +} + + +function compareTime(t1, t2) { + if (!(t1 && t2)) return; + t1 = t1.match(TIME); + t2 = t2.match(TIME); + if (!(t1 && t2)) return; + t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); + t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); + if (t1 > t2) return 1; + if (t1 < t2) return -1; + if (t1 === t2) return 0; +} + + +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return; + dt1 = dt1.split(DATE_TIME_SEPARATOR); + dt2 = dt2.split(DATE_TIME_SEPARATOR); + var res = compareDate(dt1[0], dt2[0]); + if (res === undefined) return; + return res || compareTime(dt1[1], dt2[1]); +} + + +/***/ }), + +/***/ 33733: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + metaSchemaRef: metaSchemaRef +}; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +function metaSchemaRef(ajv) { + var defaultMeta = ajv._opts.defaultMeta; + if (typeof defaultMeta == 'string') return { $ref: defaultMeta }; + if (ajv.getSchema(META_SCHEMA_ID)) return { $ref: META_SCHEMA_ID }; + console.warn('meta schema not defined'); + return {}; +} + + +/***/ }), + +/***/ 25541: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema, parentSchema) { + if (!schema) return true; + var properties = Object.keys(parentSchema.properties); + if (properties.length == 0) return true; + return {required: properties}; + }, + metaSchema: {type: 'boolean'}, + dependencies: ['properties'] + }; + + ajv.addKeyword('allRequired', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 97039: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + if (schema.length == 0) return true; + if (schema.length == 1) return {required: schema}; + var schemas = schema.map(function (prop) { + return {required: [prop]}; + }); + return {anyOf: schemas}; + }, + metaSchema: { + type: 'array', + items: { + type: 'string' + } + } + }; + + ajv.addKeyword('anyRequired', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 51673: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(33733); + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + var schemas = []; + for (var pointer in schema) + schemas.push(getSchema(pointer, schema[pointer])); + return {'allOf': schemas}; + }, + metaSchema: { + type: 'object', + propertyNames: { + type: 'string', + format: 'json-pointer' + }, + additionalProperties: util.metaSchemaRef(ajv) + } + }; + + ajv.addKeyword('deepProperties', defFunc.definition); + return ajv; +}; + + +function getSchema(jsonPointer, schema) { + var segments = jsonPointer.split('/'); + var rootSchema = {}; + var pointerSchema = rootSchema; + for (var i=1; i { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + inline: function (it, keyword, schema) { + var expr = ''; + for (var i=0; i { + +"use strict"; + +module.exports = function generate__formatLimit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + out += 'var ' + ($valid) + ' = undefined;'; + if (it.opts.format === false) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $schemaFormat = it.schema.format, + $isDataFormat = it.opts.$data && $schemaFormat.$data, + $closingBraces = ''; + if ($isDataFormat) { + var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr), + $format = 'format' + $lvl, + $compare = 'compare' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;'; + } else { + var $format = it.formats[$schemaFormat]; + if (!($format && $format.compare)) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; + } + var $isMax = $keyword == 'formatMaximum', + $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'), + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $result = 'result' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); + if (!$exclusive) { + out += '='; + } + out += ' 0;'; + } + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '}'; + return out; +} + + +/***/ }), + +/***/ 83724: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_patternRequired(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $matched = 'patternMatched' + $lvl, + $dataProperties = 'dataProperties' + $lvl, + $closingBraces = '', + $ownProperties = it.opts.ownProperties; + out += 'var ' + ($valid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + var arr1 = $schema; + if (arr1) { + var $pProperty, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $pProperty = arr1[i1 += 1]; + out += ' var ' + ($matched) + ' = false; '; + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; + var $missingPattern = it.util.escapeQuotes($pProperty); + out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + out += '' + ($closingBraces); + return out; +} + + +/***/ }), + +/***/ 20608: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_switch(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $ifPassed = 'ifPassed' + it.level, + $currentBaseId = $it.baseId, + $shouldContinue; + out += 'var ' + ($ifPassed) + ';'; + var arr1 = $schema; + if (arr1) { + var $sch, $caseIndex = -1, + l1 = arr1.length - 1; + while ($caseIndex < l1) { + $sch = arr1[$caseIndex += 1]; + if ($caseIndex && !$shouldContinue) { + out += ' if (!' + ($ifPassed) + ') { '; + $closingBraces += '}'; + } + if ($sch.if && (it.opts.strictKeywords ? typeof $sch.if == 'object' && Object.keys($sch.if).length > 0 : it.util.schemaHasRules($sch.if, it.RULES.all))) { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + $it.schema = $sch.if; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; + } else { + out += ' ' + ($ifPassed) + ' = true; '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + } + $shouldContinue = $sch.continue + } + } + out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + ';'; + return out; +} + + +/***/ }), + +/***/ 32107: +/***/ ((module) => { + +"use strict"; + + +var sequences = {}; + +var DEFAULTS = { + timestamp: function() { return Date.now(); }, + datetime: function() { return (new Date).toISOString(); }, + date: function() { return (new Date).toISOString().slice(0, 10); }, + time: function() { return (new Date).toISOString().slice(11); }, + random: function() { return Math.random(); }, + randomint: function (args) { + var limit = args && args.max || 2; + return function() { return Math.floor(Math.random() * limit); }; + }, + seq: function (args) { + var name = args && args.name || ''; + sequences[name] = sequences[name] || 0; + return function() { return sequences[name]++; }; + } +}; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + compile: function (schema, parentSchema, it) { + var funcs = {}; + + for (var key in schema) { + var d = schema[key]; + var func = getDefault(typeof d == 'string' ? d : d.func); + funcs[key] = func.length ? func(d.args) : func; + } + + return it.opts.useDefaults && !it.compositeRule + ? assignDefaults + : noop; + + function assignDefaults(data) { + for (var prop in schema){ + if (data[prop] === undefined + || (it.opts.useDefaults == 'empty' + && (data[prop] === null || data[prop] === ''))) + data[prop] = funcs[prop](); + } + return true; + } + + function noop() { return true; } + }, + DEFAULTS: DEFAULTS, + metaSchema: { + type: 'object', + additionalProperties: { + type: ['string', 'object'], + additionalProperties: false, + required: ['func', 'args'], + properties: { + func: { type: 'string' }, + args: { type: 'object' } + } + } + } + }; + + ajv.addKeyword('dynamicDefaults', defFunc.definition); + return ajv; + + function getDefault(d) { + var def = DEFAULTS[d]; + if (def) return def; + throw new Error('invalid "dynamicDefaults" keyword property value: ' + d); + } +}; + + +/***/ }), + +/***/ 46153: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = __webpack_require__(92784)('Maximum'); + + +/***/ }), + +/***/ 54409: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = __webpack_require__(92784)('Minimum'); + + +/***/ }), + +/***/ 72670: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = { + 'instanceof': __webpack_require__(62479), + range: __webpack_require__(79159), + regexp: __webpack_require__(23284), + 'typeof': __webpack_require__(22608), + dynamicDefaults: __webpack_require__(32107), + allRequired: __webpack_require__(25541), + anyRequired: __webpack_require__(97039), + oneRequired: __webpack_require__(12135), + prohibited: __webpack_require__(63115), + uniqueItemProperties: __webpack_require__(43786), + deepProperties: __webpack_require__(51673), + deepRequired: __webpack_require__(12541), + formatMinimum: __webpack_require__(54409), + formatMaximum: __webpack_require__(46153), + patternRequired: __webpack_require__(5844), + 'switch': __webpack_require__(682), + select: __webpack_require__(22308), + transform: __webpack_require__(40159) +}; + + +/***/ }), + +/***/ 62479: +/***/ ((module) => { + +"use strict"; + + +var CONSTRUCTORS = { + Object: Object, + Array: Array, + Function: Function, + Number: Number, + String: String, + Date: Date, + RegExp: RegExp +}; + +module.exports = function defFunc(ajv) { + /* istanbul ignore else */ + if (typeof Buffer != 'undefined') + CONSTRUCTORS.Buffer = Buffer; + + /* istanbul ignore else */ + if (typeof Promise != 'undefined') + CONSTRUCTORS.Promise = Promise; + + defFunc.definition = { + compile: function (schema) { + if (typeof schema == 'string') { + var Constructor = getConstructor(schema); + return function (data) { + return data instanceof Constructor; + }; + } + + var constructors = schema.map(getConstructor); + return function (data) { + for (var i=0; i { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + if (schema.length == 0) return true; + if (schema.length == 1) return {required: schema}; + var schemas = schema.map(function (prop) { + return {required: [prop]}; + }); + return {oneOf: schemas}; + }, + metaSchema: { + type: 'array', + items: { + type: 'string' + } + } + }; + + ajv.addKeyword('oneRequired', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 5844: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + inline: __webpack_require__(83724), + statements: true, + errors: 'full', + metaSchema: { + type: 'array', + items: { + type: 'string', + format: 'regex' + }, + uniqueItems: true + } + }; + + ajv.addKeyword('patternRequired', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 63115: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + if (schema.length == 0) return true; + if (schema.length == 1) return {not: {required: schema}}; + var schemas = schema.map(function (prop) { + return {required: [prop]}; + }); + return {not: {anyOf: schemas}}; + }, + metaSchema: { + type: 'array', + items: { + type: 'string' + } + } + }; + + ajv.addKeyword('prohibited', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 79159: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'number', + macro: function (schema, parentSchema) { + var min = schema[0] + , max = schema[1] + , exclusive = parentSchema.exclusiveRange; + + validateRangeSchema(min, max, exclusive); + + return exclusive === true + ? {exclusiveMinimum: min, exclusiveMaximum: max} + : {minimum: min, maximum: max}; + }, + metaSchema: { + type: 'array', + minItems: 2, + maxItems: 2, + items: { type: 'number' } + } + }; + + ajv.addKeyword('range', defFunc.definition); + ajv.addKeyword('exclusiveRange'); + return ajv; + + function validateRangeSchema(min, max, exclusive) { + if (exclusive !== undefined && typeof exclusive != 'boolean') + throw new Error('Invalid schema for exclusiveRange keyword, should be boolean'); + + if (min > max || (exclusive && min == max)) + throw new Error('There are no numbers in range'); + } +}; + + +/***/ }), + +/***/ 23284: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'string', + inline: function (it, keyword, schema) { + return getRegExp() + '.test(data' + (it.dataLevel || '') + ')'; + + function getRegExp() { + try { + if (typeof schema == 'object') + return new RegExp(schema.pattern, schema.flags); + + var rx = schema.match(/^\/(.*)\/([gimuy]*)$/); + if (rx) return new RegExp(rx[1], rx[2]); + throw new Error('cannot parse string into RegExp'); + } catch(e) { + console.error('regular expression', schema, 'is invalid'); + throw e; + } + } + }, + metaSchema: { + type: ['string', 'object'], + properties: { + pattern: { type: 'string' }, + flags: { type: 'string' } + }, + required: ['pattern'], + additionalProperties: false + } + }; + + ajv.addKeyword('regexp', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 22308: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(33733); + +module.exports = function defFunc(ajv) { + if (!ajv._opts.$data) { + console.warn('keyword select requires $data option'); + return ajv; + } + var metaSchemaRef = util.metaSchemaRef(ajv); + var compiledCaseSchemas = []; + + defFunc.definition = { + validate: function v(schema, data, parentSchema) { + if (parentSchema.selectCases === undefined) + throw new Error('keyword "selectCases" is absent'); + var compiled = getCompiledSchemas(parentSchema, false); + var validate = compiled.cases[schema]; + if (validate === undefined) validate = compiled.default; + if (typeof validate == 'boolean') return validate; + var valid = validate(data); + if (!valid) v.errors = validate.errors; + return valid; + }, + $data: true, + metaSchema: { type: ['string', 'number', 'boolean', 'null'] } + }; + + ajv.addKeyword('select', defFunc.definition); + ajv.addKeyword('selectCases', { + compile: function (schemas, parentSchema) { + var compiled = getCompiledSchemas(parentSchema); + for (var value in schemas) + compiled.cases[value] = compileOrBoolean(schemas[value]); + return function() { return true; }; + }, + valid: true, + metaSchema: { + type: 'object', + additionalProperties: metaSchemaRef + } + }); + ajv.addKeyword('selectDefault', { + compile: function (schema, parentSchema) { + var compiled = getCompiledSchemas(parentSchema); + compiled.default = compileOrBoolean(schema); + return function() { return true; }; + }, + valid: true, + metaSchema: metaSchemaRef + }); + return ajv; + + + function getCompiledSchemas(parentSchema, create) { + var compiled; + compiledCaseSchemas.some(function (c) { + if (c.parentSchema === parentSchema) { + compiled = c; + return true; + } + }); + if (!compiled && create !== false) { + compiled = { + parentSchema: parentSchema, + cases: {}, + default: true + }; + compiledCaseSchemas.push(compiled); + } + return compiled; + } + + function compileOrBoolean(schema) { + return typeof schema == 'boolean' + ? schema + : ajv.compile(schema); + } +}; + + +/***/ }), + +/***/ 682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(33733); + +module.exports = function defFunc(ajv) { + if (ajv.RULES.keywords.switch && ajv.RULES.keywords.if) return; + + var metaSchemaRef = util.metaSchemaRef(ajv); + + defFunc.definition = { + inline: __webpack_require__(20608), + statements: true, + errors: 'full', + metaSchema: { + type: 'array', + items: { + required: [ 'then' ], + properties: { + 'if': metaSchemaRef, + 'then': { + anyOf: [ + { type: 'boolean' }, + metaSchemaRef + ] + }, + 'continue': { type: 'boolean' } + }, + additionalProperties: false, + dependencies: { + 'continue': [ 'if' ] + } + } + } + }; + + ajv.addKeyword('switch', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 40159: +/***/ ((module) => { + +"use strict"; + + +module.exports = function defFunc (ajv) { + var transform = { + trimLeft: function (value) { + return value.replace(/^[\s]+/, ''); + }, + trimRight: function (value) { + return value.replace(/[\s]+$/, ''); + }, + trim: function (value) { + return value.trim(); + }, + toLowerCase: function (value) { + return value.toLowerCase(); + }, + toUpperCase: function (value) { + return value.toUpperCase(); + }, + toEnumCase: function (value, cfg) { + return cfg.hash[makeHashTableKey(value)] || value; + } + }; + + defFunc.definition = { + type: 'string', + errors: false, + modifying: true, + valid: true, + compile: function (schema, parentSchema) { + var cfg; + + if (schema.indexOf('toEnumCase') !== -1) { + // build hash table to enum values + cfg = {hash: {}}; + + // requires `enum` in schema + if (!parentSchema.enum) + throw new Error('Missing enum. To use `transform:["toEnumCase"]`, `enum:[...]` is required.'); + for (var i = parentSchema.enum.length; i--; i) { + var v = parentSchema.enum[i]; + if (typeof v !== 'string') continue; + var k = makeHashTableKey(v); + // requires all `enum` values have unique keys + if (cfg.hash[k]) + throw new Error('Invalid enum uniqueness. To use `transform:["toEnumCase"]`, all values must be unique when case insensitive.'); + cfg.hash[k] = v; + } + } + + return function (data, dataPath, object, key) { + // skip if value only + if (!object) return; + + // apply transform in order provided + for (var j = 0, l = schema.length; j < l; j++) + data = transform[schema[j]](data, cfg); + + object[key] = data; + }; + }, + metaSchema: { + type: 'array', + items: { + type: 'string', + enum: [ + 'trimLeft', 'trimRight', 'trim', + 'toLowerCase', 'toUpperCase', 'toEnumCase' + ] + } + } + }; + + ajv.addKeyword('transform', defFunc.definition); + return ajv; + + function makeHashTableKey (value) { + return value.toLowerCase(); + } +}; + + +/***/ }), + +/***/ 22608: +/***/ ((module) => { + +"use strict"; + + +var KNOWN_TYPES = ['undefined', 'string', 'number', 'object', 'function', 'boolean', 'symbol']; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + inline: function (it, keyword, schema) { + var data = 'data' + (it.dataLevel || ''); + if (typeof schema == 'string') return 'typeof ' + data + ' == "' + schema + '"'; + schema = 'validate.schema' + it.schemaPath + '.' + keyword; + return schema + '.indexOf(typeof ' + data + ') >= 0'; + }, + metaSchema: { + anyOf: [ + { + type: 'string', + enum: KNOWN_TYPES + }, + { + type: 'array', + items: { + type: 'string', + enum: KNOWN_TYPES + } + } + ] + } + }; + + ajv.addKeyword('typeof', defFunc.definition); + return ajv; +}; + + +/***/ }), + +/***/ 43786: +/***/ ((module) => { + +"use strict"; + + +var SCALAR_TYPES = ['number', 'integer', 'string', 'boolean', 'null']; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'array', + compile: function(keys, parentSchema, it) { + var equal = it.util.equal; + var scalar = getScalarKeys(keys, parentSchema); + + return function(data) { + if (data.length > 1) { + for (var k=0; k < keys.length; k++) { + var i, key = keys[k]; + if (scalar[k]) { + var hash = {}; + for (i = data.length; i--;) { + if (!data[i] || typeof data[i] != 'object') continue; + var prop = data[i][key]; + if (prop && typeof prop == 'object') continue; + if (typeof prop == 'string') prop = '"' + prop; + if (hash[prop]) return false; + hash[prop] = true; + } + } else { + for (i = data.length; i--;) { + if (!data[i] || typeof data[i] != 'object') continue; + for (var j = i; j--;) { + if (data[j] && typeof data[j] == 'object' && equal(data[i][key], data[j][key])) + return false; + } + } + } + } + } + return true; + }; + }, + metaSchema: { + type: 'array', + items: {type: 'string'} + } + }; + + ajv.addKeyword('uniqueItemProperties', defFunc.definition); + return ajv; +}; + + +function getScalarKeys(keys, schema) { + return keys.map(function(key) { + var properties = schema.items && schema.items.properties; + var propType = properties && properties[key] && properties[key].type; + return Array.isArray(propType) + ? propType.indexOf('object') < 0 && propType.indexOf('array') < 0 + : SCALAR_TYPES.indexOf(propType) >= 0; + }); +} + + +/***/ }), + +/***/ 21414: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var compileSchema = __webpack_require__(51645) + , resolve = __webpack_require__(62630) + , Cache = __webpack_require__(67246) + , SchemaObject = __webpack_require__(27837) + , stableStringify = __webpack_require__(73600) + , formats = __webpack_require__(49290) + , rules = __webpack_require__(91665) + , $dataMetaSchema = __webpack_require__(56989) + , util = __webpack_require__(16057); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = __webpack_require__(40075); +var customKeyword = __webpack_require__(58093); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = __webpack_require__(42718); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i { + +"use strict"; + + + +var Cache = module.exports = function Cache() { + this._cache = {}; +}; + + +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; + + +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; + + +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; + + +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; + + +/***/ }), + +/***/ 40075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var MissingRefError = __webpack_require__(42718).MissingRef; + +module.exports = compileAsync; + + +/** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. + */ +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + /* global Promise */ + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') + throw new Error('options.loadSchema should be a function'); + + if (typeof meta == 'function') { + callback = meta; + meta = undefined; + } + + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); + }); + + if (callback) { + p.then( + function(v) { callback(null, v); }, + callback + ); + } + + return p; + + + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) + ? compileAsync.call(self, { $ref: $schema }, true) + : Promise.resolve(); + } + + + function _compileAsync(schemaObj) { + try { return self._compile(schemaObj); } + catch(e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } + + + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); + + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } + + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); + } + }).then(function() { + return _compileAsync(schemaObj); + }); + + function removePromise() { + delete self._loadingSchemas[ref]; + } + + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } + } + } +} + + +/***/ }), + +/***/ 42718: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var resolve = __webpack_require__(62630); + +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) +}; + + +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} + + +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; + + +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} + + +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} + + +/***/ }), + +/***/ 49290: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(16057); + +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +// uri-template: https://tools.ietf.org/html/rfc6570 +var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + + +/***/ }), + +/***/ 51645: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var resolve = __webpack_require__(62630) + , util = __webpack_require__(16057) + , errorClasses = __webpack_require__(42718) + , stableStringify = __webpack_require__(73600); + +var validateGenerator = __webpack_require__(26131); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = __webpack_require__(63933); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i { + +"use strict"; + + +var URI = __webpack_require__(94007) + , equal = __webpack_require__(63933) + , util = __webpack_require__(16057) + , SchemaObject = __webpack_require__(27837) + , traverse = __webpack_require__(62437); + +module.exports = resolve; + +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; + +/** + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function + */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal]; + else return resolve.call(this, compile, root, refVal); + } + + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); + } + + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } + + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) + ? schema + : compile.call(this, schema, root, undefined, baseId); + } + + return v; +} + + +/** + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = URI.parse(ref) + , refPath = _getFullPath(p) + , baseId = getFullPath(this._getId(root.schema)); + if (Object.keys(root.schema).length === 0 || refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) + return { schema: refVal, root: root, baseId: baseId }; + root = refVal; + } else { + return; + } + } + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); + } + return getJsonPointer.call(this, p, baseId, root.schema, root); +} + + +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + var id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} + + +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.fragment = parsedRef.fragment || ''; + if (parsedRef.fragment.slice(0,1) != '/') return; + var parts = parsedRef.fragment.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } + } + } + } + } + if (schema !== undefined && schema !== root.schema) + return { schema: schema, root: root, baseId: baseId }; +} + + +var SIMPLE_INLINED = util.toHash([ + 'type', 'format', 'pattern', + 'maxLength', 'minLength', + 'maxProperties', 'minProperties', + 'maxItems', 'minItems', + 'maximum', 'minimum', + 'uniqueItems', 'multipleOf', + 'required', 'enum' +]); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema); + else if (limit) return countKeys(schema) <= limit; +} + + +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i { + +"use strict"; + + +var ruleModules = __webpack_require__(24124) + , toHash = __webpack_require__(16057).toHash; + +module.exports = function rules() { + var RULES = [ + { type: 'number', + rules: [ { 'maximum': ['exclusiveMaximum'] }, + { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, + { type: 'string', + rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, + { type: 'array', + rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, + { type: 'object', + rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', + { 'properties': ['additionalProperties', 'patternProperties'] } ] }, + { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } + ]; + + var ALL = [ 'type', '$comment' ]; + var KEYWORDS = [ + '$schema', '$id', 'id', '$data', '$async', 'title', + 'description', 'default', 'definitions', + 'examples', 'readOnly', 'writeOnly', + 'contentMediaType', 'contentEncoding', + 'additionalItems', 'then', 'else' + ]; + var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); + + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + if (typeof keyword == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; + }); + } + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + implements: implKeywords + }; + return rule; + }); + + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; + + if (group.type) RULES.types[group.type] = group; + }); + + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; + + return RULES; +}; + + +/***/ }), + +/***/ 27837: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(16057); + +module.exports = SchemaObject; + +function SchemaObject(obj) { + util.copy(obj, this); +} + + +/***/ }), + +/***/ 19652: +/***/ ((module) => { + +"use strict"; + + +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +module.exports = function ucs2length(str) { + var length = 0 + , len = str.length + , pos = 0 + , value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; + + +/***/ }), + +/***/ 16057: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: __webpack_require__(63933), + ucs2length: __webpack_require__(19652), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i { + +"use strict"; + + +var KEYWORDS = [ + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'maxProperties', + 'minProperties', + 'required', + 'additionalProperties', + 'enum', + 'format', + 'const' +]; + +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i=0; i { + +"use strict"; + + +var metaSchema = __webpack_require__(98938); + +module.exports = { + $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: {not: {required: ['macro']}} + }, + properties: { + type: metaSchema.properties.type, + schema: {type: 'boolean'}, + statements: {type: 'boolean'}, + dependencies: { + type: 'array', + items: {type: 'string'} + }, + metaSchema: {type: 'object'}, + modifying: {type: 'boolean'}, + valid: {type: 'boolean'}, + $data: {type: 'boolean'}, + async: {type: 'boolean'}, + errors: { + anyOf: [ + {type: 'boolean'}, + {const: 'full'} + ] + } + } +}; + + +/***/ }), + +/***/ 93711: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 45675: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 6051: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 17043: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 73639: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} + + +/***/ }), + +/***/ 71256: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + + +/***/ }), + +/***/ 12660: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} + + +/***/ }), + +/***/ 10184: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 27419: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + + +/***/ }), + +/***/ 87921: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { + +"use strict"; + +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + ($errs) + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + ($lvl) + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + if ($deps.length) { + out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var $propertyKey, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $propertyKey, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + + +/***/ }), + +/***/ 89795: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 85801: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 64962: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + + +/***/ }), + +/***/ 24124: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': __webpack_require__(95746), + allOf: __webpack_require__(73639), + anyOf: __webpack_require__(71256), + '$comment': __webpack_require__(12660), + const: __webpack_require__(10184), + contains: __webpack_require__(27419), + dependencies: __webpack_require__(77299), + 'enum': __webpack_require__(89795), + format: __webpack_require__(85801), + 'if': __webpack_require__(64962), + items: __webpack_require__(49623), + maximum: __webpack_require__(93711), + minimum: __webpack_require__(93711), + maxItems: __webpack_require__(45675), + minItems: __webpack_require__(45675), + maxLength: __webpack_require__(6051), + minLength: __webpack_require__(6051), + maxProperties: __webpack_require__(17043), + minProperties: __webpack_require__(17043), + multipleOf: __webpack_require__(99251), + not: __webpack_require__(67739), + oneOf: __webpack_require__(26857), + pattern: __webpack_require__(28099), + properties: __webpack_require__(59438), + propertyNames: __webpack_require__(53466), + required: __webpack_require__(88430), + uniqueItems: __webpack_require__(12207), + validate: __webpack_require__(26131) +}; + + +/***/ }), + +/***/ 49623: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + + +/***/ }), + +/***/ 99251: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 67739: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} + + +/***/ }), + +/***/ 26857: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + + +/***/ }), + +/***/ 28099: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), + +/***/ 59438: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + + +/***/ }), + +/***/ 53466: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { + +"use strict"; + +module.exports = function generate_ref(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = it.MissingRefError.message(it.baseId, $schema); + if (it.opts.missingRefs == 'fail') { + it.logger.error($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; + } + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + it.logger.warn($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + throw new it.MissingRefError(it.baseId, $schema, $message); + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + } + } else { + $async = $refVal.$async === true || (it.async && $refVal.$async !== false); + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + if ($breakOnError) { + out += ' var ' + ($valid) + '; '; + } + out += ' try { await ' + (__callValidate) + '; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = true; '; + } + out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = false; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} + + +/***/ }), + +/***/ 88430: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_required(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} + + +/***/ }), + +/***/ 12207: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + + +/***/ }), + +/***/ 26131: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} + + +/***/ }), + +/***/ 58093: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = __webpack_require__(87921); +var definitionSchema = __webpack_require__(55533); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i { + +"use strict"; +/*! + * arr-diff + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function diff(arr/*, arrays*/) { + var len = arguments.length; + var idx = 0; + while (++idx < len) { + arr = diffArray(arr, arguments[idx]); + } + return arr; +}; + +function diffArray(one, two) { + if (!Array.isArray(two)) { + return one.slice(); + } + + var tlen = two.length + var olen = one.length; + var idx = -1; + var arr = []; + + while (++idx < olen) { + var ele = one[idx]; + + var hasEle = false; + for (var i = 0; i < tlen; i++) { + var val = two[i]; + + if (ele === val) { + hasEle = true; + break; + } + } + + if (hasEle === false) { + arr.push(ele); + } + } + return arr; +} + + +/***/ }), + +/***/ 27299: +/***/ ((module) => { + +"use strict"; +/*! + * arr-flatten + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function (arr) { + return flat(arr, []); +}; + +function flat(arr, res) { + var i = 0, cur; + var len = arr.length; + for (; i < len; i++) { + cur = arr[i]; + Array.isArray(cur) ? flat(cur, res) : res.push(cur); + } + return res; +} + + +/***/ }), + +/***/ 69123: +/***/ ((module) => { + +"use strict"; + + +module.exports = function union(init) { + if (!Array.isArray(init)) { + throw new TypeError('arr-union expects the first argument to be an array.'); + } + + var len = arguments.length; + var i = 0; + + while (++i < len) { + var arg = arguments[i]; + if (!arg) continue; + + if (!Array.isArray(arg)) { + arg = [arg]; + } + + for (var j = 0; j < arg.length; j++) { + var ele = arg[j]; + + if (init.indexOf(ele) >= 0) { + continue; + } + init.push(ele); + } + } + return init; +}; + + +/***/ }), + +/***/ 19009: +/***/ ((module) => { + +"use strict"; +/*! + * array-unique + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function unique(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } + + var len = arr.length; + var i = -1; + + while (i++ < len) { + var j = i + 1; + + for (; j < arr.length; ++j) { + if (arr[i] === arr[j]) { + arr.splice(j--, 1); + } + } + } + return arr; +}; + +module.exports.immutable = function uniqueImmutable(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } + + var arrLen = arr.length; + var newArr = new Array(arrLen); + + for (var i = 0; i < arrLen; i++) { + newArr[i] = arr[i]; + } + + return module.exports(newArr); +}; + + +/***/ }), + +/***/ 64353: +/***/ ((module) => { + +"use strict"; +/*! + * assign-symbols + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function(receiver, objects) { + if (receiver === null || typeof receiver === 'undefined') { + throw new TypeError('expected first argument to be an object.'); + } + + if (typeof objects === 'undefined' || typeof Symbol === 'undefined') { + return receiver; + } + + if (typeof Object.getOwnPropertySymbols !== 'function') { + return receiver; + } + + var isEnumerable = Object.prototype.propertyIsEnumerable; + var target = Object(receiver); + var len = arguments.length, i = 0; + + while (++i < len) { + var provider = Object(arguments[i]); + var names = Object.getOwnPropertySymbols(provider); + + for (var j = 0; j < names.length; j++) { + var key = names[j]; + + if (isEnumerable.call(provider, key)) { + target[key] = provider[key]; + } + } + } + return target; +}; + + +/***/ }), + +/***/ 83327: +/***/ ((module) => { + +"use strict"; + + +function atob(str) { + return Buffer.from(str, 'base64').toString('binary'); +} + +module.exports = atob.atob = atob; + + +/***/ }), + +/***/ 87263: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(31669); +var define = __webpack_require__(90563); +var CacheBase = __webpack_require__(63375); +var Emitter = __webpack_require__(79458); +var isObject = __webpack_require__(96667); +var merge = __webpack_require__(4870); +var pascal = __webpack_require__(27255); +var cu = __webpack_require__(71523); + +/** + * Optionally define a custom `cache` namespace to use. + */ + +function namespace(name) { + var Cache = name ? CacheBase.namespace(name) : CacheBase; + var fns = []; + + /** + * Create an instance of `Base` with the given `config` and `options`. + * + * ```js + * // initialize with `config` and `options` + * var app = new Base({isApp: true}, {abc: true}); + * app.set('foo', 'bar'); + * + * // values defined with the given `config` object will be on the root of the instance + * console.log(app.baz); //=> undefined + * console.log(app.foo); //=> 'bar' + * // or use `.get` + * console.log(app.get('isApp')); //=> true + * console.log(app.get('foo')); //=> 'bar' + * + * // values defined with the given `options` object will be on `app.options + * console.log(app.options.abc); //=> true + * ``` + * + * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation. + * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object. + * @api public + */ + + function Base(config, options) { + if (!(this instanceof Base)) { + return new Base(config, options); + } + Cache.call(this, config); + this.is('base'); + this.initBase(config, options); + } + + /** + * Inherit cache-base + */ + + util.inherits(Base, Cache); + + /** + * Add static emitter methods + */ + + Emitter(Base); + + /** + * Initialize `Base` defaults with the given `config` object + */ + + Base.prototype.initBase = function(config, options) { + this.options = merge({}, this.options, options); + this.cache = this.cache || {}; + this.define('registered', {}); + if (name) this[name] = {}; + + // make `app._callbacks` non-enumerable + this.define('_callbacks', this._callbacks); + if (isObject(config)) { + this.visit('set', config); + } + Base.run(this, 'use', fns); + }; + + /** + * Set the given `name` on `app._name` and `app.is*` properties. Used for doing + * lookups in plugins. + * + * ```js + * app.is('foo'); + * console.log(app._name); + * //=> 'foo' + * console.log(app.isFoo); + * //=> true + * app.is('bar'); + * console.log(app.isFoo); + * //=> true + * console.log(app.isBar); + * //=> true + * console.log(app._name); + * //=> 'bar' + * ``` + * @name .is + * @param {String} `name` + * @return {Boolean} + * @api public + */ + + Base.prototype.is = function(name) { + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string'); + } + this.define('is' + pascal(name), true); + this.define('_name', name); + this.define('_appname', name); + return this; + }; + + /** + * Returns true if a plugin has already been registered on an instance. + * + * Plugin implementors are encouraged to use this first thing in a plugin + * to prevent the plugin from being called more than once on the same + * instance. + * + * ```js + * var base = new Base(); + * base.use(function(app) { + * if (app.isRegistered('myPlugin')) return; + * // do stuff to `app` + * }); + * + * // to also record the plugin as being registered + * base.use(function(app) { + * if (app.isRegistered('myPlugin', true)) return; + * // do stuff to `app` + * }); + * ``` + * @name .isRegistered + * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once. + * @param {String} `name` The plugin name. + * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument. + * @return {Boolean} Returns true if a plugin is already registered. + * @api public + */ + + Base.prototype.isRegistered = function(name, register) { + if (this.registered.hasOwnProperty(name)) { + return true; + } + if (register !== false) { + this.registered[name] = true; + this.emit('plugin', name); + } + return false; + }; + + /** + * Define a plugin function to be called immediately upon init. Plugins are chainable + * and expose the following arguments to the plugin function: + * + * - `app`: the current instance of `Base` + * - `base`: the [first ancestor instance](#base) of `Base` + * + * ```js + * var app = new Base() + * .use(foo) + * .use(bar) + * .use(baz) + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @return {Object} Returns the item instance for chaining. + * @api public + */ + + Base.prototype.use = function(fn) { + fn.call(this, this); + return this; + }; + + /** + * The `.define` method is used for adding non-enumerable property on the instance. + * Dot-notation is **not supported** with `define`. + * + * ```js + * // arbitrary `render` function using lodash `template` + * app.define('render', function(str, locals) { + * return _.template(str)(locals); + * }); + * ``` + * @name .define + * @param {String} `key` The name of the property to define. + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Base.prototype.define = function(key, val) { + if (isObject(key)) { + return this.visit('define', key); + } + define(this, key, val); + return this; + }; + + /** + * Mix property `key` onto the Base prototype. If base is inherited using + * `Base.extend` this method will be overridden by a new `mixin` method that will + * only add properties to the prototype of the inheriting application. + * + * ```js + * app.mixin('foo', function() { + * // do stuff + * }); + * ``` + * @name .mixin + * @param {String} `key` + * @param {Object|Array} `val` + * @return {Object} Returns the `base` instance for chaining. + * @api public + */ + + Base.prototype.mixin = function(key, val) { + Base.prototype[key] = val; + return this; + }; + + /** + * Non-enumberable mixin array, used by the static [Base.mixin]() method. + */ + + Base.prototype.mixins = Base.prototype.mixins || []; + + /** + * Getter/setter used when creating nested instances of `Base`, for storing a reference + * to the first ancestor instance. This works by setting an instance of `Base` on the `parent` + * property of a "child" instance. The `base` property defaults to the current instance if + * no `parent` property is defined. + * + * ```js + * // create an instance of `Base`, this is our first ("base") instance + * var first = new Base(); + * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later + * + * // create another instance + * var second = new Base(); + * // create a reference to the first instance (`first`) + * second.parent = first; + * + * // create another instance + * var third = new Base(); + * // create a reference to the previous instance (`second`) + * // repeat this pattern every time a "child" instance is created + * third.parent = second; + * + * // we can always access the first instance using the `base` property + * console.log(first.base.foo); + * //=> 'bar' + * console.log(second.base.foo); + * //=> 'bar' + * console.log(third.base.foo); + * //=> 'bar' + * // and now you know how to get to third base ;) + * ``` + * @name .base + * @api public + */ + + Object.defineProperty(Base.prototype, 'base', { + configurable: true, + get: function() { + return this.parent ? this.parent.base : this; + } + }); + + /** + * Static method for adding global plugin functions that will + * be added to an instance when created. + * + * ```js + * Base.use(function(app) { + * app.foo = 'bar'; + * }); + * var app = new Base(); + * console.log(app.foo); + * //=> 'bar' + * ``` + * @name #use + * @param {Function} `fn` Plugin function to use on each instance. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'use', function(fn) { + fns.push(fn); + return Base; + }); + + /** + * Run an array of functions by passing each function + * to a method on the given object specified by the given property. + * + * @param {Object} `obj` Object containing method to use. + * @param {String} `prop` Name of the method on the object to use. + * @param {Array} `arr` Array of functions to pass to the method. + */ + + define(Base, 'run', function(obj, prop, arr) { + var len = arr.length, i = 0; + while (len--) { + obj[prop](arr[i++]); + } + return Base; + }); + + /** + * Static method for inheriting the prototype and static methods of the `Base` class. + * This method greatly simplifies the process of creating inheritance-based applications. + * See [static-extend][] for more details. + * + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @name #extend + * @param {Function} `Ctor` constructor to extend + * @param {Object} `methods` Optional prototype properties to mix in. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) { + Ctor.prototype.mixins = Ctor.prototype.mixins || []; + + define(Ctor, 'mixin', function(fn) { + var mixin = fn(Ctor.prototype, Ctor); + if (typeof mixin === 'function') { + Ctor.prototype.mixins.push(mixin); + } + return Ctor; + }); + + define(Ctor, 'mixins', function(Child) { + Base.run(Child, 'mixin', Ctor.prototype.mixins); + return Ctor; + }); + + Ctor.prototype.mixin = function(key, value) { + Ctor.prototype[key] = value; + return this; + }; + return Base; + })); + + /** + * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances. + * When a mixin function returns a function, the returned function is pushed onto the `.mixins` + * array, making it available to be used on inheriting classes whenever `Base.mixins()` is + * called (e.g. `Base.mixins(Child)`). + * + * ```js + * Base.mixin(function(proto) { + * proto.foo = function(msg) { + * return 'foo ' + msg; + * }; + * }); + * ``` + * @name #mixin + * @param {Function} `fn` Function to call + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'mixin', function(fn) { + var mixin = fn(Base.prototype, Base); + if (typeof mixin === 'function') { + Base.prototype.mixins.push(mixin); + } + return Base; + }); + + /** + * Static method for running global mixin functions against a child constructor. + * Mixins must be registered before calling this method. + * + * ```js + * Base.extend(Child); + * Base.mixins(Child); + * ``` + * @name #mixins + * @param {Function} `Child` Constructor function of a child class + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'mixins', function(Child) { + Base.run(Child, 'mixin', Base.prototype.mixins); + return Base; + }); + + /** + * Similar to `util.inherit`, but copies all static properties, prototype properties, and + * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details. + * + * ```js + * Base.inherit(Foo, Bar); + * ``` + * @name #inherit + * @param {Function} `Receiver` Receiving (child) constructor + * @param {Function} `Provider` Providing (parent) constructor + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'inherit', cu.inherit); + define(Base, 'bubble', cu.bubble); + return Base; +} + +/** + * Expose `Base` with default settings + */ + +module.exports = namespace(); + +/** + * Allow users to define a namespace + */ + +module.exports.namespace = namespace; + + +/***/ }), + +/***/ 90563: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(44133); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), + +/***/ 22706: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +var toRegex = __webpack_require__(51279); +var unique = __webpack_require__(19009); +var extend = __webpack_require__(28727); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(46109); +var parsers = __webpack_require__(49665); +var Braces = __webpack_require__(68297); +var utils = __webpack_require__(68130); +var MAX_LENGTH = 1024 * 64; +var cache = {}; + +/** + * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)). + * + * ```js + * var braces = require('braces'); + * console.log(braces('{a,b,c}')); + * //=> ['(a|b|c)'] + * + * console.log(braces('{a,b,c}', {expand: true})); + * //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +function braces(pattern, options) { + var key = utils.createKey(String(pattern), options); + var arr = []; + + var disabled = options && options.cache === false; + if (!disabled && cache.hasOwnProperty(key)) { + return cache[key]; + } + + if (Array.isArray(pattern)) { + for (var i = 0; i < pattern.length; i++) { + arr.push.apply(arr, braces.create(pattern[i], options)); + } + } else { + arr = braces.create(pattern, options); + } + + if (options && options.nodupes === true) { + arr = unique(arr); + } + + if (!disabled) { + cache[key] = arr; + } + return arr; +} + +/** + * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = function(pattern, options) { + return braces.create(pattern, extend({}, options, {expand: true})); +}; + +/** + * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.optimize = function(pattern, options) { + return braces.create(pattern, options); +}; + +/** + * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function. + * + * ```js + * var braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); + } + + function create() { + if (pattern === '' || pattern.length < 3) { + return [pattern]; + } + + if (utils.isEmptySets(pattern)) { + return []; + } + + if (utils.isQuotedString(pattern)) { + return [pattern.slice(1, -1)]; + } + + var proto = new Braces(options); + var result = !options || options.expand !== true + ? proto.optimize(pattern, options) + : proto.expand(pattern, options); + + // get the generated pattern(s) + var arr = result.output; + + // filter out empty strings if specified + if (options && options.noempty === true) { + arr = arr.filter(Boolean); + } + + // filter out duplicates if specified + if (options && options.nodupes === true) { + arr = unique(arr); + } + + Object.defineProperty(arr, 'result', { + enumerable: false, + value: result + }); + + return arr; + } + + return memoize('create', pattern, options, create); +}; + +/** + * Create a regular expression from the given string `pattern`. + * + * ```js + * var braces = require('braces'); + * + * console.log(braces.makeRe('id-{200..300}')); + * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +braces.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); + } + + function makeRe() { + var arr = braces(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(arr, opts); + } + + return memoize('makeRe', pattern, options, makeRe); +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `pattern` Brace pattern to parse + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = function(pattern, options) { + var proto = new Braces(options); + return proto.parse(pattern, options); +}; + +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(braces.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first. + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ + +braces.compile = function(ast, options) { + var proto = new Braces(options); + return proto.compile(ast, options); +}; + +/** + * Clear the regex cache. + * + * ```js + * braces.clearCache(); + * ``` + * @api public + */ + +braces.clearCache = function() { + cache = braces.cache = {}; +}; + +/** + * Memoize a generated regex or function. A unique key is generated + * from the method name, pattern, and user-defined options. Set + * options.memoize to false to disable. + */ + +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + ':' + pattern, options); + var disabled = options && options.cache === false; + if (disabled) { + braces.clearCache(); + return fn(pattern, options); + } + + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + + var res = fn(pattern, options); + cache[key] = res; + return res; +} + +/** + * Expose `Braces` constructor and methods + * @type {Function} + */ + +braces.Braces = Braces; +braces.compilers = compilers; +braces.parsers = parsers; +braces.cache = cache; + +/** + * Expose `braces` + * @type {Function} + */ + +module.exports = braces; + + +/***/ }), + +/***/ 68297: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var extend = __webpack_require__(28727); +var Snapdragon = __webpack_require__(79285); +var compilers = __webpack_require__(46109); +var parsers = __webpack_require__(49665); +var utils = __webpack_require__(68130); + +/** + * Customize Snapdragon parser and renderer + */ + +function Braces(options) { + this.options = extend({}, options); +} + +/** + * Initialize braces + */ + +Braces.prototype.init = function(options) { + if (this.isInitialized) return; + this.isInitialized = true; + var opts = utils.createOptions({}, this.options, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(opts); + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; + + compilers(this.snapdragon, opts); + parsers(this.snapdragon, opts); + + /** + * Call Snapdragon `.parse` method. When AST is returned, we check to + * see if any unclosed braces are left on the stack and, if so, we iterate + * over the stack and correct the AST so that compilers are called in the correct + * order and unbalance braces are properly escaped. + */ + + utils.define(this.snapdragon, 'parse', function(pattern, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + this.parser.ast.input = pattern; + + var stack = this.parser.stack; + while (stack.length) { + addParent({type: 'brace.close', val: ''}, stack.pop()); + } + + function addParent(node, parent) { + utils.define(node, 'parent', parent); + parent.nodes.push(node); + } + + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); +}; + +/** + * Decorate `.parse` method + */ + +Braces.prototype.parse = function(ast, options) { + if (ast && typeof ast === 'object' && ast.nodes) return ast; + this.init(options); + return this.snapdragon.parse(ast, options); +}; + +/** + * Decorate `.compile` method + */ + +Braces.prototype.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = this.parse(ast, options); + } else { + this.init(options); + } + return this.snapdragon.compile(ast, options); +}; + +/** + * Expand + */ + +Braces.prototype.expand = function(pattern) { + var ast = this.parse(pattern, {expand: true}); + return this.compile(ast, {expand: true}); +}; + +/** + * Optimize + */ + +Braces.prototype.optimize = function(pattern) { + var ast = this.parse(pattern, {optimize: true}); + return this.compile(ast, {optimize: true}); +}; + +/** + * Expose `Braces` + */ + +module.exports = Braces; + + +/***/ }), + +/***/ 46109: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(68130); + +module.exports = function(braces, options) { + braces.compiler + + /** + * bos + */ + + .set('bos', function() { + if (this.output) return; + this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; + this.ast.count = 1; + }) + + /** + * Square brackets + */ + + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + + inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); + if (inner === ']-') { + inner = '\\]\\-'; + } + + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } + + var val = open + negated + inner + close; + var queue = node.parent.queue; + var last = utils.arrayify(queue.pop()); + + queue.push(utils.join(last, val)); + queue.push.apply(queue, []); + }) + + /** + * Brace + */ + + .set('brace', function(node) { + node.queue = isEscaped(node) ? [node.val] : []; + node.count = 1; + return this.mapVisit(node.nodes); + }) + + /** + * Open + */ + + .set('brace.open', function(node) { + node.parent.open = node.val; + }) + + /** + * Inner + */ + + .set('text', function(node) { + var queue = node.parent.queue; + var escaped = node.escaped; + var segs = [node.val]; + + if (node.optimize === false) { + options = utils.extend({}, options, {optimize: false}); + } + + if (node.multiplier > 1) { + node.parent.count *= node.multiplier; + } + + if (options.quantifiers === true && utils.isQuantifier(node.val)) { + escaped = true; + + } else if (node.val.length > 1) { + if (isType(node.parent, 'brace') && !isEscaped(node)) { + var expanded = utils.expand(node.val, options); + segs = expanded.segs; + + if (expanded.isOptimized) { + node.parent.isOptimized = true; + } + + // if nothing was expanded, we probably have a literal brace + if (!segs.length) { + var val = (expanded.val || node.val); + if (options.unescape !== false) { + // unescape unexpanded brace sequence/set separators + val = val.replace(/\\([,.])/g, '$1'); + // strip quotes + val = val.replace(/["'`]/g, ''); + } + + segs = [val]; + escaped = true; + } + } + + } else if (node.val === ',') { + if (options.expand) { + node.parent.queue.push(['']); + segs = ['']; + } else { + segs = ['|']; + } + } else { + escaped = true; + } + + if (escaped && isType(node.parent, 'brace')) { + if (node.parent.nodes.length <= 4 && node.parent.count === 1) { + node.parent.escaped = true; + } else if (node.parent.length <= 3) { + node.parent.escaped = true; + } + } + + if (!hasQueue(node.parent)) { + node.parent.queue = segs; + return; + } + + var last = utils.arrayify(queue.pop()); + if (node.parent.count > 1 && options.expand) { + last = multiply(last, node.parent.count); + node.parent.count = 1; + } + + queue.push(utils.join(utils.flatten(last), segs.shift())); + queue.push.apply(queue, segs); + }) + + /** + * Close + */ + + .set('brace.close', function(node) { + var queue = node.parent.queue; + var prev = node.parent.parent; + var last = prev.queue.pop(); + var open = node.parent.open; + var close = node.val; + + if (open && close && isOptimized(node, options)) { + open = '('; + close = ')'; + } + + // if a close brace exists, and the previous segment is one character + // don't wrap the result in braces or parens + var ele = utils.last(queue); + if (node.parent.count > 1 && options.expand) { + ele = multiply(queue.pop(), node.parent.count); + node.parent.count = 1; + queue.push(ele); + } + + if (close && typeof ele === 'string' && ele.length === 1) { + open = ''; + close = ''; + } + + if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) { + queue.push(utils.join(open, queue.pop() || '')); + queue = utils.flatten(utils.join(queue, close)); + } + + if (typeof last === 'undefined') { + prev.queue = [queue]; + } else { + prev.queue.push(utils.flatten(utils.join(last, queue))); + } + }) + + /** + * eos + */ + + .set('eos', function(node) { + if (this.input) return; + + if (options.optimize !== false) { + this.output = utils.last(utils.flatten(this.ast.queue)); + } else if (Array.isArray(utils.last(this.ast.queue))) { + this.output = utils.flatten(this.ast.queue.pop()); + } else { + this.output = utils.flatten(this.ast.queue); + } + + if (node.parent.count > 1 && options.expand) { + this.output = multiply(this.output, node.parent.count); + } + + this.output = utils.arrayify(this.output); + this.ast.queue = []; + }); + +}; + +/** + * Multiply the segments in the current brace level + */ + +function multiply(queue, n, options) { + return utils.flatten(utils.repeat(utils.arrayify(queue), n)); +} + +/** + * Return true if `node` is escaped + */ + +function isEscaped(node) { + return node.escaped === true; +} + +/** + * Returns true if regex parens should be used for sets. If the parent `type` + * is not `brace`, then we're on a root node, which means we should never + * expand segments and open/close braces should be `{}` (since this indicates + * a brace is missing from the set) + */ + +function isOptimized(node, options) { + if (node.parent.isOptimized) return true; + return isType(node.parent, 'brace') + && !isEscaped(node.parent) + && options.expand !== true; +} + +/** + * Returns true if the value in `node` should be wrapped in a literal brace. + * @return {Boolean} + */ + +function isLiteralBrace(node, options) { + return isEscaped(node.parent) || options.optimize !== false; +} + +/** + * Returns true if the given `node` does not have an inner value. + * @return {Boolean} + */ + +function noInner(node, type) { + if (node.parent.queue.length === 1) { + return true; + } + var nodes = node.parent.nodes; + return nodes.length === 3 + && isType(nodes[0], 'brace.open') + && !isType(nodes[1], 'text') + && isType(nodes[2], 'brace.close'); +} + +/** + * Returns true if the given `node` is the given `type` + * @return {Boolean} + */ + +function isType(node, type) { + return typeof node !== 'undefined' && node.type === type; +} + +/** + * Returns true if the given `node` has a non-empty queue. + * @return {Boolean} + */ + +function hasQueue(node) { + return Array.isArray(node.queue) && node.queue.length; +} + + +/***/ }), + +/***/ 49665: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Node = __webpack_require__(12579); +var utils = __webpack_require__(68130); + +/** + * Braces parsers + */ + +module.exports = function(braces, options) { + braces.parser + .set('bos', function() { + if (!this.parsed) { + this.ast = this.nodes[0] = new Node(this.ast); + } + }) + + /** + * Character parsers + */ + + .set('escape', function() { + var pos = this.position(); + var m = this.match(/^(?:\\(.)|\$\{)/); + if (!m) return; + + var prev = this.prev(); + var last = utils.last(prev.nodes); + + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: m[0] + })); + + if (node.val === '\\\\') { + return node; + } + + if (node.val === '${') { + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + node.val += ch; + if (ch === '\\') { + node.val += str[++idx]; + continue; + } + if (ch === '}') { + break; + } + } + } + + if (this.options.unescape !== false) { + node.val = node.val.replace(/\\([{}])/g, '$1'); + } + + if (last.val === '"' && this.input.charAt(0) === '"') { + last.val = node.val; + this.consume(1); + return; + } + + return concatNodes.call(this, pos, node, prev, options); + }) + + /** + * Brackets: "[...]" (basic, this is overridden by + * other parsers in more advanced implementations) + */ + + .set('bracket', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; + + var prev = this.prev(); + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = m[2] || ''; + var close = m[3] || ''; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } + + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); + + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } + + return pos(new Node({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + })); + }) + + /** + * Empty braces (we capture these early to + * speed up processing in the compiler) + */ + + .set('multiplier', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{((?:,|\{,+\})+)\}/); + if (!m) return; + + this.multiplier = true; + var prev = this.prev(); + var val = m[0]; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } + + var node = pos(new Node({ + type: 'text', + multiplier: 1, + match: m, + val: val + })); + + return concatNodes.call(this, pos, node, prev, options); + }) + + /** + * Open + */ + + .set('brace.open', function() { + var pos = this.position(); + var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); + if (!m) return; + + var prev = this.prev(); + var last = utils.last(prev.nodes); + + // if the last parsed character was an extglob character + // we need to _not optimize_ the brace pattern because + // it might be mistaken for an extglob by a downstream parser + if (last && last.val && isExtglobChar(last.val.slice(-1))) { + last.optimize = false; + } + + var open = pos(new Node({ + type: 'brace.open', + val: m[0] + })); + + var node = pos(new Node({ + type: 'brace', + nodes: [] + })); + + node.push(open); + prev.push(node); + this.push('brace', node); + }) + + /** + * Close + */ + + .set('brace.close', function() { + var pos = this.position(); + var m = this.match(/^\}/); + if (!m || !m[0]) return; + + var brace = this.pop('brace'); + var node = pos(new Node({ + type: 'brace.close', + val: m[0] + })); + + if (!this.isType(brace, 'brace')) { + if (this.options.strict) { + throw new Error('missing opening "{"'); + } + node.type = 'text'; + node.multiplier = 0; + node.escaped = true; + return node; + } + + var prev = this.prev(); + var last = utils.last(prev.nodes); + if (last.text) { + var lastNode = utils.last(last.nodes); + if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) { + var open = last.nodes[0]; + var text = last.nodes[1]; + if (open.type === 'brace.open' && text && text.type === 'text') { + text.optimize = false; + } + } + } + + if (brace.nodes.length > 2) { + var first = brace.nodes[1]; + if (first.type === 'text' && first.val === ',') { + brace.nodes.splice(1, 1); + brace.nodes.push(first); + } + } + + brace.push(node); + }) + + /** + * Capture boundary characters + */ + + .set('boundary', function() { + var pos = this.position(); + var m = this.match(/^[$^](?!\{)/); + if (!m) return; + return pos(new Node({ + type: 'text', + val: m[0] + })); + }) + + /** + * One or zero, non-comma characters wrapped in braces + */ + + .set('nobrace', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{[^,]?\}/); + if (!m) return; + + var prev = this.prev(); + var val = m[0]; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } + + return pos(new Node({ + type: 'text', + multiplier: 0, + val: val + })); + }) + + /** + * Text + */ + + .set('text', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^((?!\\)[^${}[\]])+/); + if (!m) return; + + var prev = this.prev(); + var val = m[0]; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } + + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: val + })); + + return concatNodes.call(this, pos, node, prev, options); + }); +}; + +/** + * Returns true if the character is an extglob character. + */ + +function isExtglobChar(ch) { + return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; +} + +/** + * Combine text nodes, and calculate empty sets (`{,,}`) + * @param {Function} `pos` Function to calculate node position + * @param {Object} `node` AST node + * @return {Object} + */ + +function concatNodes(pos, node, parent, options) { + node.orig = node.val; + var prev = this.prev(); + var last = utils.last(prev.nodes); + var isEscaped = false; + + if (node.val.length > 1) { + var a = node.val.charAt(0); + var b = node.val.slice(-1); + + isEscaped = (a === '"' && b === '"') + || (a === "'" && b === "'") + || (a === '`' && b === '`'); + } + + if (isEscaped && options.unescape !== false) { + node.val = node.val.slice(1, node.val.length - 1); + node.escaped = true; + } + + if (node.match) { + var match = node.match[1]; + if (!match || match.indexOf('}') === -1) { + match = node.match[0]; + } + + // replace each set with a single "," + var val = match.replace(/\{/g, ',').replace(/\}/g, ''); + node.multiplier *= val.length; + node.val = ''; + } + + var simpleText = last.type === 'text' + && last.multiplier === 1 + && node.multiplier === 1 + && node.val; + + if (simpleText) { + last.val += node.val; + return; + } + + prev.push(node); +} + + +/***/ }), + +/***/ 68130: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var splitString = __webpack_require__(33218); +var utils = module.exports; + +/** + * Module dependencies + */ + +utils.extend = __webpack_require__(28727); +utils.flatten = __webpack_require__(27299); +utils.isObject = __webpack_require__(96667); +utils.fillRange = __webpack_require__(35955); +utils.repeat = __webpack_require__(69523); +utils.unique = __webpack_require__(19009); + +utils.define = function(obj, key, val) { + Object.defineProperty(obj, key, { + writable: true, + configurable: true, + enumerable: false, + value: val + }); +}; + +/** + * Returns true if the given string contains only empty brace sets. + */ + +utils.isEmptySets = function(str) { + return /^(?:\{,\})+$/.test(str); +}; + +/** + * Returns true if the given string contains only empty brace sets. + */ + +utils.isQuotedString = function(str) { + var open = str.charAt(0); + if (open === '\'' || open === '"' || open === '`') { + return str.slice(-1) === open; + } + return false; +}; + +/** + * Create the key to use for memoization. The unique key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +utils.createKey = function(pattern, options) { + var id = pattern; + if (typeof options === 'undefined') { + return id; + } + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + id += ';' + key + '=' + String(options[key]); + } + return id; +}; + +/** + * Normalize options + */ + +utils.createOptions = function(options) { + var opts = utils.extend.apply(null, arguments); + if (typeof opts.expand === 'boolean') { + opts.optimize = !opts.expand; + } + if (typeof opts.optimize === 'boolean') { + opts.expand = !opts.optimize; + } + if (opts.optimize === true) { + opts.makeRe = true; + } + return opts; +}; + +/** + * Join patterns in `a` to patterns in `b` + */ + +utils.join = function(a, b, options) { + options = options || {}; + a = utils.arrayify(a); + b = utils.arrayify(b); + + if (!a.length) return b; + if (!b.length) return a; + + var len = a.length; + var idx = -1; + var arr = []; + + while (++idx < len) { + var val = a[idx]; + if (Array.isArray(val)) { + for (var i = 0; i < val.length; i++) { + val[i] = utils.join(val[i], b, options); + } + arr.push(val); + continue; + } + + for (var j = 0; j < b.length; j++) { + var bval = b[j]; + + if (Array.isArray(bval)) { + arr.push(utils.join(val, bval, options)); + } else { + arr.push(val + bval); + } + } + } + return arr; +}; + +/** + * Split the given string on `,` if not escaped. + */ + +utils.split = function(str, options) { + var opts = utils.extend({sep: ','}, options); + if (typeof opts.keepQuotes !== 'boolean') { + opts.keepQuotes = true; + } + if (opts.unescape === false) { + opts.keepEscaping = true; + } + return splitString(str, opts, utils.escapeBrackets(opts)); +}; + +/** + * Expand ranges or sets in the given `pattern`. + * + * @param {String} `str` + * @param {Object} `options` + * @return {Object} + */ + +utils.expand = function(str, options) { + var opts = utils.extend({rangeLimit: 10000}, options); + var segs = utils.split(str, opts); + var tok = { segs: segs }; + + if (utils.isQuotedString(str)) { + return tok; + } + + if (opts.rangeLimit === true) { + opts.rangeLimit = 10000; + } + + if (segs.length > 1) { + if (opts.optimize === false) { + tok.val = segs[0]; + return tok; + } + + tok.segs = utils.stringifyArray(tok.segs); + } else if (segs.length === 1) { + var arr = str.split('..'); + + if (arr.length === 1) { + tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; + tok.segs = []; + return tok; + } + + if (arr.length === 2 && arr[0] === arr[1]) { + tok.escaped = true; + tok.val = arr[0]; + tok.segs = []; + return tok; + } + + if (arr.length > 1) { + if (opts.optimize !== false) { + opts.optimize = true; + delete opts.expand; + } + + if (opts.optimize !== true) { + var min = Math.min(arr[0], arr[1]); + var max = Math.max(arr[0], arr[1]); + var step = arr[2] || 1; + + if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + } + + arr.push(opts); + tok.segs = utils.fillRange.apply(null, arr); + + if (!tok.segs.length) { + tok.escaped = true; + tok.val = str; + return tok; + } + + if (opts.optimize === true) { + tok.segs = utils.stringifyArray(tok.segs); + } + + if (tok.segs === '') { + tok.val = str; + } else { + tok.val = tok.segs[0]; + } + return tok; + } + } else { + tok.val = str; + } + return tok; +}; + +/** + * Ensure commas inside brackets and parens are not split. + * @param {Object} `tok` Token from the `split-string` module + * @return {undefined} + */ + +utils.escapeBrackets = function(options) { + return function(tok) { + if (tok.escaped && tok.val === 'b') { + tok.val = '\\b'; + return; + } + + if (tok.val !== '(' && tok.val !== '[') return; + var opts = utils.extend({}, options); + var brackets = []; + var parens = []; + var stack = []; + var val = tok.val; + var str = tok.str; + var i = tok.idx - 1; + + while (++i < str.length) { + var ch = str[i]; + + if (ch === '\\') { + val += (opts.keepEscaping === false ? '' : ch) + str[++i]; + continue; + } + + if (ch === '(') { + parens.push(ch); + stack.push(ch); + } + + if (ch === '[') { + brackets.push(ch); + stack.push(ch); + } + + if (ch === ')') { + parens.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } + + if (ch === ']') { + brackets.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } + val += ch; + } + + tok.split = false; + tok.val = val.slice(1); + tok.idx = i; + }; +}; + +/** + * Returns true if the given string looks like a regex quantifier + * @return {Boolean} + */ + +utils.isQuantifier = function(str) { + return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); +}; + +/** + * Cast `val` to an array. + * @param {*} `val` + */ + +utils.stringifyArray = function(arr) { + return [utils.arrayify(arr).join('|')]; +}; + +/** + * Cast `val` to an array. + * @param {*} `val` + */ + +utils.arrayify = function(arr) { + if (typeof arr === 'undefined') { + return []; + } + if (typeof arr === 'string') { + return [arr]; + } + return arr; +}; + +/** + * Returns true if the given `str` is a non-empty string + * @return {Boolean} + */ + +utils.isString = function(str) { + return str != null && typeof str === 'string'; +}; + +/** + * Get the last element from `array` + * @param {Array} `array` + * @return {*} + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +utils.escapeRegex = function(str) { + return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1'); +}; + + +/***/ }), + +/***/ 63375: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isObject = __webpack_require__(96667); +var Emitter = __webpack_require__(79458); +var visit = __webpack_require__(16704); +var toPath = __webpack_require__(71708); +var union = __webpack_require__(7716); +var del = __webpack_require__(5834); +var get = __webpack_require__(89304); +var has = __webpack_require__(41825); +var set = __webpack_require__(34857); + +/** + * Create a `Cache` constructor that when instantiated will + * store values on the given `prop`. + * + * ```js + * var Cache = require('cache-base').namespace('data'); + * var cache = new Cache(); + * + * cache.set('foo', 'bar'); + * //=> {data: {foo: 'bar'}} + * ``` + * @param {String} `prop` The property name to use for storing values. + * @return {Function} Returns a custom `Cache` constructor + * @api public + */ + +function namespace(prop) { + + /** + * Create a new `Cache`. Internally the `Cache` constructor is created using + * the `namespace` function, with `cache` defined as the storage object. + * + * ```js + * var app = new Cache(); + * ``` + * @param {Object} `cache` Optionally pass an object to initialize with. + * @constructor + * @api public + */ + + function Cache(cache) { + if (prop) { + this[prop] = {}; + } + if (cache) { + this.set(cache); + } + } + + /** + * Inherit Emitter + */ + + Emitter(Cache.prototype); + + /** + * Assign `value` to `key`. Also emits `set` with + * the key and value. + * + * ```js + * app.on('set', function(key, val) { + * // do something when `set` is emitted + * }); + * + * app.set(key, value); + * + * // also takes an object or array + * app.set({name: 'Halle'}); + * app.set([{foo: 'bar'}, {baz: 'quux'}]); + * console.log(app); + * //=> {name: 'Halle', foo: 'bar', baz: 'quux'} + * ``` + * + * @name .set + * @emits `set` with `key` and `value` as arguments. + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.set = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + if (isObject(key) || Array.isArray(key)) { + this.visit('set', key); + } else { + set(prop ? this[prop] : this, key, val); + this.emit('set', key, val); + } + return this; + }; + + /** + * Union `array` to `key`. Also emits `set` with + * the key and value. + * + * ```js + * app.union('a.b', ['foo']); + * app.union('a.b', ['bar']); + * console.log(app.get('a')); + * //=> {b: ['foo', 'bar']} + * ``` + * @name .union + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.union = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + var ctx = prop ? this[prop] : this; + union(ctx, key, arrayify(val)); + this.emit('union', val); + return this; + }; + + /** + * Return the value of `key`. Dot notation may be used + * to get [nested property values][get-value]. + * + * ```js + * app.set('a.b.c', 'd'); + * app.get('a.b'); + * //=> {c: 'd'} + * + * app.get(['a', 'b']); + * //=> {c: 'd'} + * ``` + * + * @name .get + * @emits `get` with `key` and `value` as arguments. + * @param {String} `key` The name of the property to get. Dot-notation may be used. + * @return {any} Returns the value of `key` + * @api public + */ + + Cache.prototype.get = function(key) { + key = toPath(arguments); + + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); + + this.emit('get', key, val); + return val; + }; + + /** + * Return true if app has a stored value for `key`, + * false only if value is `undefined`. + * + * ```js + * app.set('foo', 'bar'); + * app.has('foo'); + * //=> true + * ``` + * + * @name .has + * @emits `has` with `key` and true or false as arguments. + * @param {String} `key` + * @return {Boolean} + * @api public + */ + + Cache.prototype.has = function(key) { + key = toPath(arguments); + + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); + + var has = typeof val !== 'undefined'; + this.emit('has', key, has); + return has; + }; + + /** + * Delete one or more properties from the instance. + * + * ```js + * app.del(); // delete all + * // or + * app.del('foo'); + * // or + * app.del(['foo', 'bar']); + * ``` + * @name .del + * @emits `del` with the `key` as the only argument. + * @param {String|Array} `key` Property name or array of property names. + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.del = function(key) { + if (Array.isArray(key)) { + this.visit('del', key); + } else { + del(prop ? this[prop] : this, key); + this.emit('del', key); + } + return this; + }; + + /** + * Reset the entire cache to an empty object. + * + * ```js + * app.clear(); + * ``` + * @api public + */ + + Cache.prototype.clear = function() { + if (prop) { + this[prop] = {}; + } + }; + + /** + * Visit `method` over the properties in the given object, or map + * visit over the object-elements in an array. + * + * @name .visit + * @param {String} `method` The name of the `base` method to call. + * @param {Object|Array} `val` The object or array to iterate over. + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.visit = function(method, val) { + visit(this, method, val); + return this; + }; + + return Cache; +} + +/** + * Cast val to an array + */ + +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} + +/** + * Expose `Cache` + */ + +module.exports = namespace(); + +/** + * Expose `Cache.namespace` + */ + +module.exports.namespace = namespace; + + +/***/ }), + +/***/ 92430: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"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__(29859); +var stream_1 = __webpack_require__(92413); +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; + } + /** + * 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 + +/***/ }), + +/***/ 71523: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(31669); +var union = __webpack_require__(69123); +var define = __webpack_require__(5477); +var staticExtend = __webpack_require__(69457); +var isObj = __webpack_require__(96667); + +/** + * Expose class utils + */ + +var cu = module.exports; + +/** + * Expose class utils: `cu` + */ + +cu.isObject = function isObject(val) { + return isObj(val) || typeof val === 'function'; +}; + +/** + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. + * + * ```js + * cu.has(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * cu.has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + * @api public + */ + +cu.has = function has(obj, val) { + val = cu.arrayify(val); + var len = val.length; + + if (cu.isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; + } + } + + var keys = cu.nativeKeys(obj); + return cu.has(keys, val); + } + + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; + } + } + return false; + } + + throw new TypeError('expected an array or object.'); +}; + +/** + * Returns true if an array or object has all of the given values. + * + * ```js + * cu.hasAll(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.hasAll(['a', 'b', 'c'], ['c', 'z']); + * //=> false + * + * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']); + * //=> false + * ``` + * @param {Object|Array} `val` + * @param {String|Array} `values` + * @return {Boolean} + * @api public + */ + +cu.hasAll = function hasAll(val, values) { + values = cu.arrayify(values); + var len = values.length; + while (len--) { + if (!cu.has(val, values[len])) { + return false; + } + } + return true; +}; + +/** + * Cast the given value to an array. + * + * ```js + * cu.arrayify('foo'); + * //=> ['foo'] + * + * cu.arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} + * @api public + */ + +cu.arrayify = function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Noop + */ + +cu.noop = function noop() { + return; +}; + +/** + * Returns the first argument passed to the function. + */ + +cu.identity = function identity(val) { + return val; +}; + +/** + * Returns true if a value has a `contructor` + * + * ```js + * cu.hasConstructor({}); + * //=> true + * + * cu.hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} + * @api public + */ + +cu.hasConstructor = function hasConstructor(val) { + return cu.isObject(val) && typeof val.constructor !== 'undefined'; +}; + +/** + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. + * + * ```js + * cu.nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * cu.nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + * @api public + */ + +cu.nativeKeys = function nativeKeys(val) { + if (!cu.hasConstructor(val)) return []; + var keys = Object.getOwnPropertyNames(val); + if ('caller' in val) keys.push('caller'); + return keys; +}; + +/** + * Returns property descriptor `key` if it's an "own" property + * of the given object. + * + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * cu.getDescriptor(App.prototype, 'count'); + * // returns: + * // { + * // get: [Function], + * // set: undefined, + * // enumerable: false, + * // configurable: false + * // } + * ``` + * + * @param {Object} `obj` + * @param {String} `key` + * @return {Object} Returns descriptor `key` + * @api public + */ + +cu.getDescriptor = function getDescriptor(obj, key) { + if (!cu.isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (typeof key !== 'string') { + throw new TypeError('expected key to be a string.'); + } + return Object.getOwnPropertyDescriptor(obj, key); +}; + +/** + * Copy a descriptor from one object to another. + * + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * var obj = {}; + * cu.copyDescriptor(obj, App.prototype, 'count'); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String} `name` + * @return {Object} + * @api public + */ + +cu.copyDescriptor = function copyDescriptor(receiver, provider, name) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string.'); + } + + var val = cu.getDescriptor(provider, name); + if (val) Object.defineProperty(receiver, name, val); +}; + +/** + * Copy static properties, prototype properties, and descriptors + * from one object to another. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ + +cu.copy = function copy(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + var props = Object.getOwnPropertyNames(provider); + var keys = Object.keys(provider); + var len = props.length, + key; + omit = cu.arrayify(omit); + + while (len--) { + key = props[len]; + + if (cu.has(keys, key)) { + define(receiver, key, provider[key]); + } else if (!(key in receiver) && !cu.has(omit, key)) { + cu.copyDescriptor(receiver, provider, key); + } + } +}; + +/** + * Inherit the static properties, prototype properties, and descriptors + * from of an object. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ + +cu.inherit = function inherit(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + + var keys = []; + for (var key in provider) { + keys.push(key); + receiver[key] = provider[key]; + } + + keys = keys.concat(cu.arrayify(omit)); + + var a = provider.prototype || provider; + var b = receiver.prototype || receiver; + cu.copy(b, a, keys); +}; + +/** + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. + * + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public + */ + +cu.extend = function() { + // keep it lazy, instead of assigning to `cu.extend` + return staticExtend.apply(null, arguments); +}; + +/** + * Bubble up events emitted from static methods on the Parent ctor. + * + * @param {Object} `Parent` + * @param {Array} `events` Event names to bubble up + * @api public + */ + +cu.bubble = function(Parent, events) { + events = events || []; + Parent.bubble = function(Child, arr) { + if (Array.isArray(arr)) { + events = union([], events, arr); + } + var len = events.length; + var idx = -1; + while (++idx < len) { + var name = events[idx]; + Parent.on(name, Child.emit.bind(Child, name)); + } + cu.bubble(Child, events); + }; +}; + + +/***/ }), + +/***/ 16704: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * collection-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var visit = __webpack_require__(59248); +var mapVisit = __webpack_require__(11270); + +module.exports = function(collection, method, val) { + var result; + + if (typeof val === 'string' && (method in collection)) { + var args = [].slice.call(arguments, 2); + result = collection[method].apply(collection, args); + } else if (Array.isArray(val)) { + result = mapVisit.apply(null, arguments); + } else { + result = visit.apply(null, arguments); + } + + if (typeof result !== 'undefined') { + return result; + } + + return collection; +}; + + +/***/ }), + +/***/ 79458: +/***/ ((module) => { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }), + +/***/ 3605: +/***/ ((module) => { + +"use strict"; +/*! + * copy-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +/** + * Copy a descriptor from one object to another. + * + * ```js + * function App() { + * this.cache = {}; + * } + * App.prototype.set = function(key, val) { + * this.cache[key] = val; + * return this; + * }; + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this.cache).length; + * } + * }); + * + * copy(App.prototype, 'count', 'len'); + * + * // create an instance + * var app = new App(); + * + * app.set('a', true); + * app.set('b', true); + * app.set('c', true); + * + * console.log(app.count); + * //=> 3 + * console.log(app.len); + * //=> 3 + * ``` + * @name copy + * @param {Object} `receiver` The target object + * @param {Object} `provider` The provider object + * @param {String} `from` The key to copy on provider. + * @param {String} `to` Optionally specify a new key name to use. + * @return {Object} + * @api public + */ + +module.exports = function copyDescriptor(receiver, provider, from, to) { + if (!isObject(provider) && typeof provider !== 'function') { + to = from; + from = provider; + provider = receiver; + } + if (!isObject(receiver) && typeof receiver !== 'function') { + throw new TypeError('expected the first argument to be an object'); + } + if (!isObject(provider) && typeof provider !== 'function') { + throw new TypeError('expected provider to be an object'); + } + + if (typeof to !== 'string') { + to = from; + } + if (typeof from !== 'string') { + throw new TypeError('expected key to be a string'); + } + + if (!(from in provider)) { + throw new Error('property "' + from + '" does not exist'); + } + + var val = Object.getOwnPropertyDescriptor(provider, from); + if (val) Object.defineProperty(receiver, to, val); +}; + +function isObject(val) { + return {}.toString.call(val) === '[object Object]'; +} + + + +/***/ }), + +/***/ 78334: +/***/ ((__unused_webpack_module, exports) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 95748: +/***/ ((module) => { + +"use strict"; + +var token = '%[a-f0-9]{2}'; +var singleMatcher = new RegExp(token, 'gi'); +var multiMatcher = new RegExp('(' + token + ')+', 'gi'); + +function decodeComponents(components, split) { + try { + // Try to decode the entire string first + return decodeURIComponent(components.join('')); + } catch (err) { + // Do nothing + } + + if (components.length === 1) { + return components; + } + + split = split || 1; + + // Split the array in 2 parts + var left = components.slice(0, split); + var right = components.slice(split); + + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); +} + +function decode(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher); + + for (var i = 1; i < tokens.length; i++) { + input = decodeComponents(tokens, i).join(''); + + tokens = input.match(singleMatcher); + } + + return input; + } +} + +function customDecodeURIComponent(input) { + // Keep track of all the replacements and prefill the map with the `BOM` + var replaceMap = { + '%FE%FF': '\uFFFD\uFFFD', + '%FF%FE': '\uFFFD\uFFFD' + }; + + var match = multiMatcher.exec(input); + while (match) { + try { + // Decode as big chunks as possible + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode(match[0]); + + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } + + match = multiMatcher.exec(input); + } + + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else + replaceMap['%C2'] = '\uFFFD'; + + var entries = Object.keys(replaceMap); + + for (var i = 0; i < entries.length; i++) { + // Replace all decoded components + var key = entries[i]; + input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + } + + return input; +} + +module.exports = function (encodedURI) { + if (typeof encodedURI !== 'string') { + throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); + } + + try { + encodedURI = encodedURI.replace(/\+/g, ' '); + + // Try the built in decoder first + return decodeURIComponent(encodedURI); + } catch (err) { + // Fallback to a more advanced decoder + return customDecodeURIComponent(encodedURI); + } +}; + + +/***/ }), + +/***/ 5477: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(49924); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), + +/***/ 30138: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(1057); + +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; + +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (typeOf(obj) !== 'object') { + return false; + } + + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } + + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } + + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } + + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} + +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; + + +/***/ }), + +/***/ 1057: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var isBuffer = __webpack_require__(72195); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), + +/***/ 54963: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(31072); + +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; + +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } + + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +/** + * Expose `isDataDescriptor` + */ + +module.exports = isDataDescriptor; + + +/***/ }), + +/***/ 31072: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var isBuffer = __webpack_require__(72195); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), + +/***/ 49924: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(42649); +var isAccessor = __webpack_require__(30138); +var isData = __webpack_require__(54963); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; + + +/***/ }), + +/***/ 42649: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + var type = typeof val; + + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); +} + + +/***/ }), + +/***/ 89901: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DescriptionFileUtils = __webpack_require__(70232); +const getInnerRequest = __webpack_require__(91878); + +module.exports = class AliasFieldPlugin { + constructor(source, field, target) { + this.source = source; + this.field = field; + this.target = target; + } + + 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 (typeof fieldData !== "object") { + if (resolveContext.log) + resolveContext.log( + "Field '" + + this.field + + "' doesn't contain a valid alias configuration" + ); + return callback(); + } + 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) { + const ignoreObj = Object.assign({}, request, { + path: false + }); + return callback(null, ignoreObj); + } + const obj = Object.assign({}, request, { + path: request.descriptionFileRoot, + request: data + }); + resolver.doResolve( + target, + obj, + "aliased from description file " + + request.descriptionFilePath + + " with mapping '" + + innerRequest + + "' to '" + + data + + "'", + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 15005: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +function startsWith(string, searchString) { + const stringLength = string.length; + const searchLength = searchString.length; + + // early out if the search length is greater than the search string + if (searchLength > stringLength) { + return false; + } + let index = -1; + while (++index < searchLength) { + if (string.charCodeAt(index) !== searchString.charCodeAt(index)) { + return false; + } + } + return true; +} + +module.exports = class AliasPlugin { + constructor(source, options, target) { + this.source = source; + this.options = Array.isArray(options) ? options : [options]; + this.target = target; + } + + 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(); + for (const item of this.options) { + if ( + innerRequest === item.name || + (!item.onlyModule && startsWith(innerRequest, item.name + "/")) + ) { + if ( + innerRequest !== item.alias && + !startsWith(innerRequest, item.alias + "/") + ) { + const newRequestStr = + item.alias + innerRequest.substr(item.name.length); + const obj = Object.assign({}, request, { + request: newRequestStr + }); + return resolver.doResolve( + target, + obj, + "aliased with mapping '" + + item.name + + "': '" + + item.alias + + "' to '" + + newRequestStr + + "'", + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + } + } + } + return callback(); + }); + } +}; + + +/***/ }), + +/***/ 2271: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class AppendPlugin { + constructor(source, appending, target) { + this.source = source; + this.appending = appending; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AppendPlugin", (request, resolveContext, callback) => { + const obj = Object.assign({}, request, { + path: request.path + this.appending, + relativePath: + request.relativePath && request.relativePath + this.appending + }); + resolver.doResolve( + target, + obj, + this.appending, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 75544: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class Storage { + constructor(duration) { + this.duration = duration; + this.running = new Map(); + this.data = new Map(); + this.levels = []; + if (duration > 0) { + this.levels.push( + new Set(), + new Set(), + new Set(), + new Set(), + new Set(), + new Set(), + new Set(), + new Set(), + new Set() + ); + for (let i = 8000; i < duration; i += 500) this.levels.push(new Set()); + } + this.count = 0; + this.interval = null; + this.needTickCheck = false; + this.nextTick = null; + this.passive = true; + this.tick = this.tick.bind(this); + } + + ensureTick() { + if (!this.interval && this.duration > 0 && !this.nextTick) + this.interval = setInterval( + this.tick, + Math.floor(this.duration / this.levels.length) + ); + } + + finished(name, err, result) { + const callbacks = this.running.get(name); + this.running.delete(name); + if (this.duration > 0) { + this.data.set(name, [err, result]); + const levelData = this.levels[0]; + this.count -= levelData.size; + levelData.add(name); + this.count += levelData.size; + this.ensureTick(); + } + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](err, result); + } + } + + finishedSync(name, err, result) { + if (this.duration > 0) { + this.data.set(name, [err, result]); + const levelData = this.levels[0]; + this.count -= levelData.size; + levelData.add(name); + this.count += levelData.size; + this.ensureTick(); + } + } + + provide(name, provider, callback) { + if (typeof name !== "string") { + callback(new TypeError("path must be a string")); + return; + } + let running = this.running.get(name); + if (running) { + running.push(callback); + return; + } + if (this.duration > 0) { + this.checkTicks(); + const data = this.data.get(name); + if (data) { + return process.nextTick(() => { + callback.apply(null, data); + }); + } + } + this.running.set(name, (running = [callback])); + provider(name, (err, result) => { + this.finished(name, err, result); + }); + } + + provideSync(name, provider) { + if (typeof name !== "string") { + throw new TypeError("path must be a string"); + } + if (this.duration > 0) { + this.checkTicks(); + const data = this.data.get(name); + if (data) { + if (data[0]) throw data[0]; + return data[1]; + } + } + let result; + try { + result = provider(name); + } catch (e) { + this.finishedSync(name, e); + throw e; + } + this.finishedSync(name, null, result); + return result; + } + + tick() { + const decay = this.levels.pop(); + for (let item of decay) { + this.data.delete(item); + } + this.count -= decay.size; + decay.clear(); + this.levels.unshift(decay); + if (this.count === 0) { + clearInterval(this.interval); + this.interval = null; + this.nextTick = null; + return true; + } else if (this.nextTick) { + this.nextTick += Math.floor(this.duration / this.levels.length); + const time = new Date().getTime(); + if (this.nextTick > time) { + this.nextTick = null; + this.interval = setInterval( + this.tick, + Math.floor(this.duration / this.levels.length) + ); + return true; + } + } else if (this.passive) { + clearInterval(this.interval); + this.interval = null; + this.nextTick = + new Date().getTime() + Math.floor(this.duration / this.levels.length); + } else { + this.passive = true; + } + } + + checkTicks() { + this.passive = false; + if (this.nextTick) { + while (!this.tick()); + } + } + + purge(what) { + if (!what) { + this.count = 0; + clearInterval(this.interval); + this.nextTick = null; + this.data.clear(); + this.levels.forEach(level => { + level.clear(); + }); + } else if (typeof what === "string") { + for (let key of this.data.keys()) { + if (key.startsWith(what)) this.data.delete(key); + } + } else { + for (let i = what.length - 1; i >= 0; i--) { + this.purge(what[i]); + } + } + } +} + +module.exports = class CachedInputFileSystem { + constructor(fileSystem, duration) { + this.fileSystem = fileSystem; + this._statStorage = new Storage(duration); + this._readdirStorage = new Storage(duration); + this._readFileStorage = new Storage(duration); + this._readJsonStorage = new Storage(duration); + this._readlinkStorage = new Storage(duration); + + this._stat = this.fileSystem.stat + ? this.fileSystem.stat.bind(this.fileSystem) + : null; + if (!this._stat) this.stat = null; + + this._statSync = this.fileSystem.statSync + ? this.fileSystem.statSync.bind(this.fileSystem) + : null; + if (!this._statSync) this.statSync = null; + + this._readdir = this.fileSystem.readdir + ? this.fileSystem.readdir.bind(this.fileSystem) + : null; + if (!this._readdir) this.readdir = null; + + this._readdirSync = this.fileSystem.readdirSync + ? this.fileSystem.readdirSync.bind(this.fileSystem) + : null; + if (!this._readdirSync) this.readdirSync = null; + + this._readFile = this.fileSystem.readFile + ? this.fileSystem.readFile.bind(this.fileSystem) + : null; + if (!this._readFile) this.readFile = null; + + this._readFileSync = this.fileSystem.readFileSync + ? this.fileSystem.readFileSync.bind(this.fileSystem) + : null; + if (!this._readFileSync) this.readFileSync = null; + + if (this.fileSystem.readJson) { + this._readJson = this.fileSystem.readJson.bind(this.fileSystem); + } else if (this.readFile) { + this._readJson = (path, callback) => { + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + let data; + try { + data = JSON.parse(buffer.toString("utf-8")); + } catch (e) { + return callback(e); + } + callback(null, data); + }); + }; + } else { + this.readJson = null; + } + if (this.fileSystem.readJsonSync) { + this._readJsonSync = this.fileSystem.readJsonSync.bind(this.fileSystem); + } else if (this.readFileSync) { + this._readJsonSync = path => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf-8")); + return data; + }; + } else { + this.readJsonSync = null; + } + + this._readlink = this.fileSystem.readlink + ? this.fileSystem.readlink.bind(this.fileSystem) + : null; + if (!this._readlink) this.readlink = null; + + this._readlinkSync = this.fileSystem.readlinkSync + ? this.fileSystem.readlinkSync.bind(this.fileSystem) + : null; + if (!this._readlinkSync) this.readlinkSync = null; + } + + stat(path, callback) { + this._statStorage.provide(path, this._stat, callback); + } + + readdir(path, callback) { + this._readdirStorage.provide(path, this._readdir, callback); + } + + readFile(path, callback) { + this._readFileStorage.provide(path, this._readFile, callback); + } + + readJson(path, callback) { + this._readJsonStorage.provide(path, this._readJson, callback); + } + + readlink(path, callback) { + this._readlinkStorage.provide(path, this._readlink, callback); + } + + statSync(path) { + return this._statStorage.provideSync(path, this._statSync); + } + + readdirSync(path) { + return this._readdirStorage.provideSync(path, this._readdirSync); + } + + readFileSync(path) { + return this._readFileStorage.provideSync(path, this._readFileSync); + } + + readJsonSync(path) { + return this._readJsonStorage.provideSync(path, this._readJsonSync); + } + + readlinkSync(path) { + return this._readlinkStorage.provideSync(path, this._readlinkSync); + } + + purge(what) { + this._statStorage.purge(what); + this._readdirStorage.purge(what); + this._readFileStorage.purge(what); + this._readlinkStorage.purge(what); + this._readJsonStorage.purge(what); + } +}; + + +/***/ }), + +/***/ 56821: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const concord = __webpack_require__(94323); +const DescriptionFileUtils = __webpack_require__(70232); +const forEachBail = __webpack_require__(60059); + +module.exports = class ConcordExtensionsPlugin { + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "ConcordExtensionsPlugin", + (request, resolveContext, callback) => { + const concordField = DescriptionFileUtils.getField( + request.descriptionFileData, + "concord" + ); + if (!concordField) return callback(); + const extensions = concord.getExtensions( + request.context, + concordField + ); + if (!extensions) return callback(); + forEachBail( + extensions, + (appending, callback) => { + const obj = Object.assign({}, request, { + path: request.path + appending, + relativePath: + request.relativePath && request.relativePath + appending + }); + resolver.doResolve( + target, + obj, + "concord extension: " + appending, + resolveContext, + callback + ); + }, + (err, result) => { + if (err) return callback(err); + + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + } + ); + } +}; + + +/***/ }), + +/***/ 27878: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const concord = __webpack_require__(94323); +const DescriptionFileUtils = __webpack_require__(70232); + +module.exports = class ConcordMainPlugin { + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ConcordMainPlugin", (request, resolveContext, callback) => { + if (request.path !== request.descriptionFileRoot) return callback(); + const concordField = DescriptionFileUtils.getField( + request.descriptionFileData, + "concord" + ); + if (!concordField) return callback(); + const mainModule = concord.getMain(request.context, concordField); + if (!mainModule) return callback(); + const obj = Object.assign({}, request, { + request: mainModule + }); + const filename = path.basename(request.descriptionFilePath); + return resolver.doResolve( + target, + obj, + "use " + mainModule + " from " + filename, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 50297: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const concord = __webpack_require__(94323); +const DescriptionFileUtils = __webpack_require__(70232); +const getInnerRequest = __webpack_require__(91878); + +module.exports = class ConcordModulesPlugin { + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ConcordModulesPlugin", (request, resolveContext, callback) => { + const innerRequest = getInnerRequest(resolver, request); + if (!innerRequest) return callback(); + const concordField = DescriptionFileUtils.getField( + request.descriptionFileData, + "concord" + ); + if (!concordField) return callback(); + const data = concord.matchModule( + request.context, + concordField, + innerRequest + ); + if (data === innerRequest) return callback(); + if (data === undefined) return callback(); + if (data === false) { + const ignoreObj = Object.assign({}, request, { + path: false + }); + return callback(null, ignoreObj); + } + const obj = Object.assign({}, request, { + path: request.descriptionFileRoot, + request: data + }); + resolver.doResolve( + target, + obj, + "aliased from description file " + + request.descriptionFilePath + + " with mapping '" + + innerRequest + + "' to '" + + data + + "'", + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 95637: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* +MIT License http://www.opensource.org/licenses/mit-license.php +Author Tobias Koppers @sokra +*/ + + +const DescriptionFileUtils = __webpack_require__(70232); + +module.exports = class DescriptionFilePlugin { + constructor(source, filenames, target) { + this.source = source; + this.filenames = [].concat(filenames); + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DescriptionFilePlugin", + (request, resolveContext, callback) => { + const directory = request.path; + DescriptionFileUtils.loadDescriptionFile( + resolver, + directory, + this.filenames, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (!result) { + if (resolveContext.missing) { + this.filenames.forEach(filename => { + resolveContext.missing.add( + resolver.join(directory, filename) + ); + }); + } + if (resolveContext.log) + resolveContext.log("No description file found"); + return callback(); + } + const relativePath = + "." + + request.path + .substr(result.directory.length) + .replace(/\\/g, "/"); + const obj = Object.assign({}, request, { + descriptionFilePath: result.path, + descriptionFileData: result.content, + descriptionFileRoot: result.directory, + relativePath: relativePath + }); + resolver.doResolve( + target, + obj, + "using description file: " + + result.path + + " (relative path: " + + relativePath + + ")", + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + } + ); + } + ); + } +}; + + +/***/ }), + +/***/ 70232: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const forEachBail = __webpack_require__(60059); + +function loadDescriptionFile( + resolver, + directory, + filenames, + resolveContext, + callback +) { + (function findDescriptionFile() { + 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") return callback(); + return onJson(err); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) return callback(); + let json; + try { + json = JSON.parse(content); + } catch (e) { + onJson(e); + } + 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: content, + directory: directory, + path: descriptionFilePath + }); + } + }, + (err, result) => { + if (err) return callback(err); + if (result) { + return callback(null, result); + } else { + directory = cdUp(directory); + if (!directory) { + return callback(); + } else { + return findDescriptionFile(); + } + } + } + ); + })(); +} + +function getField(content, field) { + if (!content) return undefined; + if (Array.isArray(field)) { + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = current[field[j]]; + } + if (typeof current === "object") { + return current; + } + } else { + if (typeof content[field] === "object") { + return content[field]; + } + } +} + +function cdUp(directory) { + if (directory === "/") return null; + 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; + + +/***/ }), + +/***/ 48504: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class DirectoryExistsPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + 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; + fs.stat(directory, (err, stat) => { + if (err || !stat) { + if (resolveContext.missing) resolveContext.missing.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " doesn't exist"); + return callback(); + } + if (!stat.isDirectory()) { + if (resolveContext.missing) resolveContext.missing.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " is not a directory"); + return callback(); + } + resolver.doResolve( + target, + request, + "existing directory", + resolveContext, + callback + ); + }); + } + ); + } +}; + + +/***/ }), + +/***/ 68372: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class FileExistsPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + 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; + fs.stat(file, (err, stat) => { + if (err || !stat) { + if (resolveContext.missing) resolveContext.missing.add(file); + if (resolveContext.log) resolveContext.log(file + " doesn't exist"); + return callback(); + } + if (!stat.isFile()) { + if (resolveContext.missing) resolveContext.missing.add(file); + if (resolveContext.log) resolveContext.log(file + " is not a file"); + return callback(); + } + resolver.doResolve( + target, + request, + "existing file: " + file, + resolveContext, + callback + ); + }); + }); + } +}; + + +/***/ }), + +/***/ 63602: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class FileKindPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("FileKindPlugin", (request, resolveContext, callback) => { + if (request.directory) return callback(); + const obj = Object.assign({}, request); + delete obj.directory; + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; + + +/***/ }), + +/***/ 31693: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class JoinRequestPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const obj = Object.assign({}, request, { + path: resolver.join(request.path, request.request), + relativePath: + request.relativePath && + resolver.join(request.relativePath, request.request), + request: undefined + }); + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; + + +/***/ }), + +/***/ 7064: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); + +module.exports = class MainFieldPlugin { + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if (request.path !== request.descriptionFileRoot) return callback(); + if (request.alreadyTriedMainField === request.descriptionFilePath) + return callback(); + const content = request.descriptionFileData; + const filename = path.basename(request.descriptionFilePath); + let mainModule; + const field = this.options.name; + 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]]; + } + if (typeof current === "string") { + mainModule = current; + } + } else { + if (typeof content[field] === "string") { + mainModule = content[field]; + } + } + if (!mainModule) return callback(); + if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) + mainModule = "./" + mainModule; + const obj = Object.assign({}, request, { + request: mainModule, + alreadyTriedMainField: request.descriptionFilePath + }); + return resolver.doResolve( + target, + obj, + "use " + + mainModule + + " from " + + this.options.name + + " in " + + filename, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 23780: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class ModuleAppendPlugin { + constructor(source, appending, target) { + this.source = source; + this.appending = appending; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModuleAppendPlugin", (request, resolveContext, callback) => { + const i = request.request.indexOf("/"), + j = request.request.indexOf("\\"); + const p = i < 0 ? j : j < 0 ? i : i < j ? i : j; + let moduleName, remainingRequest; + if (p < 0) { + moduleName = request.request; + remainingRequest = ""; + } else { + moduleName = request.request.substr(0, p); + remainingRequest = request.request.substr(p); + } + if (moduleName === "." || moduleName === "..") return callback(); + const moduleFinalName = moduleName + this.appending; + const obj = Object.assign({}, request, { + request: moduleFinalName + remainingRequest + }); + resolver.doResolve( + target, + obj, + "module variation " + moduleFinalName, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 9529: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class ModuleKindPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModuleKindPlugin", (request, resolveContext, callback) => { + if (!request.module) return callback(); + const obj = Object.assign({}, request); + delete obj.module; + resolver.doResolve( + target, + obj, + "resolve as module", + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 23195: +/***/ ((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__(60059); +const getPaths = __webpack_require__(49395); + +module.exports = class ModulesInHierachicDirectoriesPlugin { + constructor(source, directories, target) { + this.source = source; + this.directories = [].concat(directories); + this.target = target; + } + + 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 = Object.assign({}, request, { + path: addr, + request: "./" + request.request + }); + 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.missing) resolveContext.missing.add(addr); + return callback(); + }); + }, + callback + ); + } + ); + } +}; + + +/***/ }), + +/***/ 3092: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class ModulesInRootPlugin { + constructor(source, path, target) { + this.source = source; + this.path = path; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + const obj = Object.assign({}, request, { + path: this.path, + request: "./" + request.request + }); + resolver.doResolve( + target, + obj, + "looking for modules in " + this.path, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 50959: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class NextPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("NextPlugin", (request, resolveContext, callback) => { + resolver.doResolve(target, request, null, resolveContext, callback); + }); + } +}; + + +/***/ }), + +/***/ 13445: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const fs = __webpack_require__(82161); + +class NodeJsInputFileSystem { + readdir(path, callback) { + fs.readdir(path, (err, files) => { + callback( + err, + files && + files.map(file => { + return file.normalize ? file.normalize("NFC") : file; + }) + ); + }); + } + + readdirSync(path) { + const files = fs.readdirSync(path); + return ( + files && + files.map(file => { + return file.normalize ? file.normalize("NFC") : file; + }) + ); + } +} + +const fsMethods = [ + "stat", + "statSync", + "readFile", + "readFileSync", + "readlink", + "readlinkSync" +]; + +for (const key of fsMethods) { + Object.defineProperty(NodeJsInputFileSystem.prototype, key, { + configurable: true, + writable: true, + value: fs[key].bind(fs) + }); +} + +module.exports = NodeJsInputFileSystem; + + +/***/ }), + +/***/ 9743: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class ParsePlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ParsePlugin", (request, resolveContext, callback) => { + const parsed = resolver.parse(request.request); + const obj = Object.assign({}, request, parsed); + if (request.query && !parsed.query) { + obj.query = request.query; + } + if (parsed && resolveContext.log) { + if (parsed.module) resolveContext.log("Parsed request is a module"); + if (parsed.directory) + resolveContext.log("Parsed request is a directory"); + } + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; + + +/***/ }), + +/***/ 82797: +/***/ ((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__(31669); + +const Tapable = __webpack_require__(72693); +const SyncHook = __webpack_require__(77633); +const AsyncSeriesBailHook = __webpack_require__(89674); +const AsyncSeriesHook = __webpack_require__(55328); +const createInnerContext = __webpack_require__(6369); + +const REGEXP_NOT_MODULE = /^\.$|^\.[\\/]|^\.\.$|^\.\.[\\/]|^\/|^[A-Z]:[\\/]/i; +const REGEXP_DIRECTORY = /[\\/]$/i; + +const memoryFsJoin = __webpack_require__(65775); +const memoizedJoin = new Map(); +const memoryFsNormalize = __webpack_require__(69038); + +function withName(name, hook) { + hook.name = name; + return hook; +} + +function toCamelCase(str) { + return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); +} + +const deprecatedPushToMissing = util.deprecate((set, item) => { + set.add(item); +}, "Resolver: 'missing' is now a Set. Use add instead of push."); + +const deprecatedResolveContextInCallback = util.deprecate(x => { + return x; +}, "Resolver: The callback argument was splitted into resolveContext and callback."); + +const deprecatedHookAsString = util.deprecate(x => { + return x; +}, "Resolver#doResolve: The type arguments (string) is now a hook argument (Hook). Pass a reference to the hook instead."); + +class Resolver extends Tapable { + constructor(fileSystem) { + super(); + this.fileSystem = fileSystem; + this.hooks = { + resolveStep: withName("resolveStep", new SyncHook(["hook", "request"])), + noResolve: withName("noResolve", new SyncHook(["request", "error"])), + resolve: withName( + "resolve", + new AsyncSeriesBailHook(["request", "resolveContext"]) + ), + result: new AsyncSeriesHook(["result", "resolveContext"]) + }; + this._pluginCompat.tap("Resolver: before/after", options => { + if (/^before-/.test(options.name)) { + options.name = options.name.substr(7); + options.stage = -10; + } else if (/^after-/.test(options.name)) { + options.name = options.name.substr(6); + options.stage = 10; + } + }); + this._pluginCompat.tap("Resolver: step hooks", options => { + const name = options.name; + const stepHook = !/^resolve(-s|S)tep$|^no(-r|R)esolve$/.test(name); + if (stepHook) { + options.async = true; + this.ensureHook(name); + const fn = options.fn; + options.fn = (request, resolverContext, callback) => { + const innerCallback = (err, result) => { + if (err) return callback(err); + if (result !== undefined) return callback(null, result); + callback(); + }; + for (const key in resolverContext) { + innerCallback[key] = resolverContext[key]; + } + fn.call(this, request, innerCallback); + }; + } + }); + } + + ensureHook(name) { + if (typeof name !== "string") return name; + name = toCamelCase(name); + if (/^before/.test(name)) { + return this.ensureHook( + name[6].toLowerCase() + name.substr(7) + ).withOptions({ + stage: -10 + }); + } + if (/^after/.test(name)) { + return this.ensureHook( + name[5].toLowerCase() + name.substr(6) + ).withOptions({ + stage: 10 + }); + } + const hook = this.hooks[name]; + if (!hook) { + return (this.hooks[name] = withName( + name, + new AsyncSeriesBailHook(["request", "resolveContext"]) + )); + } + return hook; + } + + getHook(name) { + if (typeof name !== "string") return name; + name = toCamelCase(name); + if (/^before/.test(name)) { + return this.getHook(name[6].toLowerCase() + name.substr(7)).withOptions({ + stage: -10 + }); + } + if (/^after/.test(name)) { + return 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; + } + + resolveSync(context, path, request) { + let err, + result, + 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; + return result; + } + + resolve(context, path, request, resolveContext, callback) { + // TODO remove in enhanced-resolve 5 + // For backward compatiblity START + if (typeof callback !== "function") { + callback = deprecatedResolveContextInCallback(resolveContext); + // resolveContext is a function containing additional properties + // It's now used for resolveContext and callback + } + // END + const obj = { + context: context, + path: path, + request: request + }; + + const message = "resolve '" + request + "' in '" + path + "'"; + + // Try to resolve assuming there is no error + // We don't log stuff in this case + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + missing: resolveContext.missing, + stack: resolveContext.stack + }, + (err, result) => { + if (!err && result) { + return callback( + null, + result.path === false ? false : result.path + (result.query || ""), + result + ); + } + + const localMissing = new Set(); + // TODO remove in enhanced-resolve 5 + localMissing.push = item => deprecatedPushToMissing(localMissing, item); + const log = []; + + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: msg => { + if (resolveContext.log) { + resolveContext.log(msg); + } + log.push(msg); + }, + missing: localMissing, + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); + + const error = new Error("Can't " + message); + error.details = log.join("\n"); + error.missing = Array.from(localMissing); + this.hooks.noResolve.call(obj, error); + return callback(error); + } + ); + } + ); + } + + doResolve(hook, request, message, resolveContext, callback) { + // TODO remove in enhanced-resolve 5 + // For backward compatiblity START + if (typeof callback !== "function") { + callback = deprecatedResolveContextInCallback(resolveContext); + // resolveContext is a function containing additional properties + // It's now used for resolveContext and callback + } + if (typeof hook === "string") { + const name = toCamelCase(hook); + hook = deprecatedHookAsString(this.hooks[name]); + if (!hook) { + throw new Error(`Hook "${name}" doesn't exist`); + } + } + // END + if (typeof callback !== "function") + throw new Error("callback is not a function " + Array.from(arguments)); + if (!resolveContext) + throw new Error( + "resolveContext is not an object " + Array.from(arguments) + ); + + const stackLine = + hook.name + + ": (" + + request.path + + ") " + + (request.request || "") + + (request.query || "") + + (request.directory ? " directory" : "") + + (request.module ? " module" : ""); + + let newStack; + if (resolveContext.stack) { + newStack = new Set(resolveContext.stack); + if (resolveContext.stack.has(stackLine)) { + // Prevent recursion + 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(stackLine); + } else { + newStack = new Set([stackLine]); + } + this.hooks.resolveStep.call(hook, request); + + if (hook.isUsed()) { + const innerContext = createInnerContext( + { + log: resolveContext.log, + missing: resolveContext.missing, + stack: newStack + }, + message + ); + return hook.callAsync(request, innerContext, (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } else { + callback(); + } + } + + parse(identifier) { + if (identifier === "") return null; + const part = { + request: "", + query: "", + module: false, + directory: false, + file: false + }; + const idxQuery = identifier.indexOf("?"); + if (idxQuery === 0) { + part.query = identifier; + } else if (idxQuery > 0) { + part.request = identifier.slice(0, idxQuery); + part.query = identifier.slice(idxQuery); + } else { + part.request = identifier; + } + if (part.request) { + part.module = this.isModule(part.request); + part.directory = this.isDirectory(part.request); + if (part.directory) { + part.request = part.request.substr(0, part.request.length - 1); + } + } + return part; + } + + isModule(path) { + return !REGEXP_NOT_MODULE.test(path); + } + + isDirectory(path) { + return REGEXP_DIRECTORY.test(path); + } + + join(path, request) { + let cacheEntry; + let pathCache = memoizedJoin.get(path); + if (typeof pathCache === "undefined") { + memoizedJoin.set(path, (pathCache = new Map())); + } else { + cacheEntry = pathCache.get(request); + if (typeof cacheEntry !== "undefined") return cacheEntry; + } + cacheEntry = memoryFsJoin(path, request); + pathCache.set(request, cacheEntry); + return cacheEntry; + } + + normalize(path) { + return memoryFsNormalize(path); + } +} + +module.exports = Resolver; + + +/***/ }), + +/***/ 34129: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Resolver = __webpack_require__(82797); + +const SyncAsyncFileSystemDecorator = __webpack_require__(83230); + +const ParsePlugin = __webpack_require__(9743); +const DescriptionFilePlugin = __webpack_require__(95637); +const NextPlugin = __webpack_require__(50959); +const TryNextPlugin = __webpack_require__(31702); +const ModuleKindPlugin = __webpack_require__(9529); +const FileKindPlugin = __webpack_require__(63602); +const JoinRequestPlugin = __webpack_require__(31693); +const ModulesInHierachicDirectoriesPlugin = __webpack_require__(23195); +const ModulesInRootPlugin = __webpack_require__(3092); +const AliasPlugin = __webpack_require__(15005); +const AliasFieldPlugin = __webpack_require__(89901); +const ConcordExtensionsPlugin = __webpack_require__(56821); +const ConcordMainPlugin = __webpack_require__(27878); +const ConcordModulesPlugin = __webpack_require__(50297); +const DirectoryExistsPlugin = __webpack_require__(48504); +const FileExistsPlugin = __webpack_require__(68372); +const SymlinkPlugin = __webpack_require__(51104); +const MainFieldPlugin = __webpack_require__(7064); +const UseFilePlugin = __webpack_require__(41232); +const AppendPlugin = __webpack_require__(2271); +const RootPlugin = __webpack_require__(32669); +const RestrictionsPlugin = __webpack_require__(49751); +const ResultPlugin = __webpack_require__(19258); +const ModuleAppendPlugin = __webpack_require__(23780); +const UnsafeCachePlugin = __webpack_require__(81809); + +exports.createResolver = function(options) { + //// OPTIONS //// + + // A list of directories to resolve modules from, can be absolute path or folder name + let modules = options.modules || ["node_modules"]; + + // A list of description files to read from + const descriptionFiles = options.descriptionFiles || ["package.json"]; + + // A list of additional resolve plugins which should be applied + // The slice is there to create a copy, because otherwise pushing into plugins + // changes the original options.plugins array, causing duplicate plugins + const plugins = (options.plugins && options.plugins.slice()) || []; + + // A list of main fields in description files + let mainFields = options.mainFields || ["main"]; + + // A list of alias fields in description files + const aliasFields = options.aliasFields || []; + + // A list of main files in directories + const mainFiles = options.mainFiles || ["index"]; + + // A list of extensions which should be tried for files + let extensions = options.extensions || [".js", ".json", ".node"]; + + // Enforce that a extension from extensions must be used + const enforceExtension = options.enforceExtension || false; + + // A list of module extensions which should be tried for modules + let moduleExtensions = options.moduleExtensions || []; + + // Enforce that a extension from moduleExtensions must be used + const enforceModuleExtension = options.enforceModuleExtension || false; + + // A list of module alias configurations or an object which maps key to value + let alias = options.alias || []; + + // Resolve symlinks to their symlinked location + const symlinks = + typeof options.symlinks !== "undefined" ? options.symlinks : true; + + // Resolve to a context instead of a file + const resolveToContext = options.resolveToContext || false; + + // A list of root paths + const roots = options.roots || []; + + const restrictions = options.restrictions || []; + + // Use this cache object to unsafely cache the successful requests + let unsafeCache = options.unsafeCache || false; + + // Whether or not the unsafeCache should include request context as part of the cache key. + const cacheWithContext = + typeof options.cacheWithContext !== "undefined" + ? options.cacheWithContext + : true; + + // Enable concord description file instructions + const enableConcord = options.concord || false; + + // A function which decides whether a request should be cached or not. + // an object is passed with `path` and `request` properties. + const cachePredicate = + options.cachePredicate || + function() { + return true; + }; + + // The file system which should be used + const fileSystem = options.fileSystem; + + // Use only the sync constiants of the file system calls + const useSyncFileSystemCalls = options.useSyncFileSystemCalls; + + // A prepared Resolver to which the plugins are attached + let resolver = options.resolver; + + //// options processing //// + + if (!resolver) { + resolver = new Resolver( + useSyncFileSystemCalls + ? new SyncAsyncFileSystemDecorator(fileSystem) + : fileSystem + ); + } + + extensions = [].concat(extensions); + moduleExtensions = [].concat(moduleExtensions); + + modules = mergeFilteredToArray([].concat(modules), item => { + return !isAbsolutePath(item); + }); + + mainFields = mainFields.map(item => { + if (typeof item === "string" || Array.isArray(item)) { + item = { + name: item, + forceRelative: true + }; + } + return item; + }); + + if (typeof alias === "object" && !Array.isArray(alias)) { + alias = Object.keys(alias).map(key => { + let onlyModule = false; + let obj = alias[key]; + if (/\$$/.test(key)) { + onlyModule = true; + key = key.substr(0, key.length - 1); + } + if (typeof obj === "string") { + obj = { + alias: obj + }; + } + obj = Object.assign( + { + name: key, + onlyModule: onlyModule + }, + obj + ); + return obj; + }); + } + + if (unsafeCache && typeof unsafeCache !== "object") { + unsafeCache = {}; + } + + //// pipeline //// + + resolver.ensureHook("resolve"); + resolver.ensureHook("parsedResolve"); + resolver.ensureHook("describedResolve"); + resolver.ensureHook("rawModule"); + resolver.ensureHook("module"); + resolver.ensureHook("relative"); + resolver.ensureHook("describedRelative"); + resolver.ensureHook("directory"); + resolver.ensureHook("existingDirectory"); + resolver.ensureHook("undescribedRawFile"); + resolver.ensureHook("rawFile"); + resolver.ensureHook("file"); + resolver.ensureHook("existingFile"); + resolver.ensureHook("resolved"); + + // resolve + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + "resolve", + cachePredicate, + unsafeCache, + cacheWithContext, + "new-resolve" + ) + ); + plugins.push(new ParsePlugin("new-resolve", "parsed-resolve")); + } else { + plugins.push(new ParsePlugin("resolve", "parsed-resolve")); + } + + // parsed-resolve + plugins.push( + new DescriptionFilePlugin( + "parsed-resolve", + descriptionFiles, + "described-resolve" + ) + ); + plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + + // described-resolve + if (alias.length > 0) + plugins.push(new AliasPlugin("described-resolve", alias, "resolve")); + if (enableConcord) { + plugins.push(new ConcordModulesPlugin("described-resolve", {}, "resolve")); + } + aliasFields.forEach(item => { + plugins.push(new AliasFieldPlugin("described-resolve", item, "resolve")); + }); + plugins.push(new ModuleKindPlugin("after-described-resolve", "raw-module")); + roots.forEach(root => { + plugins.push(new RootPlugin("after-described-resolve", root, "relative")); + }); + plugins.push(new JoinRequestPlugin("after-described-resolve", "relative")); + + // raw-module + moduleExtensions.forEach(item => { + plugins.push(new ModuleAppendPlugin("raw-module", item, "module")); + }); + if (!enforceModuleExtension) + plugins.push(new TryNextPlugin("raw-module", null, "module")); + + // module + modules.forEach(item => { + if (Array.isArray(item)) + plugins.push( + new ModulesInHierachicDirectoriesPlugin("module", item, "resolve") + ); + else plugins.push(new ModulesInRootPlugin("module", item, "resolve")); + }); + + // relative + plugins.push( + new DescriptionFilePlugin( + "relative", + descriptionFiles, + "described-relative" + ) + ); + plugins.push(new NextPlugin("after-relative", "described-relative")); + + // described-relative + plugins.push(new FileKindPlugin("described-relative", "raw-file")); + plugins.push( + new TryNextPlugin("described-relative", "as directory", "directory") + ); + + // directory + plugins.push(new DirectoryExistsPlugin("directory", "existing-directory")); + + if (resolveToContext) { + // existing-directory + plugins.push(new NextPlugin("existing-directory", "resolved")); + } else { + // existing-directory + if (enableConcord) { + plugins.push(new ConcordMainPlugin("existing-directory", {}, "resolve")); + } + mainFields.forEach(item => { + plugins.push(new MainFieldPlugin("existing-directory", item, "resolve")); + }); + mainFiles.forEach(item => { + plugins.push( + new UseFilePlugin("existing-directory", item, "undescribed-raw-file") + ); + }); + + // undescribed-raw-file + plugins.push( + new DescriptionFilePlugin( + "undescribed-raw-file", + descriptionFiles, + "raw-file" + ) + ); + plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); + + // raw-file + if (!enforceExtension) { + plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); + } + if (enableConcord) { + plugins.push(new ConcordExtensionsPlugin("raw-file", {}, "file")); + } + extensions.forEach(item => { + plugins.push(new AppendPlugin("raw-file", item, "file")); + }); + + // file + if (alias.length > 0) + plugins.push(new AliasPlugin("file", alias, "resolve")); + if (enableConcord) { + plugins.push(new ConcordModulesPlugin("file", {}, "resolve")); + } + aliasFields.forEach(item => { + plugins.push(new AliasFieldPlugin("file", item, "resolve")); + }); + if (symlinks) plugins.push(new SymlinkPlugin("file", "relative")); + plugins.push(new FileExistsPlugin("file", "existing-file")); + + // existing-file + plugins.push(new NextPlugin("existing-file", "resolved")); + } + + // resolved + if (restrictions.length > 0) { + plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); + } + plugins.push(new ResultPlugin(resolver.hooks.resolved)); + + //// RESOLVER //// + + plugins.forEach(plugin => { + plugin.apply(resolver); + }); + + return resolver; +}; + +function mergeFilteredToArray(array, filter) { + return array.reduce((array, item) => { + if (filter(item)) { + const lastElement = array[array.length - 1]; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + array.push([item]); + } + return array; + } else { + array.push(item); + return array; + } + }, []); +} + +function isAbsolutePath(path) { + return /^[A-Z]:|^\//.test(path); +} + + +/***/ }), + +/***/ 49751: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +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 { + constructor(source, restrictions) { + this.source = source; + this.restrictions = restrictions; + } + + apply(resolver) { + resolver + .getHook(this.source) + .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { + if (typeof request.path === "string") { + const path = request.path; + + for (let i = 0; i < this.restrictions.length; i++) { + const rule = this.restrictions[i]; + 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); + } + } + } + + callback(); + }); + } +}; + + +/***/ }), + +/***/ 19258: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class ResultPlugin { + constructor(source) { + this.source = source; + } + + apply(resolver) { + this.source.tapAsync( + "ResultPlugin", + (request, resolverContext, callback) => { + const obj = Object.assign({}, 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); + }); + } + ); + } +}; + + +/***/ }), + +/***/ 32669: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +class RootPlugin { + /** + * @param {string | ResolveStepHook} source source hook + * @param {Array} root roots + * @param {string | ResolveStepHook} target target hook + */ + constructor(source, root, target) { + this.root = root; + 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("RootPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + if (!req.startsWith("/")) return callback(); + + const path = resolver.join(this.root, req.slice(1)); + const obj = Object.assign(request, { + path, + relativePath: request.relativePath && path + }); + resolver.doResolve( + target, + obj, + `root path ${this.root}`, + resolveContext, + callback + ); + }); + } +} + +module.exports = RootPlugin; + + +/***/ }), + +/***/ 51104: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const getPaths = __webpack_require__(49395); +const forEachBail = __webpack_require__(60059); + +module.exports = class SymlinkPlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { + const pathsResult = getPaths(request.path); + const pathSeqments = pathsResult.seqments; + const paths = pathsResult.paths; + + let containsSymlink = false; + forEachBail.withIndex( + paths, + (path, idx, callback) => { + fs.readlink(path, (err, result) => { + if (!err && result) { + pathSeqments[idx] = result; + containsSymlink = true; + // Shortcut when absolute symlink found + if (/^(\/|[a-zA-Z]:($|\\))/.test(result)) + return callback(null, idx); + } + callback(); + }); + }, + (err, idx) => { + if (!containsSymlink) return callback(); + const resultSeqments = + typeof idx === "number" + ? pathSeqments.slice(0, idx + 1) + : pathSeqments.slice(); + const result = resultSeqments.reverse().reduce((a, b) => { + return resolver.join(a, b); + }); + const obj = Object.assign({}, request, { + path: result + }); + resolver.doResolve( + target, + obj, + "resolved symlink to " + result, + resolveContext, + callback + ); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 83230: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +function SyncAsyncFileSystemDecorator(fs) { + this.fs = fs; + if (fs.statSync) { + this.stat = function(arg, callback) { + let result; + try { + result = fs.statSync(arg); + } catch (e) { + return callback(e); + } + callback(null, result); + }; + } + if (fs.readdirSync) { + this.readdir = function(arg, callback) { + let result; + try { + result = fs.readdirSync(arg); + } catch (e) { + return callback(e); + } + callback(null, result); + }; + } + if (fs.readFileSync) { + this.readFile = function(arg, callback) { + let result; + try { + result = fs.readFileSync(arg); + } catch (e) { + return callback(e); + } + callback(null, result); + }; + } + if (fs.readlinkSync) { + this.readlink = function(arg, callback) { + let result; + try { + result = fs.readlinkSync(arg); + } catch (e) { + return callback(e); + } + callback(null, result); + }; + } + if (fs.readJsonSync) { + this.readJson = function(arg, callback) { + let result; + try { + result = fs.readJsonSync(arg); + } catch (e) { + return callback(e); + } + callback(null, result); + }; + } +} +module.exports = SyncAsyncFileSystemDecorator; + + +/***/ }), + +/***/ 31702: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class TryNextPlugin { + constructor(source, message, target) { + this.source = source; + this.message = message; + this.target = target; + } + + 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 + ); + }); + } +}; + + +/***/ }), + +/***/ 81809: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +function getCacheId(request, withContext) { + return JSON.stringify({ + context: withContext ? request.context : "", + path: request.path, + query: request.query, + request: request.request + }); +} + +module.exports = class UnsafeCachePlugin { + constructor(source, filterPredicate, cache, withContext, target) { + this.source = source; + this.filterPredicate = filterPredicate; + this.withContext = withContext; + this.cache = cache || {}; + this.target = target; + } + + 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(); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 41232: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class UseFilePlugin { + constructor(source, filename, target) { + this.source = source; + this.filename = filename; + this.target = target; + } + + 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 = Object.assign({}, request, { + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, this.filename) + }); + resolver.doResolve( + target, + obj, + "using path: " + filePath, + resolveContext, + callback + ); + }); + } +}; + + +/***/ }), + +/***/ 94323: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const globToRegExp = __webpack_require__(82876)/* .globToRegExp */ .P; + +function parseType(type) { + const items = type.split("+"); + const t = items.shift(); + return { + type: t === "*" ? null : t, + features: items + }; +} + +function isTypeMatched(baseType, testedType) { + if (typeof baseType === "string") baseType = parseType(baseType); + if (typeof testedType === "string") testedType = parseType(testedType); + if (testedType.type && testedType.type !== baseType.type) return false; + return testedType.features.every(requiredFeature => { + return baseType.features.indexOf(requiredFeature) >= 0; + }); +} + +function isResourceTypeMatched(baseType, testedType) { + baseType = baseType.split("/"); + testedType = testedType.split("/"); + if (baseType.length !== testedType.length) return false; + for (let i = 0; i < baseType.length; i++) { + if (!isTypeMatched(baseType[i], testedType[i])) return false; + } + return true; +} + +function isResourceTypeSupported(context, type) { + return ( + context.supportedResourceTypes && + context.supportedResourceTypes.some(supportedType => { + return isResourceTypeMatched(supportedType, type); + }) + ); +} + +function isEnvironment(context, env) { + return ( + context.environments && + context.environments.every(environment => { + return isTypeMatched(environment, env); + }) + ); +} + +const globCache = {}; + +function getGlobRegExp(glob) { + const regExp = globCache[glob] || (globCache[glob] = globToRegExp(glob)); + return regExp; +} + +function matchGlob(glob, relativePath) { + const regExp = getGlobRegExp(glob); + return regExp.exec(relativePath); +} + +function isGlobMatched(glob, relativePath) { + return !!matchGlob(glob, relativePath); +} + +function isConditionMatched(context, condition) { + const items = condition.split("|"); + return items.some(function testFn(item) { + item = item.trim(); + const inverted = /^!/.test(item); + if (inverted) return !testFn(item.substr(1)); + if (/^[a-z]+:/.test(item)) { + // match named condition + const match = /^([a-z]+):\s*/.exec(item); + const value = item.substr(match[0].length); + const name = match[1]; + switch (name) { + case "referrer": + return isGlobMatched(value, context.referrer); + default: + return false; + } + } else if (item.indexOf("/") >= 0) { + // match supported type + return isResourceTypeSupported(context, item); + } else { + // match environment + return isEnvironment(context, item); + } + }); +} + +function isKeyMatched(context, key) { + for (;;) { + const match = /^\[([^\]]+)\]\s*/.exec(key); + if (!match) return key; + key = key.substr(match[0].length); + const condition = match[1]; + if (!isConditionMatched(context, condition)) { + return false; + } + } +} + +function getField(context, configuration, field) { + let value; + Object.keys(configuration).forEach(key => { + const pureKey = isKeyMatched(context, key); + if (pureKey === field) { + value = configuration[key]; + } + }); + return value; +} + +function getMain(context, configuration) { + return getField(context, configuration, "main"); +} + +function getExtensions(context, configuration) { + return getField(context, configuration, "extensions"); +} + +function matchModule(context, configuration, request) { + const modulesField = getField(context, configuration, "modules"); + if (!modulesField) return request; + let newRequest = request; + const keys = Object.keys(modulesField); + let iteration = 0; + let match; + let index; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const pureKey = isKeyMatched(context, key); + match = matchGlob(pureKey, newRequest); + if (match) { + const value = modulesField[key]; + if (typeof value !== "string") { + return value; + } else if (/^\(.+\)$/.test(pureKey)) { + newRequest = newRequest.replace(getGlobRegExp(pureKey), value); + } else { + index = 1; + newRequest = value.replace(/(\/?\*)?\*/g, replaceMatcher); + } + i = -1; + if (iteration++ > keys.length) { + throw new Error("Request '" + request + "' matches recursively"); + } + } + } + return newRequest; + + function replaceMatcher(find) { + switch (find) { + case "/**": { + const m = match[index++]; + return m ? "/" + m : ""; + } + case "**": + case "*": + return match[index++]; + } + } +} + +function matchType(context, configuration, relativePath) { + const typesField = getField(context, configuration, "types"); + if (!typesField) return undefined; + let type; + Object.keys(typesField).forEach(key => { + const pureKey = isKeyMatched(context, key); + if (isGlobMatched(pureKey, relativePath)) { + const value = typesField[key]; + if (!type && /\/\*$/.test(value)) + throw new Error( + "value ('" + + value + + "') of key '" + + key + + "' contains '*', but there is no previous value defined" + ); + type = value.replace(/\/\*$/, "/" + type); + } + }); + return type; +} + +exports.parseType = parseType; +exports.isTypeMatched = isTypeMatched; +exports.isResourceTypeSupported = isResourceTypeSupported; +exports.isEnvironment = isEnvironment; +exports.isGlobMatched = isGlobMatched; +exports.isConditionMatched = isConditionMatched; +exports.isKeyMatched = isKeyMatched; +exports.getField = getField; +exports.getMain = getMain; +exports.getExtensions = getExtensions; +exports.matchModule = matchModule; +exports.matchType = matchType; + + +/***/ }), + +/***/ 6369: +/***/ ((module) => { + +"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; + const childContext = { + log: (() => { + if (!options.log) return undefined; + if (!message) return options.log; + const logFunction = msg => { + if (!messageReported) { + options.log(message); + messageReported = true; + } + options.log(" " + msg); + }; + return logFunction; + })(), + stack: options.stack, + missing: options.missing + }; + return childContext; +}; + + +/***/ }), + +/***/ 60059: +/***/ ((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 currentPos = array.length; + let currentResult; + let done = []; + for (let i = 0; i < array.length; i++) { + const itCb = createIteratorCallback(i); + iterator(array[i], itCb); + if (currentPos === 0) break; + } + + function createIteratorCallback(i) { + return (...args) => { + if (i >= currentPos) return; // ignore + done.push(i); + if (args.length > 0) { + currentPos = i + 1; + done = done.filter(item => { + return item <= i; + }); + currentResult = args; + } + if (done.length === currentPos) { + callback.apply(null, currentResult); + currentPos = 0; + } + }; + } +}; + +module.exports.withIndex = function forEachBailWithIndex( + array, + iterator, + callback +) { + if (array.length === 0) return callback(); + let currentPos = array.length; + let currentResult; + let done = []; + for (let i = 0; i < array.length; i++) { + const itCb = createIteratorCallback(i); + iterator(array[i], i, itCb); + if (currentPos === 0) break; + } + + function createIteratorCallback(i) { + return (...args) => { + if (i >= currentPos) return; // ignore + done.push(i); + if (args.length > 0) { + currentPos = i + 1; + done = done.filter(item => { + return item <= i; + }); + currentResult = args; + } + if (done.length === currentPos) { + callback.apply(null, currentResult); + currentPos = 0; + } + }; + } +}; + + +/***/ }), + +/***/ 91878: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) + return request.__innerRequest; + 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); +}; + + +/***/ }), + +/***/ 49395: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +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.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; +}; + + +/***/ }), + +/***/ 82876: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +function globToRegExp(glob) { + // * [^\\\/]* + // /**/ /.+/ + // ^* \./.+ (concord special) + // ? [^\\\/] + // [!...] [^...] + // [^...] [^...] + // / [\\\/] + // {...,...} (...|...) + // ?(...|...) (...|...)? + // +(...|...) (...|...)+ + // *(...|...) (...|...)* + // @(...|...) (...|...) + if (/^\(.+\)$/.test(glob)) { + // allow to pass an RegExp in brackets + return new RegExp(glob.substr(1, glob.length - 2)); + } + const tokens = tokenize(glob); + const process = createRoot(); + const regExpStr = tokens.map(process).join(""); + return new RegExp("^" + regExpStr + "$"); +} + +const SIMPLE_TOKENS = { + "@(": "one", + "?(": "zero-one", + "+(": "one-many", + "*(": "zero-many", + "|": "segment-sep", + "/**/": "any-path-segments", + "**": "any-path", + "*": "any-path-segment", + "?": "any-char", + "{": "or", + "/": "path-sep", + ",": "comma", + ")": "closing-segment", + "}": "closing-or" +}; + +function tokenize(glob) { + return glob + .split( + /([@?+*]\(|\/\*\*\/|\*\*|[?*]|\[[!^]?(?:[^\]\\]|\\.)+\]|\{|,|\/|[|)}])/g + ) + .map(item => { + if (!item) return null; + const t = SIMPLE_TOKENS[item]; + if (t) { + return { + type: t + }; + } + if (item[0] === "[") { + if (item[1] === "^" || item[1] === "!") { + return { + type: "inverted-char-set", + value: item.substr(2, item.length - 3) + }; + } else { + return { + type: "char-set", + value: item.substr(1, item.length - 2) + }; + } + } + return { + type: "string", + value: item + }; + }) + .filter(Boolean) + .concat({ + type: "end" + }); +} + +function createRoot() { + const inOr = []; + const process = createSeqment(); + let initial = true; + return function(token) { + switch (token.type) { + case "or": + inOr.push(initial); + return "("; + case "comma": + if (inOr.length) { + initial = inOr[inOr.length - 1]; + return "|"; + } else { + return process( + { + type: "string", + value: "," + }, + initial + ); + } + case "closing-or": + if (inOr.length === 0) throw new Error("Unmatched '}'"); + inOr.pop(); + return ")"; + case "end": + if (inOr.length) throw new Error("Unmatched '{'"); + return process(token, initial); + default: { + const result = process(token, initial); + initial = false; + return result; + } + } + }; +} + +function createSeqment() { + const inSeqment = []; + const process = createSimple(); + return function(token, initial) { + switch (token.type) { + case "one": + case "one-many": + case "zero-many": + case "zero-one": + inSeqment.push(token.type); + return "("; + case "segment-sep": + if (inSeqment.length) { + return "|"; + } else { + return process( + { + type: "string", + value: "|" + }, + initial + ); + } + case "closing-segment": { + const segment = inSeqment.pop(); + switch (segment) { + case "one": + return ")"; + case "one-many": + return ")+"; + case "zero-many": + return ")*"; + case "zero-one": + return ")?"; + } + throw new Error("Unexcepted segment " + segment); + } + case "end": + if (inSeqment.length > 0) { + throw new Error("Unmatched segment, missing ')'"); + } + return process(token, initial); + default: + return process(token, initial); + } + }; +} + +function createSimple() { + return function(token, initial) { + switch (token.type) { + case "path-sep": + return "[\\\\/]+"; + case "any-path-segments": + return "[\\\\/]+(?:(.+)[\\\\/]+)?"; + case "any-path": + return "(.*)"; + case "any-path-segment": + if (initial) { + return "\\.[\\\\/]+(?:.*[\\\\/]+)?([^\\\\/]+)"; + } else { + return "([^\\\\/]*)"; + } + case "any-char": + return "[^\\\\/]"; + case "inverted-char-set": + return "[^" + token.value + "]"; + case "char-set": + return "[" + token.value + "]"; + case "string": + return token.value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + case "end": + return ""; + default: + throw new Error("Unsupported token '" + token.type + "'"); + } + }; +} + +exports.P = globToRegExp; + + +/***/ }), + +/***/ 87450: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ResolverFactory = __webpack_require__(34129); + +const NodeJsInputFileSystem = __webpack_require__(13445); +const CachedInputFileSystem = __webpack_require__(75544); + +const nodeFileSystem = new CachedInputFileSystem( + new NodeJsInputFileSystem(), + 4000 +); + +const nodeContext = { + environments: ["node+es3+es5+process+native"] +}; + +const asyncResolver = ResolverFactory.createResolver({ + extensions: [".js", ".json", ".node"], + fileSystem: nodeFileSystem +}); +module.exports = 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({ + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +module.exports.sync = function resolveSync(context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncResolver.resolveSync(context, path, request); +}; + +const asyncContextResolver = ResolverFactory.createResolver({ + extensions: [".js", ".json", ".node"], + resolveToContext: true, + fileSystem: nodeFileSystem +}); +module.exports.context = function resolveContext( + 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; + } + asyncContextResolver.resolve( + context, + path, + request, + resolveContext, + callback + ); +}; + +const syncContextResolver = ResolverFactory.createResolver({ + extensions: [".js", ".json", ".node"], + resolveToContext: true, + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +module.exports.context.sync = function resolveContextSync( + context, + path, + request +) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncContextResolver.resolveSync(context, path, request); +}; + +const asyncLoaderResolver = ResolverFactory.createResolver({ + extensions: [".js", ".json", ".node"], + moduleExtensions: ["-loader"], + mainFields: ["loader", "main"], + fileSystem: nodeFileSystem +}); +module.exports.loader = function resolveLoader( + 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; + } + asyncLoaderResolver.resolve(context, path, request, resolveContext, callback); +}; + +const syncLoaderResolver = ResolverFactory.createResolver({ + extensions: [".js", ".json", ".node"], + moduleExtensions: ["-loader"], + mainFields: ["loader", "main"], + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +module.exports.loader.sync = function resolveLoaderSync( + context, + path, + request +) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncLoaderResolver.resolveSync(context, path, request); +}; + +module.exports.create = function create(options) { + options = Object.assign( + { + fileSystem: nodeFileSystem + }, + options + ); + 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); + }; +}; + +module.exports.create.sync = function createSync(options) { + options = Object.assign( + { + 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); + }; +}; + +// Export Resolver, FileSystems and Plugins +module.exports.ResolverFactory = ResolverFactory; + +module.exports.NodeJsInputFileSystem = NodeJsInputFileSystem; +module.exports.CachedInputFileSystem = CachedInputFileSystem; + + +/***/ }), + +/***/ 65775: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const normalize = __webpack_require__(69038); + +const absoluteWinRegExp = /^[A-Z]:([\\\/]|$)/i; +const absoluteNixRegExp = /^\//i; + +module.exports = function join(path, request) { + if(!request) return normalize(path); + if(absoluteWinRegExp.test(request)) return normalize(request.replace(/\//g, "\\")); + if(absoluteNixRegExp.test(request)) return normalize(request); + if(path == "/") return normalize(path + request); + if(absoluteWinRegExp.test(path)) return normalize(path.replace(/\//g, "\\") + "\\" + request.replace(/\//g, "\\")); + if(absoluteNixRegExp.test(path)) return normalize(path + "/" + request); + return normalize(path + "/" + request); +}; + + +/***/ }), + +/***/ 69038: +/***/ ((module) => { + +"use strict"; + + +// eslint-disable-next-line complexity +module.exports = function normalize(path) { + var parts = path.split(/(\\+|\/+)/); + if(parts.length === 1) + return path; + var result = []; + var absolutePathStart = 0; + for(var i = 0, sep = false; i < parts.length; i += 1, sep = !sep) { + var part = parts[i]; + if(i === 0 && /^([A-Z]:)?$/i.test(part)) { + result.push(part); + absolutePathStart = 2; + } else if(sep) { + // UNC paths on Windows begin with a double backslash. + if (i === 1 && parts[0].length === 0 && part === "\\\\") { + result.push(part); + } else { + result.push(part[0]); + } + } else if(part === "..") { + switch(result.length) { + case 0: + // i. e. ".." => ".." + // i. e. "../a/b/c" => "../a/b/c" + result.push(part); + break; + case 2: + // i. e. "a/.." => "" + // i. e. "/.." => "/" + // i. e. "C:\.." => "C:\" + // i. e. "a/../b/c" => "b/c" + // i. e. "/../b/c" => "/b/c" + // i. e. "C:\..\a\b\c" => "C:\a\b\c" + if (result[0] !== ".") { + i += 1; + sep = !sep; + result.length = absolutePathStart; + } else { + result.length = 0; + result.push(part); + } + break; + case 4: + // i. e. "a/b/.." => "a" + // i. e. "/a/.." => "/" + // i. e. "C:\a\.." => "C:\" + // i. e. "/a/../b/c" => "/b/c" + if(absolutePathStart === 0) { + result.length -= 3; + } else { + i += 1; + sep = !sep; + result.length = 2; + } + break; + default: + // i. e. "/a/b/.." => "/a" + // i. e. "/a/b/../c" => "/a/c" + result.length -= 3; + break; + } + } else if(part === ".") { + switch(result.length) { + case 0: + // i. e. "." => "." + // i. e. "./a/b/c" => "./a/b/c" + result.push(part); + break; + case 2: + // i. e. "a/." => "a" + // i. e. "/." => "/" + // i. e. "C:\." => "C:\" + // i. e. "C:\.\a\b\c" => "C:\a\b\c" + if(absolutePathStart === 0) { + result.length -= 1; + } else { + i += 1; + sep = !sep; + } + break; + default: + // i. e. "a/b/." => "a/b" + // i. e. "/a/." => "/" + // i. e. "C:\a\." => "C:\" + // i. e. "a/./b/c" => "a/b/c" + // i. e. "/a/./b/c" => "/a/b/c" + result.length -= 1; + break; + } + } else if(part) { + result.push(part); + } + } + if(result.length === 1 && /^[A-Za-z]:$/.test(result[0])) + return result[0] + "\\"; + return result.join(""); +}; + + +/***/ }), + +/***/ 81744: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var prr = __webpack_require__(59570) + +function init (type, message, cause) { + if (!!message && typeof message != 'string') { + message = message.message || message.name + } + prr(this, { + type : type + , name : type + // can be passed just a 'cause' + , cause : typeof message != 'string' ? message : cause + , message : message + }, 'ewr') +} + +// generic prototype, not intended to be actually used - helpful for `instanceof` +function CustomError (message, cause) { + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, this.constructor) + init.call(this, 'CustomError', message, cause) +} + +CustomError.prototype = new Error() + +function createError (errno, type, proto) { + var err = function (message, cause) { + init.call(this, type, message, cause) + //TODO: the specificity here is stupid, errno should be available everywhere + if (type == 'FilesystemError') { + this.code = this.cause.code + this.path = this.cause.path + this.errno = this.cause.errno + this.message = + (errno.errno[this.cause.errno] + ? errno.errno[this.cause.errno].description + : this.cause.message) + + (this.cause.path ? ' [' + this.cause.path + ']' : '') + } + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, err) + } + err.prototype = !!proto ? new proto() : new CustomError() + return err +} + +module.exports = function (errno) { + var ce = function (type, proto) { + return createError(errno, type, proto) + } + return { + CustomError : CustomError + , FilesystemError : ce('FilesystemError') + , createError : ce + } +} + + +/***/ }), + +/***/ 48916: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var all = module.exports.all = [ + { + errno: -2, + code: 'ENOENT', + description: 'no such file or directory' + }, + { + errno: -1, + code: 'UNKNOWN', + description: 'unknown error' + }, + { + errno: 0, + code: 'OK', + description: 'success' + }, + { + errno: 1, + code: 'EOF', + description: 'end of file' + }, + { + errno: 2, + code: 'EADDRINFO', + description: 'getaddrinfo error' + }, + { + errno: 3, + code: 'EACCES', + description: 'permission denied' + }, + { + errno: 4, + code: 'EAGAIN', + description: 'resource temporarily unavailable' + }, + { + errno: 5, + code: 'EADDRINUSE', + description: 'address already in use' + }, + { + errno: 6, + code: 'EADDRNOTAVAIL', + description: 'address not available' + }, + { + errno: 7, + code: 'EAFNOSUPPORT', + description: 'address family not supported' + }, + { + errno: 8, + code: 'EALREADY', + description: 'connection already in progress' + }, + { + errno: 9, + code: 'EBADF', + description: 'bad file descriptor' + }, + { + errno: 10, + code: 'EBUSY', + description: 'resource busy or locked' + }, + { + errno: 11, + code: 'ECONNABORTED', + description: 'software caused connection abort' + }, + { + errno: 12, + code: 'ECONNREFUSED', + description: 'connection refused' + }, + { + errno: 13, + code: 'ECONNRESET', + description: 'connection reset by peer' + }, + { + errno: 14, + code: 'EDESTADDRREQ', + description: 'destination address required' + }, + { + errno: 15, + code: 'EFAULT', + description: 'bad address in system call argument' + }, + { + errno: 16, + code: 'EHOSTUNREACH', + description: 'host is unreachable' + }, + { + errno: 17, + code: 'EINTR', + description: 'interrupted system call' + }, + { + errno: 18, + code: 'EINVAL', + description: 'invalid argument' + }, + { + errno: 19, + code: 'EISCONN', + description: 'socket is already connected' + }, + { + errno: 20, + code: 'EMFILE', + description: 'too many open files' + }, + { + errno: 21, + code: 'EMSGSIZE', + description: 'message too long' + }, + { + errno: 22, + code: 'ENETDOWN', + description: 'network is down' + }, + { + errno: 23, + code: 'ENETUNREACH', + description: 'network is unreachable' + }, + { + errno: 24, + code: 'ENFILE', + description: 'file table overflow' + }, + { + errno: 25, + code: 'ENOBUFS', + description: 'no buffer space available' + }, + { + errno: 26, + code: 'ENOMEM', + description: 'not enough memory' + }, + { + errno: 27, + code: 'ENOTDIR', + description: 'not a directory' + }, + { + errno: 28, + code: 'EISDIR', + description: 'illegal operation on a directory' + }, + { + errno: 29, + code: 'ENONET', + description: 'machine is not on the network' + }, + { + errno: 31, + code: 'ENOTCONN', + description: 'socket is not connected' + }, + { + errno: 32, + code: 'ENOTSOCK', + description: 'socket operation on non-socket' + }, + { + errno: 33, + code: 'ENOTSUP', + description: 'operation not supported on socket' + }, + { + errno: 34, + code: 'ENOENT', + description: 'no such file or directory' + }, + { + errno: 35, + code: 'ENOSYS', + description: 'function not implemented' + }, + { + errno: 36, + code: 'EPIPE', + description: 'broken pipe' + }, + { + errno: 37, + code: 'EPROTO', + description: 'protocol error' + }, + { + errno: 38, + code: 'EPROTONOSUPPORT', + description: 'protocol not supported' + }, + { + errno: 39, + code: 'EPROTOTYPE', + description: 'protocol wrong type for socket' + }, + { + errno: 40, + code: 'ETIMEDOUT', + description: 'connection timed out' + }, + { + errno: 41, + code: 'ECHARSET', + description: 'invalid Unicode character' + }, + { + errno: 42, + code: 'EAIFAMNOSUPPORT', + description: 'address family for hostname not supported' + }, + { + errno: 44, + code: 'EAISERVICE', + description: 'servname not supported for ai_socktype' + }, + { + errno: 45, + code: 'EAISOCKTYPE', + description: 'ai_socktype not supported' + }, + { + errno: 46, + code: 'ESHUTDOWN', + description: 'cannot send after transport endpoint shutdown' + }, + { + errno: 47, + code: 'EEXIST', + description: 'file already exists' + }, + { + errno: 48, + code: 'ESRCH', + description: 'no such process' + }, + { + errno: 49, + code: 'ENAMETOOLONG', + description: 'name too long' + }, + { + errno: 50, + code: 'EPERM', + description: 'operation not permitted' + }, + { + errno: 51, + code: 'ELOOP', + description: 'too many symbolic links encountered' + }, + { + errno: 52, + code: 'EXDEV', + description: 'cross-device link not permitted' + }, + { + errno: 53, + code: 'ENOTEMPTY', + description: 'directory not empty' + }, + { + errno: 54, + code: 'ENOSPC', + description: 'no space left on device' + }, + { + errno: 55, + code: 'EIO', + description: 'i/o error' + }, + { + errno: 56, + code: 'EROFS', + description: 'read-only file system' + }, + { + errno: 57, + code: 'ENODEV', + description: 'no such device' + }, + { + errno: 58, + code: 'ESPIPE', + description: 'invalid seek' + }, + { + errno: 59, + code: 'ECANCELED', + description: 'operation canceled' + } +] + +module.exports.errno = {} +module.exports.code = {} + +all.forEach(function (error) { + module.exports.errno[error.errno] = error + module.exports.code[error.code] = error +}) + +module.exports.custom = __webpack_require__(81744)(module.exports) +module.exports.create = module.exports.custom.createError + + +/***/ }), + +/***/ 64352: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + 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__(40379); + + 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 || {}; + + 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; + } + } + + /* 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; + } + + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } + + 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); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = __webpack_require__(25916).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 : */ + + +/***/ }), + +/***/ 40379: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + 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; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + 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; + } + + 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' + }; + + 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'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + 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; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + 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); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // 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; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // 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; + + 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; + }; + + // 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); + }; + + // 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; + } + + 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; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + 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)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + 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 + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + 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)); + } + } + } + } + }; + + 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; + + // 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.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, 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); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + 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; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + 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); + + 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 + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + 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); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + 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]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + 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)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + 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; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + 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__(35464)/* .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 : */ + + +/***/ }), + +/***/ 67913: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(44102); +var parsers = __webpack_require__(97129); + +/** + * Module dependencies + */ + +var debug = __webpack_require__(31185)('expand-brackets'); +var extend = __webpack_require__(28727); +var Snapdragon = __webpack_require__(79285); +var toRegex = __webpack_require__(51279); + +/** + * Parses the given POSIX character class `pattern` and returns a + * string that can be used for creating regular expressions for matching. + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public + */ + +function brackets(pattern, options) { + debug('initializing from <%s>', __filename); + var res = brackets.create(pattern, options); + return res.output; +} + +/** + * Takes an array of strings and a POSIX character class pattern, and returns a new + * array with only the strings that matched the pattern. + * + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]')); + * //=> ['a'] + * + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+')); + * //=> ['a', 'ab'] + * ``` + * @param {Array} `arr` Array of strings to match + * @param {String} `pattern` POSIX character class pattern(s) + * @param {Object} `options` + * @return {Array} + * @api public + */ + +brackets.match = function(arr, pattern, options) { + arr = [].concat(arr); + var opts = extend({}, options); + var isMatch = brackets.matcher(pattern, opts); + var len = arr.length; + var idx = -1; + var res = []; + + while (++idx < len) { + var ele = arr[idx]; + if (isMatch(ele)) { + res.push(ele); + } + } + + if (res.length === 0) { + if (opts.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + + if (opts.nonull === true || opts.nullglob === true) { + return [pattern.split('\\').join('')]; + } + } + return res; +}; + +/** + * Returns true if the specified `string` matches the given + * brackets `pattern`. + * + * ```js + * var brackets = require('expand-brackets'); + * + * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]')); + * //=> true + * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ + +brackets.isMatch = function(str, pattern, options) { + return brackets.matcher(pattern, options)(str); +}; + +/** + * Takes a POSIX character class pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. + * + * ```js + * var brackets = require('expand-brackets'); + * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.A')); + * //=> true + * ``` + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ + +brackets.matcher = function(pattern, options) { + var re = brackets.makeRe(pattern, options); + return function(str) { + return re.test(str); + }; +}; + +/** + * Create a regular expression from the given `pattern`. + * + * ```js + * var brackets = require('expand-brackets'); + * var re = brackets.makeRe('[[:alpha:]]'); + * console.log(re); + * //=> /^(?:[a-zA-Z])$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +brackets.makeRe = function(pattern, options) { + var res = brackets.create(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(res.output, opts); +}; + +/** + * Parses the given POSIX character class `pattern` and returns an object + * with the compiled `output` and optional source `map`. + * + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets('[[:alpha:]]')); + * // { options: { source: 'string' }, + * // input: '[[:alpha:]]', + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // not: [Function], + * // escape: [Function], + * // text: [Function], + * // posix: [Function], + * // bracket: [Function], + * // 'bracket.open': [Function], + * // 'bracket.inner': [Function], + * // 'bracket.literal': [Function], + * // 'bracket.close': [Function] }, + * // output: '[a-zA-Z]', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: [ [Object], [Object], [Object] ] }, + * // parsingErrors: [] } + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public + */ + +brackets.create = function(pattern, options) { + var snapdragon = (options && options.snapdragon) || new Snapdragon(options); + compilers(snapdragon); + parsers(snapdragon); + + var ast = snapdragon.parse(pattern, options); + ast.input = pattern; + var res = snapdragon.compile(ast, options); + res.input = pattern; + return res; +}; + +/** + * Expose `brackets` constructor, parsers and compilers + */ + +brackets.compilers = compilers; +brackets.parsers = parsers; + +/** + * Expose `brackets` + * @type {Function} + */ + +module.exports = brackets; + + +/***/ }), + +/***/ 44102: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var posix = __webpack_require__(88412); + +module.exports = function(brackets) { + brackets.compiler + + /** + * Escaped characters + */ + + .set('escape', function(node) { + return this.emit('\\' + node.val.replace(/^\\/, ''), node); + }) + + /** + * Text + */ + + .set('text', function(node) { + return this.emit(node.val.replace(/([{}])/g, '\\$1'), node); + }) + + /** + * POSIX character classes + */ + + .set('posix', function(node) { + if (node.val === '[::]') { + return this.emit('\\[::\\]', node); + } + + var val = posix[node.inner]; + if (typeof val === 'undefined') { + val = '[' + node.inner + ']'; + } + return this.emit(val, node); + }) + + /** + * Non-posix brackets + */ + + .set('bracket', function(node) { + return this.mapVisit(node.nodes); + }) + .set('bracket.open', function(node) { + return this.emit(node.val, node); + }) + .set('bracket.inner', function(node) { + var inner = node.val; + + if (inner === '[' || inner === ']') { + return this.emit('\\' + node.val, node); + } + if (inner === '^]') { + return this.emit('^\\]', node); + } + if (inner === '^') { + return this.emit('^', node); + } + + if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) { + inner = inner.split('-').join('\\-'); + } + + var isNegated = inner.charAt(0) === '^'; + // add slashes to negated brackets, per spec + if (isNegated && inner.indexOf('/') === -1) { + inner += '/'; + } + if (isNegated && inner.indexOf('.') === -1) { + inner += '.'; + } + + // don't unescape `0` (octal literal) + inner = inner.replace(/\\([1-9])/g, '$1'); + return this.emit(inner, node); + }) + .set('bracket.close', function(node) { + var val = node.val.replace(/^\\/, ''); + if (node.parent.escaped === true) { + return this.emit('\\' + val, node); + } + return this.emit(val, node); + }); +}; + + +/***/ }), + +/***/ 97129: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(34467); +var define = __webpack_require__(5477); + +/** + * Text regex + */ + +var TEXT_REGEX = '(\\[(?=.*\\])|\\])+'; +var not = utils.createRegex(TEXT_REGEX); + +/** + * Brackets parsers + */ + +function parsers(brackets) { + brackets.state = brackets.state || {}; + brackets.parser.sets.bracket = brackets.parser.sets.bracket || []; + brackets.parser + + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; + + return pos({ + type: 'escape', + val: m[0] + }); + }) + + /** + * Text parser + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; + + return pos({ + type: 'text', + val: m[0] + }); + }) + + /** + * POSIX character classes: "[[:alpha:][:digits:]]" + */ + + .capture('posix', function() { + var pos = this.position(); + var m = this.match(/^\[:(.*?):\](?=.*\])/); + if (!m) return; + + var inside = this.isInside('bracket'); + if (inside) { + brackets.posix++; + } + + return pos({ + type: 'posix', + insideBracket: inside, + inner: m[1], + val: m[0] + }); + }) + + /** + * Bracket (noop) + */ + + .capture('bracket', function() {}) + + /** + * Open: '[' + */ + + .capture('bracket.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\[(?=.*\])/); + if (!m) return; + + var prev = this.prev(); + var last = utils.last(prev.nodes); + + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); + return pos({ + type: 'escape', + val: m[0] + }); + } + + var open = pos({ + type: 'bracket.open', + val: m[0] + }); + + if (last.type === 'bracket.open' || this.isInside('bracket')) { + open.val = '\\' + open.val; + open.type = 'bracket.inner'; + open.escaped = true; + return open; + } + + var node = pos({ + type: 'bracket', + nodes: [open] + }); + + define(node, 'parent', prev); + define(open, 'parent', node); + this.push('bracket', node); + prev.nodes.push(node); + }) + + /** + * Bracket text + */ + + .capture('bracket.inner', function() { + if (!this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; + + var next = this.input.charAt(0); + var val = m[0]; + + var node = pos({ + type: 'bracket.inner', + val: val + }); + + if (val === '\\\\') { + return node; + } + + var first = val.charAt(0); + var last = val.slice(-1); + + if (first === '!') { + val = '^' + val.slice(1); + } + + if (last === '\\' || (val === '^' && next === ']')) { + val += this.input[0]; + this.consume(1); + } + + node.val = val; + return node; + }) + + /** + * Close: ']' + */ + + .capture('bracket.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\]/); + if (!m) return; + + var prev = this.prev(); + var last = utils.last(prev.nodes); + + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); + + return pos({ + type: 'escape', + val: m[0] + }); + } + + var node = pos({ + type: 'bracket.close', + rest: this.input, + val: m[0] + }); + + if (last.type === 'bracket.open') { + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } + + var bracket = this.pop('bracket'); + if (!this.isType(bracket, 'bracket')) { + if (this.options.strict) { + throw new Error('missing opening "["'); + } + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } + + bracket.nodes.push(node); + define(node, 'parent', bracket); + }); +} + +/** + * Brackets parsers + */ + +module.exports = parsers; + +/** + * Expose text regex + */ + +module.exports.TEXT_REGEX = TEXT_REGEX; + + +/***/ }), + +/***/ 34467: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var toRegex = __webpack_require__(51279); +var regexNot = __webpack_require__(30931); +var cached; + +/** + * Get the last element from `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr) { + return arr[arr.length - 1]; +}; + +/** + * Create and cache regex to use for text nodes + */ + +exports.createRegex = function(pattern, include) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re; + + if (typeof include === 'string') { + re = toRegex('^(?:' + include + '|' + not + ')', opts); + } else { + re = toRegex(not, opts); + } + + return (cached = re); +}; + + +/***/ }), + +/***/ 28727: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isObject = __webpack_require__(18493); + +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); + } + } + return o; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + + +/***/ }), + +/***/ 66675: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +var extend = __webpack_require__(28727); +var unique = __webpack_require__(19009); +var toRegex = __webpack_require__(51279); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(90752); +var parsers = __webpack_require__(32269); +var Extglob = __webpack_require__(31052); +var utils = __webpack_require__(91439); +var MAX_LENGTH = 1024 * 64; + +/** + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob('*.!(*a)')); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public + */ + +function extglob(pattern, options) { + return extglob.create(pattern, options).output; +} + +/** + * Takes an array of strings and an extglob pattern and returns a new + * array that contains only the strings that match the pattern. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)')); + * //=> ['a.b', 'a.c'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Extglob pattern + * @param {Object} `options` + * @return {Array} Returns an array of matches + * @api public + */ + +extglob.match = function(list, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + list = utils.arrayify(list); + var isMatch = extglob.matcher(pattern, options); + var len = list.length; + var idx = -1; + var matches = []; + + while (++idx < len) { + var ele = list[idx]; + + if (isMatch(ele)) { + matches.push(ele); + } + } + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return unique(matches); + } + + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [pattern.split('\\').join('')]; + } + } + + return options.nodupes !== false ? unique(matches) : matches; +}; + +/** + * Returns true if the specified `string` matches the given + * extglob `pattern`. + * + * ```js + * var extglob = require('extglob'); + * + * console.log(extglob.isMatch('a.a', '*.!(*a)')); + * //=> false + * console.log(extglob.isMatch('a.b', '*.!(*a)')); + * //=> true + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ + +extglob.isMatch = function(str, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern === str) { + return true; + } + + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } + + var isMatch = utils.memoize('isMatch', pattern, options, extglob.matcher); + return isMatch(str); +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but + * the pattern can match any part of the string. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(extglob.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + +extglob.contains = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } + + var opts = extend({}, options, {contains: true}); + opts.strictClose = false; + opts.strictOpen = false; + return extglob.isMatch(str, pattern, opts); +}; + +/** + * Takes an extglob pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. + * + * ```js + * var extglob = require('extglob'); + * var isMatch = extglob.matcher('*.!(*a)'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ + +extglob.matcher = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + function matcher() { + var re = extglob.makeRe(pattern, options); + return function(str) { + return re.test(str); + }; + } + + return utils.memoize('matcher', pattern, options, matcher); +}; + +/** + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.create('*.!(*a)').output); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +extglob.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + function create() { + var ext = new Extglob(options); + var ast = ext.parse(pattern, options); + return ext.compile(ast, options); + } + + return utils.memoize('create', pattern, options, create); +}; + +/** + * Returns an array of matches captured by `pattern` in `string`, or `null` + * if the pattern did not match. + * + * ```js + * var extglob = require('extglob'); + * extglob.capture(pattern, string[, options]); + * + * console.log(extglob.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(extglob.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ + +extglob.capture = function(pattern, str, options) { + var re = extglob.makeRe(pattern, extend({capture: true}, options)); + + function match() { + return function(string) { + var match = re.exec(string); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = utils.memoize('capture', pattern, options, match); + return capture(str); +}; + +/** + * Create a regular expression from the given `pattern` and `options`. + * + * ```js + * var extglob = require('extglob'); + * var re = extglob.makeRe('*.!(*a)'); + * console.log(re); + * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +extglob.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function makeRe() { + var opts = extend({strictErrors: false}, options); + if (opts.strictErrors === true) opts.strict = true; + var res = extglob.create(pattern, opts); + return toRegex(res.output, opts); + } + + var regex = utils.memoize('makeRe', pattern, options, makeRe); + if (regex.source.length > MAX_LENGTH) { + throw new SyntaxError('potentially malicious regex detected'); + } + + return regex; +}; + +/** + * Cache + */ + +extglob.cache = utils.cache; +extglob.clearCache = function() { + extglob.cache.__data__ = {}; +}; + +/** + * Expose `Extglob` constructor, parsers and compilers + */ + +extglob.Extglob = Extglob; +extglob.compilers = compilers; +extglob.parsers = parsers; + +/** + * Expose `extglob` + * @type {Function} + */ + +module.exports = extglob; + + +/***/ }), + +/***/ 90752: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var brackets = __webpack_require__(67913); + +/** + * Extglob compilers + */ + +module.exports = function(extglob) { + function star() { + if (typeof extglob.options.star === 'function') { + return extglob.options.star.apply(this, arguments); + } + if (typeof extglob.options.star === 'string') { + return extglob.options.star; + } + return '.*?'; + } + + /** + * Use `expand-brackets` compilers + */ + + extglob.use(brackets.compilers); + extglob.compiler + + /** + * Escaped: "\\*" + */ + + .set('escape', function(node) { + return this.emit(node.val, node); + }) + + /** + * Dot: "." + */ + + .set('dot', function(node) { + return this.emit('\\' + node.val, node); + }) + + /** + * Question mark: "?" + */ + + .set('qmark', function(node) { + var val = '[^\\\\/.]'; + var prev = this.prev(); + + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch !== '!' && ch !== '=' && ch !== ':') { + return this.emit(val, node); + } + return this.emit(node.val, node); + } + + if (prev.type === 'text' && prev.val) { + return this.emit(val, node); + } + + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) + + /** + * Plus: "+" + */ + + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); + } + var ch = this.output.slice(-1); + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) + + /** + * Star: "*" + */ + + .set('star', function(node) { + var prev = this.prev(); + var prefix = prev.type !== 'text' && prev.type !== 'escape' + ? '(?!\\.)' + : ''; + + return this.emit(prefix + star.call(this, node), node); + }) + + /** + * Parens + */ + + .set('paren', function(node) { + return this.mapVisit(node.nodes); + }) + .set('paren.open', function(node) { + var capture = this.options.capture ? '(' : ''; + + switch (node.parent.prefix) { + case '!': + case '^': + return this.emit(capture + '(?:(?!(?:', node); + case '*': + case '+': + case '?': + case '@': + return this.emit(capture + '(?:', node); + default: { + var val = node.val; + if (this.options.bash === true) { + val = '\\' + val; + } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') { + val += '?:'; + } + + return this.emit(val, node); + } + } + }) + .set('paren.close', function(node) { + var capture = this.options.capture ? ')' : ''; + + switch (node.prefix) { + case '!': + case '^': + var prefix = /^(\)|$)/.test(node.rest) ? '$' : ''; + var str = star.call(this, node); + + // if the extglob has a slash explicitly defined, we know the user wants + // to match slashes, so we need to ensure the "star" regex allows for it + if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) { + str = '.*?'; + } + + return this.emit(prefix + ('))' + str + ')') + capture, node); + case '*': + case '+': + case '?': + return this.emit(')' + node.prefix + capture, node); + case '@': + return this.emit(')' + capture, node); + default: { + var val = (this.options.bash === true ? '\\' : '') + ')'; + return this.emit(val, node); + } + } + }) + + /** + * Text + */ + + .set('text', function(node) { + var val = node.val.replace(/[\[\]]/g, '\\$&'); + return this.emit(val, node); + }); +}; + + +/***/ }), + +/***/ 31052: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +var Snapdragon = __webpack_require__(79285); +var define = __webpack_require__(62250); +var extend = __webpack_require__(28727); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(90752); +var parsers = __webpack_require__(32269); + +/** + * Customize Snapdragon parser and renderer + */ + +function Extglob(options) { + this.options = extend({source: 'extglob'}, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(this.options); + this.snapdragon.patterns = this.snapdragon.patterns || {}; + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; + + compilers(this.snapdragon); + parsers(this.snapdragon); + + /** + * Override Snapdragon `.parse` method + */ + + define(this.snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strict !== true) { + var node = last.nodes[0]; + node.val = '\\' + node.val; + var sibling = node.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; + }); + + /** + * Decorate `.parse` method + */ + + define(this, 'parse', function(ast, options) { + return this.snapdragon.parse.apply(this.snapdragon, arguments); + }); + + /** + * Decorate `.compile` method + */ + + define(this, 'compile', function(ast, options) { + return this.snapdragon.compile.apply(this.snapdragon, arguments); + }); + +} + +/** + * Expose `Extglob` + */ + +module.exports = Extglob; + + +/***/ }), + +/***/ 32269: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var brackets = __webpack_require__(67913); +var define = __webpack_require__(62250); +var utils = __webpack_require__(91439); + +/** + * Characters to use in text regex (we want to "not" match + * characters that are matched by other parsers) + */ + +var TEXT_REGEX = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+'; +var not = utils.createRegex(TEXT_REGEX); + +/** + * Extglob parsers + */ + +function parsers(extglob) { + extglob.state = extglob.state || {}; + + /** + * Use `expand-brackets` parsers + */ + + extglob.use(brackets.parsers); + extglob.parser.sets.paren = extglob.parser.sets.paren || []; + extglob.parser + + /** + * Extglob open: "*(" + */ + + .capture('paren.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^([!@*?+])?\(/); + if (!m) return; + + var prev = this.prev(); + var prefix = m[1]; + var val = m[0]; + + var open = pos({ + type: 'paren.open', + parsed: parsed, + val: val + }); + + var node = pos({ + type: 'paren', + prefix: prefix, + nodes: [open] + }); + + // if nested negation extglobs, just cancel them out to simplify + if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') { + prev.prefix = '@'; + node.prefix = '@'; + } + + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'parent', prev); + define(open, 'parent', node); + + this.push('paren', node); + prev.nodes.push(node); + }) + + /** + * Extglob close: ")" + */ + + .capture('paren.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\)/); + if (!m) return; + + var parent = this.pop('paren'); + var node = pos({ + type: 'paren.close', + rest: this.input, + parsed: parsed, + val: m[0] + }); + + if (!this.isType(parent, 'paren')) { + if (this.options.strict) { + throw new Error('missing opening paren: "("'); + } + node.escaped = true; + return node; + } + + node.prefix = parent.prefix; + parent.nodes.push(node); + define(node, 'parent', parent); + }) + + /** + * Escape: "\\." + */ + + .capture('escape', function() { + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; + + return pos({ + type: 'escape', + val: m[0], + ch: m[1] + }); + }) + + /** + * Question marks: "?" + */ + + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; + extglob.state.metachar = true; + return pos({ + type: 'qmark', + rest: this.input, + parsed: parsed, + val: m[0] + }); + }) + + /** + * Character parsers + */ + + .capture('star', /^\*(?!\()/) + .capture('plus', /^\+(?!\()/) + .capture('dot', /^\./) + .capture('text', not); +}; + +/** + * Expose text regex string + */ + +module.exports.TEXT_REGEX = TEXT_REGEX; + +/** + * Extglob parsers + */ + +module.exports = parsers; + + +/***/ }), + +/***/ 91439: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var regex = __webpack_require__(30931); +var Cache = __webpack_require__(49908); + +/** + * Utils + */ + +var utils = module.exports; +var cache = utils.cache = new Cache(); + +/** + * Cast `val` to an array + * @return {Array} + */ + +utils.arrayify = function(val) { + if (!Array.isArray(val)) { + return [val]; + } + return val; +}; + +/** + * Memoize a generated regex or function + */ + +utils.memoize = function(type, pattern, options, fn) { + var key = utils.createKey(type + pattern, options); + + if (cache.has(type, key)) { + return cache.get(type, key); + } + + var val = fn(pattern, options); + if (options && options.cache === false) { + return val; + } + + cache.set(type, key, val); + return val; +}; + +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +utils.createKey = function(pattern, options) { + var key = pattern; + if (typeof options === 'undefined') { + return key; + } + for (var prop in options) { + key += ';' + prop + '=' + String(options[prop]); + } + return key; +}; + +/** + * Create the regex to use for matching text + */ + +utils.createRegex = function(str) { + var opts = {contains: true, strictClose: false}; + return regex(str, opts); +}; + + +/***/ }), + +/***/ 62250: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(44133); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), + +/***/ 63933: +/***/ ((module) => { + +"use strict"; + + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; + + +/***/ }), + +/***/ 73600: +/***/ ((module) => { + +"use strict"; + + +module.exports = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + var seen = []; + return (function stringify (node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); + + var i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; + } + return out + ']'; + } + + if (node === null) return 'null'; + + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); + + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); +}; + + +/***/ }), + +/***/ 35955: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * fill-range + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var util = __webpack_require__(31669); +var isNumber = __webpack_require__(87218); +var extend = __webpack_require__(28727); +var repeat = __webpack_require__(6332); +var toRegex = __webpack_require__(1353); + +/** + * Return a range of numbers or letters. + * + * @param {String} `start` Start of the range + * @param {String} `stop` End of the range + * @param {String} `step` Increment or decrement to use. + * @param {Function} `fn` Custom function to modify each element in the range. + * @return {Array} + */ + +function fillRange(start, stop, step, options) { + if (typeof start === 'undefined') { + return []; + } + + if (typeof stop === 'undefined' || start === stop) { + // special case, for handling negative zero + var isString = typeof start === 'string'; + if (isNumber(start) && !toNumber(start)) { + return [isString ? '0' : 0]; + } + return [start]; + } + + if (typeof step !== 'number' && typeof step !== 'string') { + options = step; + step = undefined; + } + + if (typeof options === 'function') { + options = { transform: options }; + } + + var opts = extend({step: step}, options); + if (opts.step && !isValidNumber(opts.step)) { + if (opts.strictRanges === true) { + throw new TypeError('expected options.step to be a number'); + } + return []; + } + + opts.isNumber = isValidNumber(start) && isValidNumber(stop); + if (!opts.isNumber && !isValid(start, stop)) { + if (opts.strictRanges === true) { + throw new RangeError('invalid range arguments: ' + util.inspect([start, stop])); + } + return []; + } + + opts.isPadded = isPadded(start) || isPadded(stop); + opts.toString = opts.stringify + || typeof opts.step === 'string' + || typeof start === 'string' + || typeof stop === 'string' + || !opts.isNumber; + + if (opts.isPadded) { + opts.maxLength = Math.max(String(start).length, String(stop).length); + } + + // support legacy minimatch/fill-range options + if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize; + if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe; + return expand(start, stop, opts); +} + +function expand(start, stop, options) { + var a = options.isNumber ? toNumber(start) : start.charCodeAt(0); + var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0); + + var step = Math.abs(toNumber(options.step)) || 1; + if (options.toRegex && step === 1) { + return toRange(a, b, start, stop, options); + } + + var zero = {greater: [], lesser: []}; + var asc = a < b; + var arr = new Array(Math.round((asc ? b - a : a - b) / step)); + var idx = 0; + + while (asc ? a <= b : a >= b) { + var val = options.isNumber ? a : String.fromCharCode(a); + if (options.toRegex && (val >= 0 || !options.isNumber)) { + zero.greater.push(val); + } else { + zero.lesser.push(Math.abs(val)); + } + + if (options.isPadded) { + val = zeros(val, options); + } + + if (options.toString) { + val = String(val); + } + + if (typeof options.transform === 'function') { + arr[idx++] = options.transform(val, a, b, step, idx, arr, options); + } else { + arr[idx++] = val; + } + + if (asc) { + a += step; + } else { + a -= step; + } + } + + if (options.toRegex === true) { + return toSequence(arr, zero, options); + } + return arr; +} + +function toRange(a, b, start, stop, options) { + if (options.isPadded) { + return toRegex(start, stop, options); + } + + if (options.isNumber) { + return toRegex(Math.min(a, b), Math.max(a, b), options); + } + + var start = String.fromCharCode(Math.min(a, b)); + var stop = String.fromCharCode(Math.max(a, b)); + return '[' + start + '-' + stop + ']'; +} + +function toSequence(arr, zeros, options) { + var greater = '', lesser = ''; + if (zeros.greater.length) { + greater = zeros.greater.join('|'); + } + if (zeros.lesser.length) { + lesser = '-(' + zeros.lesser.join('|') + ')'; + } + var res = greater && lesser + ? greater + '|' + lesser + : greater || lesser; + + if (options.capture) { + return '(' + res + ')'; + } + return res; +} + +function zeros(val, options) { + if (options.isPadded) { + var str = String(val); + var len = str.length; + var dash = ''; + if (str.charAt(0) === '-') { + dash = '-'; + str = str.slice(1); + } + var diff = options.maxLength - len; + var pad = repeat('0', diff); + val = (dash + pad + str); + } + if (options.stringify) { + return String(val); + } + return val; +} + +function toNumber(val) { + return Number(val) || 0; +} + +function isPadded(str) { + return /^-?0\d/.test(str); +} + +function isValid(min, max) { + return (isValidNumber(min) || isValidLetter(min)) + && (isValidNumber(max) || isValidLetter(max)); +} + +function isValidLetter(ch) { + return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); +} + +function isValidNumber(n) { + return isNumber(n) && !/\./.test(n); +} + +/** + * Expose `fillRange` + * @type {Function} + */ + +module.exports = fillRange; + + +/***/ }), + +/***/ 43086: +/***/ ((module) => { + +"use strict"; +/*! + * for-in + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function forIn(obj, fn, thisArg) { + for (var key in obj) { + if (fn.call(thisArg, obj[key], key, obj) === false) { + break; + } + } +}; + + +/***/ }), + +/***/ 49908: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +/*! + * fragment-cache + * + * Copyright (c) 2016-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var MapCache = __webpack_require__(4337); + +/** + * Create a new `FragmentCache` with an optional object to use for `caches`. + * + * ```js + * var fragment = new FragmentCache(); + * ``` + * @name FragmentCache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ + +function FragmentCache(caches) { + this.caches = caches || {}; +} + +/** + * Prototype + */ + +FragmentCache.prototype = { + + /** + * Get cache `name` from the `fragment.caches` object. Creates a new + * `MapCache` if it doesn't already exist. + * + * ```js + * var cache = fragment.cache('files'); + * console.log(fragment.caches.hasOwnProperty('files')); + * //=> true + * ``` + * @name .cache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ + + cache: function(cacheName) { + return this.caches[cacheName] || (this.caches[cacheName] = new MapCache()); + }, + + /** + * Set a value for property `key` on cache `name` + * + * ```js + * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'})); + * ``` + * @name .set + * @param {String} `name` + * @param {String} `key` Property name to set + * @param {any} `val` The value of `key` + * @return {Object} The cache instance for chaining + * @api public + */ + + set: function(cacheName, key, val) { + var cache = this.cache(cacheName); + cache.set(key, val); + return cache; + }, + + /** + * Returns true if a non-undefined value is set for `key` on fragment cache `name`. + * + * ```js + * var cache = fragment.cache('files'); + * cache.set('somefile.js'); + * + * console.log(cache.has('somefile.js')); + * //=> true + * + * console.log(cache.has('some-other-file.js')); + * //=> false + * ``` + * @name .has + * @param {String} `name` Cache name + * @param {String} `key` Optionally specify a property to check for on cache `name` + * @return {Boolean} + * @api public + */ + + has: function(cacheName, key) { + return typeof this.get(cacheName, key) !== 'undefined'; + }, + + /** + * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method, + * so that cache `name` will be created it doesn't already exist. If `key` is not passed, + * the entire cache (`name`) is returned. + * + * ```js + * var Vinyl = require('vinyl'); + * var cache = fragment.cache('files'); + * cache.set('somefile.js', new Vinyl({path: 'somefile.js'})); + * console.log(cache.get('somefile.js')); + * //=> + * ``` + * @name .get + * @param {String} `name` + * @return {Object} Returns cache `name`, or the value of `key` if specified + * @api public + */ + + get: function(name, key) { + var cache = this.cache(name); + if (typeof key === 'string') { + return cache.get(key); + } + return cache; + } +}; + +/** + * Expose `FragmentCache` + */ + +exports = module.exports = FragmentCache; + + +/***/ }), + +/***/ 89304: +/***/ ((module) => { + +/*! + * get-value + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function(obj, prop, a, b, c) { + if (!isObject(obj) || !prop) { + return obj; + } + + prop = toString(prop); + + // allowing for multiple properties to be passed as + // a string or array, but much faster (3-4x) than doing + // `[].slice.call(arguments)` + if (a) prop += '.' + toString(a); + if (b) prop += '.' + toString(b); + if (c) prop += '.' + toString(c); + + if (prop in obj) { + return obj[prop]; + } + + var segs = prop.split('.'); + var len = segs.length; + var i = -1; + + while (obj && (++i < len)) { + var key = segs[i]; + while (key[key.length - 1] === '\\') { + key = key.slice(0, -1) + '.' + segs[++i]; + } + obj = obj[key]; + } + return obj; +}; + +function isObject(val) { + return val !== null && (typeof val === 'object' || typeof val === 'function'); +} + +function toString(val) { + if (!val) return ''; + if (Array.isArray(val)) { + return val.join('.'); + } + return val; +} + + +/***/ }), + +/***/ 95581: +/***/ ((module) => { + +"use strict"; + + +module.exports = clone + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} + + +/***/ }), + +/***/ 82161: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var fs = __webpack_require__(35747) +var polyfills = __webpack_require__(60034) +var legacy = __webpack_require__(7077) +var clone = __webpack_require__(95581) + +var util = __webpack_require__(31669) + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* 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) { + retry() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + retry() + } + + 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__(42357).equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + 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) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + 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) + + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + 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 + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) + + return go$readdir(args) + + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() + + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } + + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } + + 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 + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + 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) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + 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) + } + + 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) + + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) +} + +function retry () { + var elem = fs[gracefulQueue].shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} + + +/***/ }), + +/***/ 7077: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Stream = __webpack_require__(92413).Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + 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]; + } + + 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; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + 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]; + } + + 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; + } + + 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(); + } + } +} + + +/***/ }), + +/***/ 60034: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var constants = __webpack_require__(27619) + +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) {} + +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} + +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) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // 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) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + 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 () {} + } + + // 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. + + // 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`. + read.__proto__ = 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) + + 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 + } + } + + 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) + }) + }) + }) + } + + 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) + }) + } + } + + 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) + }) + } + } + + 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 + } + } + } + + 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) + } + } + + 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.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } + } + + // 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 + } + + return false + } +} + + +/***/ }), + +/***/ 41825: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * has-value + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isObject = __webpack_require__(96667); +var hasValues = __webpack_require__(80455); +var get = __webpack_require__(89304); + +module.exports = function(val, prop) { + return hasValues(isObject(val) && prop ? get(val, prop) : val); +}; + + +/***/ }), + +/***/ 80455: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(54329); +var isNumber = __webpack_require__(87218); + +module.exports = function hasValue(val) { + // is-number checks for NaN and other edge cases + if (isNumber(val)) { + return true; + } + + switch (typeOf(val)) { + case 'null': + case 'boolean': + case 'function': + return true; + case 'string': + case 'arguments': + return val.length !== 0; + case 'error': + return val.message !== ''; + case 'array': + var len = val.length; + if (len === 0) { + return false; + } + for (var i = 0; i < len; i++) { + if (hasValue(val[i])) { + return true; + } + } + return false; + case 'file': + case 'map': + case 'set': + return val.size !== 0; + case 'object': + var keys = Object.keys(val); + if (keys.length === 0) { + return false; + } + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (hasValue(val[key])) { + return true; + } + } + return false; + default: { + return false; + } + } +}; + + +/***/ }), + +/***/ 54329: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var isBuffer = __webpack_require__(72195); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), + +/***/ 2989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(31669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(97350); +} + + +/***/ }), + +/***/ 97350: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 13121: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(97458); + +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; + +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (typeOf(obj) !== 'object') { + return false; + } + + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } + + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } + + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } + + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} + +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; + + +/***/ }), + +/***/ 97458: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), + +/***/ 72195: +/***/ ((module) => { + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + + +/***/ }), + +/***/ 74194: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(82401); + +module.exports = function isDataDescriptor(obj, prop) { + // data descriptor properties + var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' + }; + + if (typeOf(obj) !== 'object') { + return false; + } + + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +}; + + +/***/ }), + +/***/ 82401: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), + +/***/ 44133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(46927); +var isAccessor = __webpack_require__(13121); +var isData = __webpack_require__(74194); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; + + +/***/ }), + +/***/ 46927: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), + +/***/ 18493: +/***/ ((module) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; + + +/***/ }), + +/***/ 87218: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-number + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(48865); + +module.exports = function isNumber(num) { + var type = typeOf(num); + + if (type === 'string') { + if (!num.trim()) return false; + } else if (type !== 'number') { + return false; + } + + return (num - num + 1) >= 0; +}; + + +/***/ }), + +/***/ 81064: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(96667); + +function isObjectObject(o) { + return isObject(o) === true + && Object.prototype.toString.call(o) === '[object Object]'; +} + +module.exports = function isPlainObject(o) { + var ctor,prot; + + if (isObjectObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== 'function') return false; + + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +}; + + +/***/ }), + +/***/ 21352: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 96667: +/***/ ((module) => { + +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && Array.isArray(val) === false; +}; + + +/***/ }), + +/***/ 48335: +/***/ ((module) => { + +"use strict"; + + +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 + } +} + + +/***/ }), + +/***/ 62437: +/***/ ((module) => { + +"use strict"; + + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i { + +var isBuffer = __webpack_require__(72195); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), + +/***/ 99736: +/***/ ((module) => { + +"use strict"; + + +class LoadingLoaderError extends Error { + constructor(message) { + super(message); + this.name = "LoaderRunnerError"; + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = LoadingLoaderError; + + +/***/ }), + +/***/ 73278: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +var fs = __webpack_require__(35747); +var readFile = fs.readFile.bind(fs); +var loadLoader = __webpack_require__(5384); + +function utf8BufferToString(buf) { + var str = buf.toString("utf-8"); + if(str.charCodeAt(0) === 0xFEFF) { + return str.substr(1); + } else { + return str; + } +} + +function splitQuery(req) { + var i = req.indexOf("?"); + if(i < 0) return [req, ""]; + return [req.substr(0, i), req.substr(i)]; +} + +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, + 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 + obj.query; + }, + set: function(value) { + if(typeof value === "string") { + var splittedRequest = splitQuery(value); + obj.path = splittedRequest[0]; + obj.query = splittedRequest[1]; + obj.options = undefined; + obj.ident = undefined; + } else { + if(!value.loader) + throw new Error("request should be a string or object with loader and object (" + JSON.stringify(value) + ")"); + obj.path = value.loader; + 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); + } + 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); + } + +} + +function convertArgs(args, raw) { + if(!raw && Buffer.isBuffer(args[0])) + args[0] = utf8BufferToString(args[0]); + else if(raw && typeof args[0] === "string") + args[0] = new Buffer(args[0], "utf-8"); // eslint-disable-line +} + +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); + } + + // 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); + if(args.length > 0) { + 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; + + var resourcePath = loaderContext.resourcePath; + if(resourcePath) { + loaderContext.addDependency(resourcePath); + options.readResource(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 splitted = splitQuery(resource); + return dirname(splitted[0]); +}; + +exports.runLoaders = function runLoaders(options, callback) { + // read options + var resource = options.resource || ""; + var loaders = options.loaders || []; + var loaderContext = options.context || {}; + var readResource = options.readResource || readFile; + + // + var splittedResource = resource && splitQuery(resource); + var resourcePath = splittedResource ? splittedResource[0] : undefined; + var resourceQuery = splittedResource ? splittedResource[1] : undefined; + var contextDirectory = resourcePath ? dirname(resourcePath) : null; + + // execution state + var requestCacheable = true; + var fileDependencies = []; + var contextDependencies = []; + + // prepare loader objects + loaders = loaders.map(createLoaderObject); + + loaderContext.context = contextDirectory; + loaderContext.loaderIndex = 0; + loaderContext.loaders = loaders; + loaderContext.resourcePath = resourcePath; + loaderContext.resourceQuery = resourceQuery; + 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.getDependencies = function getDependencies() { + return fileDependencies.slice(); + }; + loaderContext.getContextDependencies = function getContextDependencies() { + return contextDependencies.slice(); + }; + loaderContext.clearDependencies = function clearDependencies() { + fileDependencies.length = 0; + contextDependencies.length = 0; + requestCacheable = true; + }; + Object.defineProperty(loaderContext, "resource", { + enumerable: true, + get: function() { + if(loaderContext.resourcePath === undefined) + return undefined; + return loaderContext.resourcePath + loaderContext.resourceQuery; + }, + set: function(value) { + var splittedResource = value && splitQuery(value); + loaderContext.resourcePath = splittedResource ? splittedResource[0] : undefined; + loaderContext.resourceQuery = splittedResource ? splittedResource[1] : 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; + } + }); + + // finish loader context + if(Object.preventExtensions) { + Object.preventExtensions(loaderContext); + } + + var processOptions = { + resourceBuffer: null, + readResource: readResource + }; + iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { + if(err) { + return callback(err, { + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies + }); + } + callback(null, { + result: result, + resourceBuffer: processOptions.resourceBuffer, + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies + }); + }); +}; + + +/***/ }), + +/***/ 5384: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var LoaderLoadingError = __webpack_require__(99736); + +module.exports = function loadLoader(loader, callback) { + if(typeof System === "object" && typeof System.import === "function") { + System.import(loader.path).catch(callback).then(function(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(); + }); + } 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(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(); + } +}; + + +/***/ }), + +/***/ 4337: +/***/ ((module) => { + +"use strict"; +/*! + * map-cache + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var hasOwn = Object.prototype.hasOwnProperty; + +/** + * Expose `MapCache` + */ + +module.exports = MapCache; + +/** + * Creates a cache object to store key/value pairs. + * + * ```js + * var cache = new MapCache(); + * ``` + * + * @api public + */ + +function MapCache(data) { + this.__data__ = data || {}; +} + +/** + * Adds `value` to `key` on the cache. + * + * ```js + * cache.set('foo', 'bar'); + * ``` + * + * @param {String} `key` The key of the value to cache. + * @param {*} `value` The value to cache. + * @returns {Object} Returns the `Cache` object for chaining. + * @api public + */ + +MapCache.prototype.set = function mapSet(key, value) { + if (key !== '__proto__') { + this.__data__[key] = value; + } + return this; +}; + +/** + * Gets the cached value for `key`. + * + * ```js + * cache.get('foo'); + * //=> 'bar' + * ``` + * + * @param {String} `key` The key of the value to get. + * @returns {*} Returns the cached value. + * @api public + */ + +MapCache.prototype.get = function mapGet(key) { + return key === '__proto__' ? undefined : this.__data__[key]; +}; + +/** + * Checks if a cached value for `key` exists. + * + * ```js + * cache.has('foo'); + * //=> true + * ``` + * + * @param {String} `key` The key of the entry to check. + * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`. + * @api public + */ + +MapCache.prototype.has = function mapHas(key) { + return key !== '__proto__' && hasOwn.call(this.__data__, key); +}; + +/** + * Removes `key` and its value from the cache. + * + * ```js + * cache.del('foo'); + * ``` + * @title .del + * @param {String} `key` The key of the value to remove. + * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`. + * @api public + */ + +MapCache.prototype.del = function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; +}; + + +/***/ }), + +/***/ 11270: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var util = __webpack_require__(31669); +var visit = __webpack_require__(59248); + +/** + * Map `visit` over an array of objects. + * + * @param {Object} `collection` The context in which to invoke `method` + * @param {String} `method` Name of the method to call on `collection` + * @param {Object} `arr` Array of objects. + */ + +module.exports = function mapVisit(collection, method, val) { + if (isObject(val)) { + return visit.apply(null, arguments); + } + + if (!Array.isArray(val)) { + throw new TypeError('expected an array: ' + util.inspect(val)); + } + + var args = [].slice.call(arguments, 3); + + for (var i = 0; i < val.length; i++) { + var ele = val[i]; + if (isObject(ele)) { + visit.apply(null, [collection, method, ele].concat(args)); + } else { + collection[method].apply(collection, [ele].concat(args)); + } + } +}; + +function isObject(val) { + return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object')); +} + + +/***/ }), + +/***/ 32327: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +var normalize = __webpack_require__(25458); +var errors = __webpack_require__(48916); +var stream = __webpack_require__(68193); + +var ReadableStream = stream.Readable; +var WritableStream = stream.Writable; + +function MemoryFileSystemError(err, path) { + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, arguments.callee) + this.code = err.code; + this.errno = err.errno; + this.message = err.description; + this.path = path; +} +MemoryFileSystemError.prototype = new Error(); + +function MemoryFileSystem(data) { + this.data = data || {}; +} +module.exports = MemoryFileSystem; + +function isDir(item) { + if(typeof item !== "object") return false; + return item[""] === true; +} + +function isFile(item) { + if(typeof item !== "object") return false; + return !item[""]; +} + +function pathToArray(path) { + path = normalize(path); + var nix = /^\//.test(path); + if(!nix) { + if(!/^[A-Za-z]:/.test(path)) { + throw new MemoryFileSystemError(errors.code.EINVAL, path); + } + path = path.replace(/[\\\/]+/g, "\\"); // multi slashs + path = path.split(/[\\\/]/); + path[0] = path[0].toUpperCase(); + } else { + path = path.replace(/\/+/g, "/"); // multi slashs + path = path.substr(1).split("/"); + } + if(!path[path.length-1]) path.pop(); + return path; +} + +function trueFn() { return true; } +function falseFn() { return false; } + +MemoryFileSystem.prototype.meta = function(_path) { + var path = pathToArray(_path); + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + return; + current = current[path[i]]; + } + return current[path[i]]; +} + +MemoryFileSystem.prototype.existsSync = function(_path) { + return !!this.meta(_path); +} + +MemoryFileSystem.prototype.statSync = function(_path) { + var current = this.meta(_path); + if(_path === "/" || isDir(current)) { + return { + isFile: falseFn, + isDirectory: trueFn, + isBlockDevice: falseFn, + isCharacterDevice: falseFn, + isSymbolicLink: falseFn, + isFIFO: falseFn, + isSocket: falseFn + }; + } else if(isFile(current)) { + return { + isFile: trueFn, + isDirectory: falseFn, + isBlockDevice: falseFn, + isCharacterDevice: falseFn, + isSymbolicLink: falseFn, + isFIFO: falseFn, + isSocket: falseFn + }; + } else { + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + } +}; + +MemoryFileSystem.prototype.readFileSync = function(_path, encoding) { + var path = pathToArray(_path); + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + current = current[path[i]]; + } + if(!isFile(current[path[i]])) { + if(isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.EISDIR, _path); + else + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + } + current = current[path[i]]; + return encoding ? current.toString(encoding) : current; +}; + +MemoryFileSystem.prototype.readdirSync = function(_path) { + if(_path === "/") return Object.keys(this.data).filter(Boolean); + var path = pathToArray(_path); + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + current = current[path[i]]; + } + if(!isDir(current[path[i]])) { + if(isFile(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); + else + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + } + return Object.keys(current[path[i]]).filter(Boolean); +}; + +MemoryFileSystem.prototype.mkdirpSync = function(_path) { + var path = pathToArray(_path); + if(path.length === 0) return; + var current = this.data; + for(var i = 0; i < path.length; i++) { + if(isFile(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); + else if(!isDir(current[path[i]])) + current[path[i]] = {"":true}; + current = current[path[i]]; + } + return; +}; + +MemoryFileSystem.prototype.mkdirSync = function(_path) { + var path = pathToArray(_path); + if(path.length === 0) return; + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + current = current[path[i]]; + } + if(isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.EEXIST, _path); + else if(isFile(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); + current[path[i]] = {"":true}; + return; +}; + +MemoryFileSystem.prototype._remove = function(_path, name, testFn) { + var path = pathToArray(_path); + if(path.length === 0) { + throw new MemoryFileSystemError(errors.code.EPERM, _path); + } + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + current = current[path[i]]; + } + if(!testFn(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + delete current[path[i]]; + return; +}; + +MemoryFileSystem.prototype.rmdirSync = function(_path) { + return this._remove(_path, "Directory", isDir); +}; + +MemoryFileSystem.prototype.unlinkSync = function(_path) { + return this._remove(_path, "File", isFile); +}; + +MemoryFileSystem.prototype.readlinkSync = function(_path) { + throw new MemoryFileSystemError(errors.code.ENOSYS, _path); +}; + +MemoryFileSystem.prototype.writeFileSync = function(_path, content, encoding) { + if(!content && !encoding) throw new Error("No content"); + var path = pathToArray(_path); + if(path.length === 0) { + throw new MemoryFileSystemError(errors.code.EISDIR, _path); + } + var current = this.data; + for(var i = 0; i < path.length - 1; i++) { + if(!isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.ENOENT, _path); + current = current[path[i]]; + } + if(isDir(current[path[i]])) + throw new MemoryFileSystemError(errors.code.EISDIR, _path); + current[path[i]] = encoding || typeof content === "string" ? new Buffer(content, encoding) : content; + return; +}; + +MemoryFileSystem.prototype.join = __webpack_require__(89597); +MemoryFileSystem.prototype.pathToArray = pathToArray; +MemoryFileSystem.prototype.normalize = normalize; + +// stream functions + +MemoryFileSystem.prototype.createReadStream = function(path, options) { + var stream = new ReadableStream(); + var done = false; + var data; + try { + data = this.readFileSync(path); + } catch (e) { + stream._read = function() { + if (done) { + return; + } + done = true; + this.emit('error', e); + this.push(null); + }; + return stream; + } + options = options || { }; + options.start = options.start || 0; + options.end = options.end || data.length; + stream._read = function() { + if (done) { + return; + } + done = true; + this.push(data.slice(options.start, options.end)); + this.push(null); + }; + return stream; +}; + +MemoryFileSystem.prototype.createWriteStream = function(path, options) { + var stream = new WritableStream(), self = this; + try { + // Zero the file and make sure it is writable + this.writeFileSync(path, new Buffer(0)); + } catch(e) { + // This or setImmediate? + stream.once('prefinish', function() { + stream.emit('error', e); + }); + return stream; + } + var bl = [ ], len = 0; + stream._write = function(chunk, encoding, callback) { + bl.push(chunk); + len += chunk.length; + self.writeFile(path, Buffer.concat(bl, len), callback); + } + return stream; +}; + +// async functions + +["stat", "readdir", "mkdirp", "rmdir", "unlink", "readlink"].forEach(function(fn) { + MemoryFileSystem.prototype[fn] = function(path, callback) { + try { + var result = this[fn + "Sync"](path); + } catch(e) { + setImmediate(function() { + callback(e); + }); + + return; + } + setImmediate(function() { + callback(null, result); + }); + }; +}); + +["mkdir", "readFile"].forEach(function(fn) { + MemoryFileSystem.prototype[fn] = function(path, optArg, callback) { + if(!callback) { + callback = optArg; + optArg = undefined; + } + try { + var result = this[fn + "Sync"](path, optArg); + } catch(e) { + setImmediate(function() { + callback(e); + }); + + return; + } + setImmediate(function() { + callback(null, result); + }); + }; +}); + +MemoryFileSystem.prototype.exists = function(path, callback) { + return callback(this.existsSync(path)); +} + +MemoryFileSystem.prototype.writeFile = function (path, content, encoding, callback) { + if(!callback) { + callback = encoding; + encoding = undefined; + } + try { + this.writeFileSync(path, content, encoding); + } catch(e) { + return callback(e); + } + return callback(); +}; + + +/***/ }), + +/***/ 89597: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var normalize = __webpack_require__(25458); + +var absoluteWinRegExp = /^[A-Z]:([\\\/]|$)/i; +var absoluteNixRegExp = /^\//i; + +module.exports = function join(path, request) { + if(!request) return normalize(path); + if(absoluteWinRegExp.test(request)) return normalize(request.replace(/\//g, "\\")); + if(absoluteNixRegExp.test(request)) return normalize(request); + if(path == "/") return normalize(path + request); + if(absoluteWinRegExp.test(path)) return normalize(path.replace(/\//g, "\\") + "\\" + request.replace(/\//g, "\\")); + if(absoluteNixRegExp.test(path)) return normalize(path + "/" + request); + return normalize(path + "/" + request); +}; + + +/***/ }), + +/***/ 25458: +/***/ ((module) => { + +module.exports = function normalize(path) { + var parts = path.split(/(\\+|\/+)/); + if(parts.length === 1) + return path; + var result = []; + var absolutePathStart = 0; + for(var i = 0, sep = false; i < parts.length; i++, sep = !sep) { + var part = parts[i]; + if(i === 0 && /^([A-Z]:)?$/i.test(part)) { + result.push(part); + absolutePathStart = 2; + } else if(sep) { + result.push(part[0]); + } else if(part === "..") { + switch(result.length) { + case 0: + // i. e. ".." => ".." + // i. e. "../a/b/c" => "../a/b/c" + result.push(part); + break; + case 2: + // i. e. "a/.." => "" + // i. e. "/.." => "/" + // i. e. "C:\.." => "C:\" + // i. e. "a/../b/c" => "b/c" + // i. e. "/../b/c" => "/b/c" + // i. e. "C:\..\a\b\c" => "C:\a\b\c" + i++; + sep = !sep; + result.length = absolutePathStart; + break; + case 4: + // i. e. "a/b/.." => "a" + // i. e. "/a/.." => "/" + // i. e. "C:\a\.." => "C:\" + // i. e. "/a/../b/c" => "/b/c" + if(absolutePathStart === 0) { + result.length -= 3; + } else { + i++; + sep = !sep; + result.length = 2; + } + break; + default: + // i. e. "/a/b/.." => "/a" + // i. e. "/a/b/../c" => "/a/c" + result.length -= 3; + break; + } + } else if(part === ".") { + switch(result.length) { + case 0: + // i. e. "." => "." + // i. e. "./a/b/c" => "./a/b/c" + result.push(part); + break; + case 2: + // i. e. "a/." => "a" + // i. e. "/." => "/" + // i. e. "C:\." => "C:\" + // i. e. "C:\.\a\b\c" => "C:\a\b\c" + if(absolutePathStart === 0) { + result.length--; + } else { + i++; + sep = !sep; + } + break; + default: + // i. e. "a/b/." => "a/b" + // i. e. "/a/." => "/" + // i. e. "C:\a\." => "C:\" + // i. e. "a/./b/c" => "a/b/c" + // i. e. "/a/./b/c" => "/a/b/c" + result.length--; + break; + } + } else if(part) { + result.push(part); + } + } + if(result.length === 1 && /^[A-Za-z]:$/.test(result)) + return result[0] + "\\"; + return result.join(""); +}; + + +/***/ }), + +/***/ 53024: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +var util = __webpack_require__(31669); +var braces = __webpack_require__(22706); +var toRegex = __webpack_require__(51279); +var extend = __webpack_require__(3767); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(26113); +var parsers = __webpack_require__(14086); +var cache = __webpack_require__(34743); +var utils = __webpack_require__(63976); +var MAX_LENGTH = 1024 * 64; + +/** + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var mm = require('micromatch'); + * mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +function micromatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); + + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; + } + + if (len === 1) { + return micromatch.match(list, patterns[0], options); + } + + var omit = []; + var keep = []; + var idx = -1; + + while (++idx < len) { + var pattern = patterns[idx]; + + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); + } else { + keep.push.apply(keep, micromatch.match(list, pattern, options)); + } + } + + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } + + return matches; +} + +/** + * Similar to the main function, but `pattern` must be a string. + * + * ```js + * var mm = require('micromatch'); + * mm.match(list, pattern[, options]); + * + * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public + */ + +micromatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } + + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, micromatch.matcher); + var matches = []; + + list = utils.arrayify(list); + var len = list.length; + var idx = -1; + + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); + } + } + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } + + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; + } + } + + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = micromatch.not(matches, options.ignore, options); + } + + return options.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the specified `string` matches the given glob `pattern`. + * + * ```js + * var mm = require('micromatch'); + * mm.isMatch(string, pattern[, options]); + * + * console.log(mm.isMatch('a.a', '*.a')); + * //=> true + * console.log(mm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public + */ + +micromatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; + } + + var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); + return isMatch(str); +}; + +/** + * Returns true if some of the strings in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length === 1) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length !== 1) { + return false; + } + } + return true; +}; + +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. + * + * ```js + * var mm = require('micromatch'); + * mm.any(string, patterns[, options]); + * + * console.log(mm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(mm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (micromatch.isMatch(str, patterns[i], options)) { + return true; + } + } + return false; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * var mm = require('micromatch'); + * mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + if (typeof patterns === 'string') { + patterns = [patterns]; + } + for (var i = 0; i < patterns.length; i++) { + if (!micromatch.isMatch(str, patterns[i], options)) { + return false; + } + } + return true; +}; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; + + var unixify = utils.unixify(opts); + list = utils.arrayify(list).map(unixify); + + var matches = utils.diff(list, micromatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, micromatch(list, ignore)); + } + + return opts.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + +micromatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } + + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } + } + + var opts = extend({}, options, {contains: true}); + return micromatch.any(str, patterns, opts); +}; + +/** + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private + */ + +micromatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * var mm = require('micromatch'); + * mm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = micromatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); +}; + +/** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * var mm = require('micromatch'); + * mm.matcher(pattern[, options]); + * + * var isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = function matcher(pattern, options) { + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); + } + + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } + + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } + + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); + } + return utils.matchPath(pattern, options); + } + + // if pattern is a glob string + var re = micromatch.makeRe(pattern, options); + + // if `options.matchBase` or `options.basename` is defined + if (micromatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); + } + + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); + + return function(str) { + if (equals(str)) { + return true; + } + + if (regex.test(unixify(str))) { + return true; + } + return false; + }; + } + + var fn = test(re); + Object.defineProperty(fn, 'result', { + configurable: true, + enumerable: false, + value: re.result + }); + return fn; +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * var mm = require('micromatch'); + * mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch.capture = function(pattern, str, options) { + var re = micromatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); + + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = memoize('capture', pattern, options, match); + return capture(str); +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var mm = require('micromatch'); + * mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function makeRe() { + var result = micromatch.create(pattern, options); + var ast_array = []; + var output = result.map(function(obj) { + obj.ast.state = obj.state; + ast_array.push(obj.ast); + return obj.output; + }); + + var regex = toRegex(output.join('|'), options); + Object.defineProperty(regex, 'result', { + configurable: true, + enumerable: false, + value: ast_array + }); + return regex; + } + + return memoize('makeRe', pattern, options, makeRe); +}; + +/** + * Expand the given brace `pattern`. + * + * ```js + * var mm = require('micromatch'); + * console.log(mm.braces('foo/{a,b}/bar')); + * //=> ['foo/(a|b)/bar'] + * + * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); + * //=> ['foo/(a|b)/bar'] + * ``` + * @param {String} `pattern` String with brace pattern to expand. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch.braces = function(pattern, options) { + if (typeof pattern !== 'string' && !Array.isArray(pattern)) { + throw new TypeError('expected pattern to be an array or string'); + } + + function expand() { + if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { + return utils.arrayify(pattern); + } + return braces(pattern, options); + } + + return memoize('braces', pattern, options, expand); +}; + +/** + * Proxy to the [micromatch.braces](#method), for parity with + * minimatch. + */ + +micromatch.braceExpand = function(pattern, options) { + var opts = extend({}, options, {expand: true}); + return micromatch.braces(pattern, opts); +}; + +/** + * Parses the given glob `pattern` and returns an array of abstract syntax + * trees (ASTs), with the compiled `output` and optional source `map` on + * each AST. + * + * ```js + * var mm = require('micromatch'); + * mm.create(pattern[, options]); + * + * console.log(mm.create('abc/*.js')); + * // [{ options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 }] + * ``` + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. + * @api public + */ + +micromatch.create = function(pattern, options) { + return memoize('create', pattern, options, function() { + function create(str, opts) { + return micromatch.compile(micromatch.parse(str, opts), opts); + } + + pattern = micromatch.braces(pattern, options); + var len = pattern.length; + var idx = -1; + var res = []; + + while (++idx < len) { + res.push(create(pattern[idx], options)); + } + return res; + }); +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var mm = require('micromatch'); + * mm.parse(pattern[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +micromatch.parse = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); + + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; + } + + return memoize('parse', pattern, options, parse); +}; + +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var mm = require('micromatch'); + * mm.compile(ast[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(mm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ + +micromatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = micromatch.parse(ast, options); + } + + return memoize('compile', ast.input, options, function() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); + }); +}; + +/** + * Clear the regex cache. + * + * ```js + * mm.clearCache(); + * ``` + * @api public + */ + +micromatch.clearCache = function() { + micromatch.cache.caches = {}; +}; + +/** + * Returns true if the given value is effectively an empty string + */ + +function isEmptyString(val) { + return String(val) === '' || String(val) === './'; +} + +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. + */ + +function compose(patterns, options, matcher) { + var matchers; + + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); + } + } + + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; + } + } + return false; + }; + }); +} + +/** + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. + */ + +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); + + if (options && options.cache === false) { + return fn(pattern, options); + } + + if (cache.has(type, key)) { + return cache.get(type, key); + } + + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} + +/** + * Expose compiler, parser and cache on `micromatch` + */ + +micromatch.compilers = compilers; +micromatch.parsers = parsers; +micromatch.caches = cache.caches; + +/** + * Expose `micromatch` + * @type {Function} + */ + +module.exports = micromatch; + + +/***/ }), + +/***/ 34743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = new (__webpack_require__(49908))(); + + +/***/ }), + +/***/ 26113: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var nanomatch = __webpack_require__(57925); +var extglob = __webpack_require__(66675); + +module.exports = function(snapdragon) { + var compilers = snapdragon.compiler.compilers; + var opts = snapdragon.options; + + // register nanomatch compilers + snapdragon.use(nanomatch.compilers); + + // get references to some specific nanomatch compilers before they + // are overridden by the extglob and/or custom compilers + var escape = compilers.escape; + var qmark = compilers.qmark; + var slash = compilers.slash; + var star = compilers.star; + var text = compilers.text; + var plus = compilers.plus; + var dot = compilers.dot; + + // register extglob compilers or escape exglobs if disabled + if (opts.extglob === false || opts.noext === true) { + snapdragon.compiler.use(escapeExtglobs); + } else { + snapdragon.use(extglob.compilers); + } + + snapdragon.use(function() { + this.options.star = this.options.star || function(/*node*/) { + return '[^\\\\/]*?'; + }; + }); + + // custom micromatch compilers + snapdragon.compiler + + // reset referenced compiler + .set('dot', dot) + .set('escape', escape) + .set('plus', plus) + .set('slash', slash) + .set('qmark', qmark) + .set('star', star) + .set('text', text); +}; + +function escapeExtglobs(compiler) { + compiler.set('paren', function(node) { + var val = ''; + visit(node, function(tok) { + if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val; + }); + return this.emit(val, node); + }); + + /** + * Visit `node` with the given `fn` + */ + + function visit(node, fn) { + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + + /** + * Map visit over array of `nodes`. + */ + + function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } + } +} + + +/***/ }), + +/***/ 14086: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var extglob = __webpack_require__(66675); +var nanomatch = __webpack_require__(57925); +var regexNot = __webpack_require__(30931); +var toRegex = __webpack_require__(51279); +var not; + +/** + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) + */ + +var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; +var createNotRegex = function(opts) { + return not || (not = textRegex(TEXT)); +}; + +/** + * Parsers + */ + +module.exports = function(snapdragon) { + var parsers = snapdragon.parser.parsers; + + // register nanomatch parsers + snapdragon.use(nanomatch.parsers); + + // get references to some specific nanomatch parsers before they + // are overridden by the extglob and/or parsers + var escape = parsers.escape; + var slash = parsers.slash; + var qmark = parsers.qmark; + var plus = parsers.plus; + var star = parsers.star; + var dot = parsers.dot; + + // register extglob parsers + snapdragon.use(extglob.parsers); + + // custom micromatch parsers + snapdragon.parser + .use(function() { + // override "notRegex" created in nanomatch parser + this.notRegex = /^\!+(?!\()/; + }) + // reset the referenced parsers + .capture('escape', escape) + .capture('slash', slash) + .capture('qmark', qmark) + .capture('star', star) + .capture('plus', plus) + .capture('dot', dot) + + /** + * Override `text` parser + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(createNotRegex(this.options)); + if (!m || !m[0]) return; + + // escape regex boundary characters and simple brackets + var val = m[0].replace(/([[\]^$])/g, '\\$1'); + + return pos({ + type: 'text', + val: val + }); + }); +}; + +/** + * Create text regex + */ + +function textRegex(pattern) { + var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); + var prefix = '(?:[\\^]|\\\\|'; + return toRegex(prefix + notStr + ')', {strictClose: false}); +} + + +/***/ }), + +/***/ 63976: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = module.exports; +var path = __webpack_require__(85622); + +/** + * Module dependencies + */ + +var Snapdragon = __webpack_require__(79285); +utils.define = __webpack_require__(35851); +utils.diff = __webpack_require__(9455); +utils.extend = __webpack_require__(3767); +utils.pick = __webpack_require__(38509); +utils.typeOf = __webpack_require__(19613); +utils.unique = __webpack_require__(19009); + +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ + +utils.isWindows = function() { + return path.sep === '\\' || process.platform === 'win32'; +}; + +/** + * Get the `Snapdragon` instance to use + */ + +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } + + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } + + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + } + + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); + + return snapdragon; +}; + +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +utils.createKey = function(pattern, options) { + if (utils.typeOf(options) !== 'object') { + return pattern; + } + var val = pattern; + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + val += ';' + key + '=' + String(options[key]); + } + return val; +}; + +/** + * Cast `val` to an array + * @return {Array} + */ + +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Return true if `val` is a non-empty string + */ + +utils.isString = function(val) { + return typeof val === 'string'; +}; + +/** + * Return true if `val` is a non-empty string + */ + +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; + +/** + * Returns true if the given `str` has special characters + */ + +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); +}; + +/** + * Escape regex characters in the given string + */ + +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); +}; + +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ + +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; + +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ + +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; + +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ + +utils.stripPrefix = function(str) { + if (str.charAt(0) !== '.') { + return str; + } + var ch = str.charAt(1); + if (utils.isSlash(ch)) { + return str.slice(2); + } + return str; +}; + +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ + +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; + +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; + +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ + +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; + +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ + +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; + +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; + +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; + +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ + +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(path.basename(filepath)); + }; +}; + +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ + +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + return unixify(str); +}; + +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ + +utils.unixify = function(options) { + options = options || {}; + return function(filepath) { + if (utils.isWindows() || options.unixify === true) { + filepath = utils.toPosixPath(filepath); + } + if (options.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (options.unescape === true) { + filepath = utils.unescape(filepath); + } + return filepath; + }; +}; + + +/***/ }), + +/***/ 35851: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; + +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); + } + + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } + + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; +}; + + +/***/ }), + +/***/ 3767: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(98775); +var assignSymbols = __webpack_require__(64353); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), + +/***/ 98775: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 19613: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), + +/***/ 4870: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(29502); +var forIn = __webpack_require__(43086); + +function mixinDeep(target, objects) { + var len = arguments.length, i = 0; + while (++i < len) { + var obj = arguments[i]; + if (isObject(obj)) { + forIn(obj, copy, target); + } + } + return target; +} + +/** + * Copy properties from the source object to the + * target object. + * + * @param {*} `val` + * @param {String} `key` + */ + +function copy(val, key) { + if (!isValidKey(key)) { + return; + } + + var obj = this[key]; + if (isObject(val) && isObject(obj)) { + mixinDeep(obj, val); + } else { + this[key] = val; + } +} + +/** + * Returns true if `val` is an object or function. + * + * @param {any} val + * @return {Boolean} + */ + +function isObject(val) { + return isExtendable(val) && !Array.isArray(val); +} + +/** + * Returns true if `key` is a valid key to use when extending objects. + * + * @param {String} `key` + * @return {Boolean} + */ + +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +}; + +/** + * Expose `mixinDeep` + */ + +module.exports = mixinDeep; + + +/***/ }), + +/***/ 29502: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 57925: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +var util = __webpack_require__(31669); +var toRegex = __webpack_require__(51279); +var extend = __webpack_require__(69148); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(4756); +var parsers = __webpack_require__(5333); +var cache = __webpack_require__(58250); +var utils = __webpack_require__(41340); +var MAX_LENGTH = 1024 * 64; + +/** + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var nm = require('nanomatch'); + * nm(list, patterns[, options]); + * + * console.log(nm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +function nanomatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); + + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; + } + + if (len === 1) { + return nanomatch.match(list, patterns[0], options); + } + + var negated = false; + var omit = []; + var keep = []; + var idx = -1; + + while (++idx < len) { + var pattern = patterns[idx]; + + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); + negated = true; + } else { + keep.push.apply(keep, nanomatch.match(list, pattern, options)); + } + } + + // minimatch.match parity + if (negated && keep.length === 0) { + if (options && options.unixify === false) { + keep = list.slice(); + } else { + var unixify = utils.unixify(options); + for (var i = 0; i < list.length; i++) { + keep.push(unixify(list[i])); + } + } + } + + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } + + return matches; +} + +/** + * Similar to the main function, but `pattern` must be a string. + * + * ```js + * var nm = require('nanomatch'); + * nm.match(list, pattern[, options]); + * + * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public + */ + +nanomatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } + + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, nanomatch.matcher); + var matches = []; + + list = utils.arrayify(list); + var len = list.length; + var idx = -1; + + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); + } + } + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } + + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; + } + } + + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = nanomatch.not(matches, options.ignore, options); + } + + return options.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the specified `string` matches the given glob `pattern`. + * + * ```js + * var nm = require('nanomatch'); + * nm.isMatch(string, pattern[, options]); + * + * console.log(nm.isMatch('a.a', '*.a')); + * //=> true + * console.log(nm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public + */ + +nanomatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { + return false; + } + + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; + } + + var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); + return isMatch(str); +}; + +/** + * Returns true if some of the elements in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.some(list, patterns[, options]); + * + * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length === 1) { + return true; + } + } + + return false; +}; + +/** + * Returns true if every element in the given `list` matches + * at least one of the given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.every(list, patterns[, options]); + * + * console.log(nm.every('foo.js', ['foo.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length !== 1) { + return false; + } + } + + return true; +}; + +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. + * + * ```js + * var nm = require('nanomatch'); + * nm.any(string, patterns[, options]); + * + * console.log(nm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(nm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (nanomatch.isMatch(str, patterns[i], options)) { + return true; + } + } + return false; +}; + +/** + * Returns true if **all** of the given `patterns` + * match the specified string. + * + * ```js + * var nm = require('nanomatch'); + * nm.all(string, patterns[, options]); + * + * console.log(nm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (!nanomatch.isMatch(str, patterns[i], options)) { + return false; + } + } + return true; +}; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.not(list, patterns[, options]); + * + * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +nanomatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; + + list = utils.arrayify(list); + + var matches = utils.diff(list, nanomatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, nanomatch(list, ignore)); + } + + return opts.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var nm = require('nanomatch'); + * nm.contains(string, pattern[, options]); + * + * console.log(nm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(nm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + +nanomatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } + + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } + } + + var opts = extend({}, options, {contains: true}); + return nanomatch.any(str, patterns, opts); +}; + +/** + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private + */ + +nanomatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * var nm = require('nanomatch'); + * nm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(nm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +nanomatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = nanomatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); +}; + +/** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * var nm = require('nanomatch'); + * nm.matcher(pattern[, options]); + * + * var isMatch = nm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. + * @api public + */ + +nanomatch.matcher = function matcher(pattern, options) { + if (utils.isEmptyString(pattern)) { + return function() { + return false; + }; + } + + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); + } + + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } + + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } + + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); + } + return utils.matchPath(pattern, options); + } + + // if pattern is a glob string + var re = nanomatch.makeRe(pattern, options); + + // if `options.matchBase` or `options.basename` is defined + if (nanomatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); + } + + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); + + return function(str) { + if (equals(str)) { + return true; + } + + if (regex.test(unixify(str))) { + return true; + } + return false; + }; + } + + // create matcher function + var matcherFn = test(re); + // set result object from compiler on matcher function, + // as a non-enumerable property. useful for debugging + utils.define(matcherFn, 'result', re.result); + return matcherFn; +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or + * `null` if the pattern did not match. + * + * ```js + * var nm = require('nanomatch'); + * nm.capture(pattern, string[, options]); + * + * console.log(nm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(nm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ + +nanomatch.capture = function(pattern, str, options) { + var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); + + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = memoize('capture', pattern, options, match); + return capture(str); +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var nm = require('nanomatch'); + * nm.makeRe(pattern[, options]); + * + * console.log(nm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +nanomatch.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function makeRe() { + var opts = utils.extend({wrap: false}, options); + var result = nanomatch.create(pattern, opts); + var regex = toRegex(result.output, opts); + utils.define(regex, 'result', result); + return regex; + } + + return memoize('makeRe', pattern, options, makeRe); +}; + +/** + * Parses the given glob `pattern` and returns an object with the compiled `output` + * and optional source `map`. + * + * ```js + * var nm = require('nanomatch'); + * nm.create(pattern[, options]); + * + * console.log(nm.create('abc/*.js')); + * // { options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 } + * ``` + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. + * @api public + */ + +nanomatch.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + function create() { + return nanomatch.compile(nanomatch.parse(pattern, options), options); + } + return memoize('create', pattern, options, create); +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var nm = require('nanomatch'); + * nm.parse(pattern[, options]); + * + * var ast = nm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +nanomatch.parse = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); + + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; + } + + return memoize('parse', pattern, options, parse); +}; + +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var nm = require('nanomatch'); + * nm.compile(ast[, options]); + * + * var ast = nm.parse('a/{b,c}/d'); + * console.log(nm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ + +nanomatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = nanomatch.parse(ast, options); + } + + function compile() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); + } + + return memoize('compile', ast.input, options, compile); +}; + +/** + * Clear the regex cache. + * + * ```js + * nm.clearCache(); + * ``` + * @api public + */ + +nanomatch.clearCache = function() { + nanomatch.cache.__data__ = {}; +}; + +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. + */ + +function compose(patterns, options, matcher) { + var matchers; + + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); + } + } + + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; + } + } + return false; + }; + }); +} + +/** + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. + */ + +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); + + if (options && options.cache === false) { + return fn(pattern, options); + } + + if (cache.has(type, key)) { + return cache.get(type, key); + } + + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} + +/** + * Expose compiler, parser and cache on `nanomatch` + */ + +nanomatch.compilers = compilers; +nanomatch.parsers = parsers; +nanomatch.cache = cache; + +/** + * Expose `nanomatch` + * @type {Function} + */ + +module.exports = nanomatch; + + +/***/ }), + +/***/ 58250: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = new (__webpack_require__(49908))(); + + +/***/ }), + +/***/ 4756: +/***/ ((module) => { + +"use strict"; + + +/** +* Nanomatch compilers +*/ + +module.exports = function(nanomatch, options) { + function slash() { + if (options && typeof options.slash === 'string') { + return options.slash; + } + if (options && typeof options.slash === 'function') { + return options.slash.call(nanomatch); + } + return '\\\\/'; + } + + function star() { + if (options && typeof options.star === 'string') { + return options.star; + } + if (options && typeof options.star === 'function') { + return options.star.call(nanomatch); + } + return '[^' + slash() + ']*?'; + } + + var ast = nanomatch.ast = nanomatch.parser.ast; + ast.state = nanomatch.parser.state; + nanomatch.compiler.state = ast.state; + nanomatch.compiler + + /** + * Negation / escaping + */ + + .set('not', function(node) { + var prev = this.prev(); + if (this.options.nonegate === true || prev.type !== 'bos') { + return this.emit('\\' + node.val, node); + } + return this.emit(node.val, node); + }) + .set('escape', function(node) { + if (this.options.unescape && /^[-\w_.]/.test(node.val)) { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + .set('quoted', function(node) { + return this.emit(node.val, node); + }) + + /** + * Regex + */ + + .set('dollar', function(node) { + if (node.parent.type === 'bracket') { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + + /** + * Dot: "." + */ + + .set('dot', function(node) { + if (node.dotfiles === true) this.dotfiles = true; + return this.emit('\\' + node.val, node); + }) + + /** + * Slashes: "/" and "\" + */ + + .set('backslash', function(node) { + return this.emit(node.val, node); + }) + .set('slash', function(node, nodes, i) { + var val = '[' + slash() + ']'; + var parent = node.parent; + var prev = this.prev(); + + // set "node.hasSlash" to true on all ancestor parens nodes + while (parent.type === 'paren' && !parent.hasSlash) { + parent.hasSlash = true; + parent = parent.parent; + } + + if (prev.addQmark) { + val += '?'; + } + + // word boundary + if (node.rest.slice(0, 2) === '\\b') { + return this.emit(val, node); + } + + // globstars + if (node.parsed === '**' || node.parsed === './**') { + this.output = '(?:' + this.output; + return this.emit(val + ')?', node); + } + + // negation + if (node.parsed === '!**' && this.options.nonegate !== true) { + return this.emit(val + '?\\b', node); + } + return this.emit(val, node); + }) + + /** + * Square brackets + */ + + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + var val = node.val; + + if (node.escaped === true) { + inner = inner.replace(/\\?(\W)/g, '\\$1'); + negated = ''; + } + + if (inner === ']-') { + inner = '\\]\\-'; + } + + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } + + val = open + negated + inner + close; + return this.emit(val, node); + }) + + /** + * Square: "[.]" (only matches a single character in brackets) + */ + + .set('square', function(node) { + var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; + return this.emit(val, node); + }) + + /** + * Question mark: "?" + */ + + .set('qmark', function(node) { + var prev = this.prev(); + // don't use "slash" variable so that we always avoid + // matching backslashes and slashes with a qmark + var val = '[^.\\\\/]'; + if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { + val = '[^\\\\/]'; + } + + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch === '!' || ch === '=' || ch === ':') { + return this.emit(node.val, node); + } + } + + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) + + /** + * Plus + */ + + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); + } + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + var ch = this.output.slice(-1); + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) + + /** + * globstar: '**' + */ + + .set('globstar', function(node, nodes, i) { + if (!this.output) { + this.state.leadingGlobstar = true; + } + + var prev = this.prev(); + var before = this.prev(2); + var next = this.next(); + var after = this.next(2); + var type = prev.type; + var val = node.val; + + if (prev.type === 'slash' && next.type === 'slash') { + if (before.type === 'text') { + this.output += '?'; + + if (after.type !== 'text') { + this.output += '\\b'; + } + } + } + + var parsed = node.parsed; + if (parsed.charAt(0) === '!') { + parsed = parsed.slice(1); + } + + var isInside = node.isInside.paren || node.isInside.brace; + if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { + val = star(); + } else { + val = this.options.dot !== true + ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?' + : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?'; + } + + if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { + val = '(?!\\.)' + val; + } + + if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { + if (after.type === 'text' || after.type === 'star') { + node.addQmark = true; + } + } + + if (this.options.capture) { + val = '(' + val + ')'; + } + + return this.emit(val, node); + }) + + /** + * Star: "*" + */ + + .set('star', function(node, nodes, i) { + var prior = nodes[i - 2] || {}; + var prev = this.prev(); + var next = this.next(); + var type = prev.type; + + function isStart(n) { + return n.type === 'bos' || n.type === 'slash'; + } + + if (this.output === '' && this.options.contains !== true) { + this.output = '(?![' + slash() + '])'; + } + + if (type === 'bracket' && this.options.bash === false) { + var str = next && next.type === 'bracket' ? star() : '*?'; + if (!prev.nodes || prev.nodes[1].type !== 'posix') { + return this.emit(str, node); + } + } + + var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' + ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') + : ''; + + if (isStart(prev) || (isStart(prior) && type === 'not')) { + if (prefix !== '(?!\\.)') { + prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; + } else { + prefix += '(?=.)'; + } + } else if (prefix === '(?!\\.)') { + prefix = ''; + } + + if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { + this.output = '(?!\\.)' + this.output; + } + + var output = prefix + star(); + if (this.options.capture) { + output = '(' + output + ')'; + } + + return this.emit(output, node); + }) + + /** + * Text + */ + + .set('text', function(node) { + return this.emit(node.val, node); + }) + + /** + * End-of-string + */ + + .set('eos', function(node) { + var prev = this.prev(); + var val = node.val; + + this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; + if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { + val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); + } + + return this.emit(val, node); + }); + + /** + * Allow custom compilers to be passed on options + */ + + if (options && typeof options.compilers === 'function') { + options.compilers(nanomatch.compiler); + } +}; + + + +/***/ }), + +/***/ 5333: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var regexNot = __webpack_require__(30931); +var toRegex = __webpack_require__(51279); + +/** + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) + */ + +var cached; +var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; +var not = createTextRegex(NOT_REGEX); + +/** + * Nanomatch parsers + */ + +module.exports = function(nanomatch, options) { + var parser = nanomatch.parser; + var opts = parser.options; + + parser.state = { + slashes: 0, + paths: [] + }; + + parser.ast.state = parser.state; + parser + + /** + * Beginning-of-string + */ + + .capture('prefix', function() { + if (this.parsed) return; + var m = this.match(/^\.[\\/]/); + if (!m) return; + this.state.strictOpen = !!this.options.strictOpen; + this.state.addPrefix = true; + }) + + /** + * Escape: "\\." + */ + + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^(?:\\(.)|([$^]))/); + if (!m) return; + + return pos({ + type: 'escape', + val: m[2] || m[1] + }); + }) + + /** + * Quoted strings + */ + + .capture('quoted', function() { + var pos = this.position(); + var m = this.match(/^["']/); + if (!m) return; + + var quote = m[0]; + if (this.input.indexOf(quote) === -1) { + return pos({ + type: 'escape', + val: quote + }); + } + + var tok = advanceTo(this.input, quote); + this.consume(tok.len); + + return pos({ + type: 'quoted', + val: tok.esc + }); + }) + + /** + * Negations: "!" + */ + + .capture('not', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(this.notRegex || /^!+/); + if (!m) return; + var val = m[0]; + + var isNegated = (val.length % 2) === 1; + if (parsed === '' && !isNegated) { + val = ''; + } + + // if nothing has been parsed, we know `!` is at the start, + // so we need to wrap the result in a negation regex + if (parsed === '' && isNegated && this.options.nonegate !== true) { + this.bos.val = '(?!^(?:'; + this.append = ')$).*'; + val = ''; + } + return pos({ + type: 'not', + val: val + }); + }) + + /** + * Dot: "." + */ + + .capture('dot', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\.+/); + if (!m) return; + + var val = m[0]; + this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); + + return pos({ + type: 'dot', + dotfiles: this.state.dot, + val: val + }); + }) + + /** + * Plus: "+" + */ + + .capture('plus', /^\+(?!\()/) + + /** + * Question mark: "?" + */ + + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; + + this.state.metachar = true; + this.state.qmark = true; + + return pos({ + type: 'qmark', + parsed: parsed, + val: m[0] + }); + }) + + /** + * Globstar: "**" + */ + + .capture('globstar', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); + if (!m) return; + + var type = opts.noglobstar !== true ? 'globstar' : 'star'; + var node = pos({type: type, parsed: parsed}); + this.state.metachar = true; + + while (this.input.slice(0, 4) === '/**/') { + this.input = this.input.slice(3); + } + + node.isInside = { + brace: this.isInside('brace'), + paren: this.isInside('paren') + }; + + if (type === 'globstar') { + this.state.globstar = true; + node.val = '**'; + + } else { + this.state.star = true; + node.val = '*'; + } + + return node; + }) + + /** + * Star: "*" + */ + + .capture('star', function() { + var pos = this.position(); + var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; + var m = this.match(starRe); + if (!m) return; + + this.state.metachar = true; + this.state.star = true; + return pos({ + type: 'star', + val: m[0] + }); + }) + + /** + * Slash: "/" + */ + + .capture('slash', function() { + var pos = this.position(); + var m = this.match(/^\//); + if (!m) return; + + this.state.slashes++; + return pos({ + type: 'slash', + val: m[0] + }); + }) + + /** + * Backslash: "\\" + */ + + .capture('backslash', function() { + var pos = this.position(); + var m = this.match(/^\\(?![*+?(){}[\]'"])/); + if (!m) return; + + var val = m[0]; + + if (this.isInside('bracket')) { + val = '\\'; + } else if (val.length > 1) { + val = '\\\\'; + } + + return pos({ + type: 'backslash', + val: val + }); + }) + + /** + * Square: "[.]" + */ + + .capture('square', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\[([^!^\\])\]/); + if (!m) return; + + return pos({ + type: 'square', + val: m[1] + }); + }) + + /** + * Brackets: "[...]" (basic, this can be overridden by other parsers) + */ + + .capture('bracket', function() { + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; + + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); + var close = m[3] || ''; + + if (m[2] && inner.length < m[2].length) { + val = val.replace(/\\\\+/, '\\\\'); + } + + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); + + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } + + return pos({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + }); + }) + + /** + * Text + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; + + return pos({ + type: 'text', + val: m[0] + }); + }); + + /** + * Allow custom parsers to be passed on options + */ + + if (options && typeof options.parsers === 'function') { + options.parsers(nanomatch.parser); + } +}; + +/** + * Advance to the next non-escaped character + */ + +function advanceTo(input, endChar) { + var ch = input.charAt(0); + var tok = { len: 1, val: '', esc: '' }; + var idx = 0; + + function advance() { + if (ch !== '\\') { + tok.esc += '\\' + ch; + tok.val += ch; + } + + ch = input.charAt(++idx); + tok.len++; + + if (ch === '\\') { + advance(); + advance(); + } + } + + while (ch && ch !== endChar) { + advance(); + } + return tok; +} + +/** + * Create text regex + */ + +function createTextRegex(pattern) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re = toRegex('^(?:[*]\\((?=.)|' + not + ')', opts); + return (cached = re); +} + +/** + * Expose negation string + */ + +module.exports.not = NOT_REGEX; + + +/***/ }), + +/***/ 41340: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = module.exports; +var path = __webpack_require__(85622); + +/** + * Module dependencies + */ + +var isWindows = __webpack_require__(8025)(); +var Snapdragon = __webpack_require__(79285); +utils.define = __webpack_require__(18918); +utils.diff = __webpack_require__(9455); +utils.extend = __webpack_require__(69148); +utils.pick = __webpack_require__(38509); +utils.typeOf = __webpack_require__(42556); +utils.unique = __webpack_require__(19009); + +/** + * Returns true if the given value is effectively an empty string + */ + +utils.isEmptyString = function(val) { + return String(val) === '' || String(val) === './'; +}; + +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ + +utils.isWindows = function() { + return path.sep === '\\' || isWindows === true; +}; + +/** + * Return the last element from an array + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +/** + * Get the `Snapdragon` instance to use + */ + +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } + + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.call(this, str, options); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } + + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + } + + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); + + return snapdragon; +}; + +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +utils.createKey = function(pattern, options) { + if (typeof options === 'undefined') { + return pattern; + } + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; +}; + +/** + * Cast `val` to an array + * @return {Array} + */ + +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Return true if `val` is a non-empty string + */ + +utils.isString = function(val) { + return typeof val === 'string'; +}; + +/** + * Return true if `val` is a non-empty string + */ + +utils.isRegex = function(val) { + return utils.typeOf(val) === 'regexp'; +}; + +/** + * Return true if `val` is a non-empty string + */ + +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; + +/** + * Escape regex characters in the given string + */ + +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&'); +}; + +/** + * Combines duplicate characters in the provided `input` string. + * @param {String} `input` + * @returns {String} + */ + +utils.combineDupes = function(input, patterns) { + patterns = utils.arrayify(patterns).join('|').split('|'); + patterns = patterns.map(function(s) { + return s.replace(/\\?([+*\\/])/g, '\\$1'); + }); + var substr = patterns.join('|'); + var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); + return input.replace(regex, ''); +}; + +/** + * Returns true if the given `str` has special characters + */ + +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); +}; + +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ + +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; + +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ + +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; + +/** + * Strip the drive letter from a windows filepath + * @param {String} `fp` + * @return {String} + */ + +utils.stripDrive = function(fp) { + return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; +}; + +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ + +utils.stripPrefix = function(str) { + if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { + return str.slice(2); + } + return str; +}; + +/** + * Returns true if `str` is a common character that doesn't need + * to be processed to be used for matching. + * @param {String} `str` + * @return {Boolean} + */ + +utils.isSimpleChar = function(str) { + return str.trim() === '' || str === '.'; +}; + +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ + +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; + +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; + +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ + +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; + +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ + +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; + +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; + +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; + +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ + +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; + +/** + * Returns the given value unchanced. + * @return {any} + */ + +utils.identity = function(val) { + return val; +}; + +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ + +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + if (options && typeof options.unixify === 'function') { + return options.unixify(str); + } + return unixify(str); +}; + +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ + +utils.unixify = function(options) { + var opts = options || {}; + return function(filepath) { + if (opts.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (opts.unescape === true) { + filepath = utils.unescape(filepath); + } + if (opts.unixify === true || utils.isWindows()) { + filepath = utils.toPosixPath(filepath); + } + return filepath; + }; +}; + + +/***/ }), + +/***/ 18918: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; + +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); + } + + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } + + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; +}; + + +/***/ }), + +/***/ 69148: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(61781); +var assignSymbols = __webpack_require__(64353); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), + +/***/ 61781: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 8025: +/***/ ((module, exports) => { + +/*! + * is-windows + * + * Copyright © 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +(function(factory) { + if (exports && typeof exports === 'object' && "object" !== 'undefined') { + module.exports = factory(); + } else if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof window !== 'undefined') { + window.isWindows = factory(); + } else if (typeof global !== 'undefined') { + global.isWindows = factory(); + } else if (typeof self !== 'undefined') { + self.isWindows = factory(); + } else { + this.isWindows = factory(); + } +})(function() { + 'use strict'; + return function isWindows() { + return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); + }; +}); + + +/***/ }), + +/***/ 42556: +/***/ ((module) => { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), + +/***/ 5884: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.assert = __webpack_require__.ab + "assert.js"; +exports.buffer = __webpack_require__.ab + "index.js"; +exports.child_process = null; +exports.cluster = null; +exports.console = __webpack_require__.ab + "index1.js"; +exports.constants = __webpack_require__.ab + "constants.json"; +exports.crypto = __webpack_require__.ab + "index2.js"; +exports.dgram = null; +exports.dns = null; +exports.domain = __webpack_require__.ab + "index3.js"; +exports.events = __webpack_require__.ab + "events.js"; +exports.fs = null; +exports.http = __webpack_require__.ab + "index4.js"; +exports.https = __webpack_require__.ab + "index5.js"; +exports.module = null; +exports.net = null; +exports.os = __webpack_require__.ab + "browser.js"; +exports.path = __webpack_require__.ab + "index6.js"; +exports.punycode = __webpack_require__.ab + "punycode.js"; +exports.process = __webpack_require__.ab + "browser1.js"; +exports.querystring = __webpack_require__.ab + "index7.js"; +exports.readline = null; +exports.repl = null; +exports.stream = __webpack_require__.ab + "index8.js"; +exports._stream_duplex = __webpack_require__.ab + "duplex.js"; +exports._stream_passthrough = __webpack_require__.ab + "passthrough.js"; +exports._stream_readable = __webpack_require__.ab + "readable.js"; +exports._stream_transform = __webpack_require__.ab + "transform.js"; +exports._stream_writable = __webpack_require__.ab + "writable.js"; +exports.string_decoder = __webpack_require__.ab + "string_decoder.js"; +exports.sys = __webpack_require__.ab + "util.js"; +exports.timers = __webpack_require__.ab + "main.js"; +exports.tls = null; +exports.tty = __webpack_require__.ab + "index9.js"; +exports.url = __webpack_require__.ab + "url.js"; +exports.util = __webpack_require__.ab + "util.js"; +exports.vm = __webpack_require__.ab + "index10.js"; +exports.zlib = __webpack_require__.ab + "index11.js"; + + +/***/ }), + +/***/ 31368: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var typeOf = __webpack_require__(48865); +var copyDescriptor = __webpack_require__(3605); +var define = __webpack_require__(5477); + +/** + * Copy static properties, prototype properties, and descriptors from one object to another. + * + * ```js + * function App() {} + * var proto = App.prototype; + * App.prototype.set = function() {}; + * App.prototype.get = function() {}; + * + * var obj = {}; + * copy(obj, proto); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ + +function copy(receiver, provider, omit) { + if (!isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + + var props = nativeKeys(provider); + var keys = Object.keys(provider); + var len = props.length; + omit = arrayify(omit); + + while (len--) { + var key = props[len]; + + if (has(keys, key)) { + define(receiver, key, provider[key]); + } else if (!(key in receiver) && !has(omit, key)) { + copyDescriptor(receiver, provider, key); + } + } +}; + +/** + * Return true if the given value is an object or function + */ + +function isObject(val) { + return typeOf(val) === 'object' || typeof val === 'function'; +} + +/** + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. + * + * ```js + * has(['a', 'b', 'c'], 'c'); + * //=> true + * + * has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + */ + +function has(obj, val) { + val = arrayify(val); + var len = val.length; + + if (isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; + } + } + + var keys = nativeKeys(obj); + return has(keys, val); + } + + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; + } + } + return false; + } + + throw new TypeError('expected an array or object.'); +} + +/** + * Cast the given value to an array. + * + * ```js + * arrayify('foo'); + * //=> ['foo'] + * + * arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} + */ + +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} + +/** + * Returns true if a value has a `contructor` + * + * ```js + * hasConstructor({}); + * //=> true + * + * hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} + */ + +function hasConstructor(val) { + return isObject(val) && typeof val.constructor !== 'undefined'; +} + +/** + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. + * + * ```js + * nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + */ + +function nativeKeys(val) { + if (!hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +} + +/** + * Expose `copy` + */ + +module.exports = copy; + +/** + * Expose `copy.has` for tests + */ + +module.exports.has = has; + + +/***/ }), + +/***/ 59248: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * object-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(96667); + +module.exports = function visit(thisArg, method, target, val) { + if (!isObject(thisArg) && typeof thisArg !== 'function') { + throw new Error('object-visit expects `thisArg` to be an object.'); + } + + if (typeof method !== 'string') { + throw new Error('object-visit expects `method` name to be a string'); + } + + if (typeof thisArg[method] !== 'function') { + return thisArg; + } + + var args = [].slice.call(arguments, 3); + target = target || {}; + + for (var key in target) { + var arr = [key, target[key]].concat(args); + thisArg[method].apply(thisArg, arr); + } + return thisArg; +}; + + +/***/ }), + +/***/ 38509: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * object.pick + * + * Copyright (c) 2014-2015 Jon Schlinkert, contributors. + * Licensed under the MIT License + */ + + + +var isObject = __webpack_require__(96667); + +module.exports = function pick(obj, keys) { + if (!isObject(obj) && typeof obj !== 'function') { + return {}; + } + + var res = {}; + if (typeof keys === 'string') { + if (keys in obj) { + res[keys] = obj[keys]; + } + return res; + } + + var len = keys.length; + var idx = -1; + + while (++idx < len) { + var key = keys[idx]; + if (key in obj) { + res[key] = obj[key]; + } + } + return res; +}; + + +/***/ }), + +/***/ 27255: +/***/ ((module) => { + +/*! + * pascalcase + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +function pascalcase(str) { + if (typeof str !== 'string') { + throw new TypeError('expected a string.'); + } + str = str.replace(/([A-Z])/g, ' $1'); + if (str.length === 1) { return str.toUpperCase(); } + str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); + str = str.charAt(0).toUpperCase() + str.slice(1); + return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { + return ch.toUpperCase(); + }); +} + +module.exports = pascalcase; + + +/***/ }), + +/***/ 88412: +/***/ ((module) => { + +"use strict"; + + +/** + * POSIX character classes + */ + +module.exports = { + 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' +}; + + +/***/ }), + +/***/ 58404: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 59570: +/***/ (function(module) { + +/*! + * prr + * (c) 2013 Rod Vagg + * https://github.com/rvagg/prr + * License: MIT + */ + +(function (name, context, definition) { + if ( true && module.exports) + module.exports = definition() + else + context[name] = definition() +})('prr', this, function() { + + var setProperty = typeof Object.defineProperty == 'function' + ? function (obj, key, options) { + Object.defineProperty(obj, key, options) + return obj + } + : function (obj, key, options) { // < es5 + obj[key] = options.value + return obj + } + + , makeOptions = function (value, options) { + var oo = typeof options == 'object' + , os = !oo && typeof options == 'string' + , op = function (p) { + return oo + ? !!options[p] + : os + ? options.indexOf(p[0]) > -1 + : false + } + + return { + enumerable : op('enumerable') + , configurable : op('configurable') + , writable : op('writable') + , value : value + } + } + + , prr = function (obj, key, value, options) { + var k + + options = makeOptions(value, options) + + if (typeof key == 'object') { + for (k in key) { + if (Object.hasOwnProperty.call(key, k)) { + options.value = key[k] + setProperty(obj, k, options) + } + } + return obj + } + + return setProperty(obj, key, options) + } + + return prr +}) + +/***/ }), + +/***/ 79822: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(76417).randomBytes + + +/***/ }), + +/***/ 42770: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(58404); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ + +var Readable = __webpack_require__(79341); +var Writable = __webpack_require__(78063); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 60143: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(62826); + +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 79341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(58404); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(21352); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(28614).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(1065); +/**/ + +/**/ + +var Buffer = __webpack_require__(96788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ + +/**/ +var debugUtil = __webpack_require__(31669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(28878); +var destroyImpl = __webpack_require__(87915); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(42770); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 62826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(42770); + +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 78063: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(58404); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(92262) +}; +/**/ + +/**/ +var Stream = __webpack_require__(1065); +/**/ + +/**/ + +var Buffer = __webpack_require__(96788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(87915); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(42770); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 28878: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(96788).Buffer; +var util = __webpack_require__(31669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 87915: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(58404); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + 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(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 1065: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(92413); + + +/***/ }), + +/***/ 96788: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(64293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 7395: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(96788).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 68193: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(92413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(79341); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(78063); + exports.Duplex = __webpack_require__(42770); + exports.Transform = __webpack_require__(62826); + exports.PassThrough = __webpack_require__(60143); +} + + +/***/ }), + +/***/ 30931: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var extend = __webpack_require__(39700); +var safe = __webpack_require__(71217); + +/** + * The main export is a function that takes a `pattern` string and an `options` object. + * + * ```js + & var not = require('regex-not'); + & console.log(not('foo')); + & //=> /^(?:(?!^(?:foo)$).)*$/ + * ``` + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. + * @api public + */ + +function toRegex(pattern, options) { + return new RegExp(toRegex.create(pattern, options)); +} + +/** + * Create a regex-compatible string from the given `pattern` and `options`. + * + * ```js + & var not = require('regex-not'); + & console.log(not.create('foo')); + & //=> '^(?:(?!^(?:foo)$).)*$' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public + */ + +toRegex.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + var opts = extend({}, options); + if (opts.contains === true) { + opts.strictNegate = false; + } + + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var endChar = opts.endChar ? opts.endChar : '+'; + var str = pattern; + + if (opts.strictNegate === false) { + str = '(?:(?!(?:' + pattern + ')).)' + endChar; + } else { + str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; + } + + var res = open + str + close; + if (opts.safe === true && safe(res) === false) { + throw new Error('potentially unsafe regular expression: ' + res); + } + + return res; +}; + +/** + * Expose `toRegex` + */ + +module.exports = toRegex; + + +/***/ }), + +/***/ 39700: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(93295); +var assignSymbols = __webpack_require__(64353); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), + +/***/ 93295: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 69523: +/***/ ((module) => { + +"use strict"; +/*! + * repeat-element + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Licensed under the MIT license. + */ + + + +module.exports = function repeat(ele, num) { + var arr = new Array(num); + + for (var i = 0; i < num; i++) { + arr[i] = ele; + } + + return arr; +}; + + +/***/ }), + +/***/ 6332: +/***/ ((module) => { + +"use strict"; +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +/** + * Results cache + */ + +var res = ''; +var cache; + +/** + * Expose `repeat` + */ + +module.exports = repeat; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } + + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } + + num >>= 1; + str += str; + } + + res += str; + res = res.substr(0, max); + return res; +} + + +/***/ }), + +/***/ 25622: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var util = __webpack_require__(10265); +var types = __webpack_require__(40432); +var sets = __webpack_require__(28135); +var positions = __webpack_require__(54771); + + +module.exports = function(regexpStr) { + var i = 0, l, c, + start = { type: types.ROOT, stack: []}, + + // Keep track of last clause/group and stack. + lastGroup = start, + last = start.stack, + groupStack = []; + + + var repeatErr = function(i) { + util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); + }; + + // Decode a few escaped characters. + var str = util.strToChars(regexpStr); + l = str.length; + + // Iterate through each character in string. + while (i < l) { + c = str[i++]; + + switch (c) { + // Handle escaped characters, inclues a few sets. + case '\\': + c = str[i++]; + + switch (c) { + case 'b': + last.push(positions.wordBoundary()); + break; + + case 'B': + last.push(positions.nonWordBoundary()); + break; + + case 'w': + last.push(sets.words()); + break; + + case 'W': + last.push(sets.notWords()); + break; + + case 'd': + last.push(sets.ints()); + break; + + case 'D': + last.push(sets.notInts()); + break; + + case 's': + last.push(sets.whitespace()); + break; + + case 'S': + last.push(sets.notWhitespace()); + break; + + default: + // Check if c is integer. + // In which case it's a reference. + if (/\d/.test(c)) { + last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); + + // Escaped character. + } else { + last.push({ type: types.CHAR, value: c.charCodeAt(0) }); + } + } + + break; + + + // Positionals. + case '^': + last.push(positions.begin()); + break; + + case '$': + last.push(positions.end()); + break; + + + // Handle custom sets. + case '[': + // Check if this class is 'anti' i.e. [^abc]. + var not; + if (str[i] === '^') { + not = true; + i++; + } else { + not = false; + } + + // Get all the characters in class. + var classTokens = util.tokenizeClass(str.slice(i), regexpStr); + + // Increase index by length of class. + i += classTokens[1]; + last.push({ + type: types.SET, + set: classTokens[0], + not: not, + }); + + break; + + + // Class of any character except \n. + case '.': + last.push(sets.anyChar()); + break; + + + // Push group onto stack. + case '(': + // Create group. + var group = { + type: types.GROUP, + stack: [], + remember: true, + }; + + c = str[i]; + + // If if this is a special kind of group. + if (c === '?') { + c = str[i + 1]; + i += 2; + + // Match if followed by. + if (c === '=') { + group.followedBy = true; + + // Match if not followed by. + } else if (c === '!') { + group.notFollowedBy = true; + + } else if (c !== ':') { + util.error(regexpStr, + 'Invalid group, character \'' + c + + '\' after \'?\' at column ' + (i - 1)); + } + + group.remember = false; + } + + // Insert subgroup into current group stack. + last.push(group); + + // Remember the current group for when the group closes. + groupStack.push(lastGroup); + + // Make this new group the current group. + lastGroup = group; + last = group.stack; + break; + + + // Pop group out of stack. + case ')': + if (groupStack.length === 0) { + util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); + } + lastGroup = groupStack.pop(); + + // Check if this group has a PIPE. + // To get back the correct last stack. + last = lastGroup.options ? + lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; + break; + + + // Use pipe character to give more choices. + case '|': + // Create array where options are if this is the first PIPE + // in this clause. + if (!lastGroup.options) { + lastGroup.options = [lastGroup.stack]; + delete lastGroup.stack; + } + + // Create a new stack and add to options for rest of clause. + var stack = []; + lastGroup.options.push(stack); + last = stack; + break; + + + // Repetition. + // For every repetition, remove last element from last stack + // then insert back a RANGE object. + // This design is chosen because there could be more than + // one repetition symbols in a regex i.e. `a?+{2,3}`. + case '{': + var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; + if (rs !== null) { + if (last.length === 0) { + repeatErr(i); + } + min = parseInt(rs[1], 10); + max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; + i += rs[0].length; + + last.push({ + type: types.REPETITION, + min: min, + max: max, + value: last.pop(), + }); + } else { + last.push({ + type: types.CHAR, + value: 123, + }); + } + break; + + case '?': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: 1, + value: last.pop(), + }); + break; + + case '+': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 1, + max: Infinity, + value: last.pop(), + }); + break; + + case '*': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: Infinity, + value: last.pop(), + }); + break; + + + // Default is a character that is not `\[](){}?+*^$`. + default: + last.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); + } + + } + + // Check if any groups have not been closed. + if (groupStack.length !== 0) { + util.error(regexpStr, 'Unterminated group'); + } + + return start; +}; + +module.exports.types = types; + + +/***/ }), + +/***/ 54771: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var types = __webpack_require__(40432); + +exports.wordBoundary = function() { + return { type: types.POSITION, value: 'b' }; +}; + +exports.nonWordBoundary = function() { + return { type: types.POSITION, value: 'B' }; +}; + +exports.begin = function() { + return { type: types.POSITION, value: '^' }; +}; + +exports.end = function() { + return { type: types.POSITION, value: '$' }; +}; + + +/***/ }), + +/***/ 28135: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var types = __webpack_require__(40432); + +var INTS = function() { + return [{ type: types.RANGE , from: 48, to: 57 }]; +}; + +var WORDS = function() { + return [ + { type: types.CHAR, value: 95 }, + { type: types.RANGE, from: 97, to: 122 }, + { type: types.RANGE, from: 65, to: 90 } + ].concat(INTS()); +}; + +var WHITESPACE = function() { + return [ + { type: types.CHAR, value: 9 }, + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 11 }, + { type: types.CHAR, value: 12 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 32 }, + { type: types.CHAR, value: 160 }, + { type: types.CHAR, value: 5760 }, + { type: types.CHAR, value: 6158 }, + { type: types.CHAR, value: 8192 }, + { type: types.CHAR, value: 8193 }, + { type: types.CHAR, value: 8194 }, + { type: types.CHAR, value: 8195 }, + { type: types.CHAR, value: 8196 }, + { type: types.CHAR, value: 8197 }, + { type: types.CHAR, value: 8198 }, + { type: types.CHAR, value: 8199 }, + { type: types.CHAR, value: 8200 }, + { type: types.CHAR, value: 8201 }, + { type: types.CHAR, value: 8202 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + { type: types.CHAR, value: 8239 }, + { type: types.CHAR, value: 8287 }, + { type: types.CHAR, value: 12288 }, + { type: types.CHAR, value: 65279 } + ]; +}; + +var NOTANYCHAR = function() { + return [ + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + ]; +}; + +// Predefined class objects. +exports.words = function() { + return { type: types.SET, set: WORDS(), not: false }; +}; + +exports.notWords = function() { + return { type: types.SET, set: WORDS(), not: true }; +}; + +exports.ints = function() { + return { type: types.SET, set: INTS(), not: false }; +}; + +exports.notInts = function() { + return { type: types.SET, set: INTS(), not: true }; +}; + +exports.whitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: false }; +}; + +exports.notWhitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: true }; +}; + +exports.anyChar = function() { + return { type: types.SET, set: NOTANYCHAR(), not: true }; +}; + + +/***/ }), + +/***/ 40432: +/***/ ((module) => { + +module.exports = { + ROOT : 0, + GROUP : 1, + POSITION : 2, + SET : 3, + RANGE : 4, + REPETITION : 5, + REFERENCE : 6, + CHAR : 7, +}; + + +/***/ }), + +/***/ 10265: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var types = __webpack_require__(40432); +var sets = __webpack_require__(28135); + + +// All of these are private and only used by randexp. +// It's assumed that they will always be called with the correct input. + +var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; +var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; + +/** + * Finds character representations in str and convert all to + * their respective characters + * + * @param {String} str + * @return {String} + */ +exports.strToChars = function(str) { + /* jshint maxlen: false */ + var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; + str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { + if (lbs) { + return s; + } + + var code = b ? 8 : + a16 ? parseInt(a16, 16) : + b16 ? parseInt(b16, 16) : + c8 ? parseInt(c8, 8) : + dctrl ? CTRL.indexOf(dctrl) : + SLSH[eslsh]; + + var c = String.fromCharCode(code); + + // Escape special regex characters. + if (/[\[\]{}\^$.|?*+()]/.test(c)) { + c = '\\' + c; + } + + return c; + }); + + return str; +}; + + +/** + * turns class into tokens + * reads str until it encounters a ] not preceeded by a \ + * + * @param {String} str + * @param {String} regexpStr + * @return {Array., Number>} + */ +exports.tokenizeClass = function(str, regexpStr) { + /* jshint maxlen: false */ + var tokens = []; + var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; + var rs, c; + + + while ((rs = regexp.exec(str)) != null) { + if (rs[1]) { + tokens.push(sets.words()); + + } else if (rs[2]) { + tokens.push(sets.ints()); + + } else if (rs[3]) { + tokens.push(sets.whitespace()); + + } else if (rs[4]) { + tokens.push(sets.notWords()); + + } else if (rs[5]) { + tokens.push(sets.notInts()); + + } else if (rs[6]) { + tokens.push(sets.notWhitespace()); + + } else if (rs[7]) { + tokens.push({ + type: types.RANGE, + from: (rs[8] || rs[9]).charCodeAt(0), + to: rs[10].charCodeAt(0), + }); + + } else if (c = rs[12]) { + tokens.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); + + } else { + return [tokens, regexp.lastIndex]; + } + } + + exports.error(regexpStr, 'Unterminated character class'); +}; + + +/** + * Shortcut to throw errors. + * + * @param {String} regexp + * @param {String} msg + */ +exports.error = function(regexp, msg) { + throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); +}; + + +/***/ }), + +/***/ 71217: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parse = __webpack_require__(25622); +var types = parse.types; + +module.exports = function (re, opts) { + if (!opts) opts = {}; + var replimit = opts.limit === undefined ? 25 : opts.limit; + + if (isRegExp(re)) re = re.source; + else if (typeof re !== 'string') re = String(re); + + try { re = parse(re) } + catch (err) { return false } + + var reps = 0; + return (function walk (node, starHeight) { + if (node.type === types.REPETITION) { + starHeight ++; + reps ++; + if (starHeight > 1) return false; + if (reps > replimit) return false; + } + + if (node.options) { + for (var i = 0, len = node.options.length; i < len; i++) { + var ok = walk({ stack: node.options[i] }, starHeight); + if (!ok) return false; + } + } + var stack = node.stack || (node.value && node.value.stack); + if (!stack) return true; + + for (var i = 0; i < stack.length; i++) { + var ok = walk(stack[i], starHeight); + if (!ok) return false; + } + + return true; + })(re, 0); +}; + +function isRegExp (x) { + return {}.toString.call(x) === '[object RegExp]'; +} + + +/***/ }), + +/***/ 85841: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ + + + +var randomBytes = __webpack_require__(79822); + +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I)-' + UID + '-(\\d+)__@"', 'g'); + +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; + +var RESERVED_SYMBOLS = ['*', 'async']; + +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; +} + +function generateUID() { + var bytes = randomBytes(UID_LENGTH); + var result = ''; + for(var i=0; i arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); + + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } + + // arrow functions + return serializedFn; + } + + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } + + var str; + + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0) { + return str; + } + + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } + + if (type === 'D') { + return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; + } + + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } + + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } + + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } + + if (type === 'U') { + return 'undefined' + } + + if (type === 'I') { + return infinities[valueIndex]; + } + + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); +} + + +/***/ }), + +/***/ 34857: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var split = __webpack_require__(33218); +var extend = __webpack_require__(28727); +var isPlainObject = __webpack_require__(81064); +var isObject = __webpack_require__(18493); + +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; + } + + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); + } + + if (typeof prop !== 'string') { + return obj; + } + + var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); + var len = keys.length; + var idx = -1; + var current = obj; + + while (++idx < len) { + var key = keys[idx]; + if (idx !== len - 1) { + if (!isObject(current[key])) { + current[key] = {}; + } + current = current[key]; + continue; + } + + if (isPlainObject(current[key]) && isPlainObject(val)) { + current[key] = extend({}, current[key], val); + } else { + current[key] = val; + } + } + + return obj; +}; + +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +} + + +/***/ }), + +/***/ 12579: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +var isObject = __webpack_require__(96667); +var define = __webpack_require__(88599); +var utils = __webpack_require__(82071); +var ownNames; + +/** + * Create a new AST `Node` with the given `val` and `type`. + * + * ```js + * var node = new Node('*', 'Star'); + * var node = new Node({type: 'star', val: '*'}); + * ``` + * @name Node + * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. + * @param {String} `type` The node type to use when `val` is a string. + * @return {Object} node instance + * @api public + */ + +function Node(val, type, parent) { + if (typeof type !== 'string') { + parent = type; + type = null; + } + + define(this, 'parent', parent); + define(this, 'isNode', true); + define(this, 'expect', null); + + if (typeof type !== 'string' && isObject(val)) { + lazyKeys(); + var keys = Object.keys(val); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (ownNames.indexOf(key) === -1) { + this[key] = val[key]; + } + } + } else { + this.type = type; + this.val = val; + } +} + +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(Node.isNode(node)); //=> true + * console.log(Node.isNode({})); //=> false + * ``` + * @param {Object} `node` + * @returns {Boolean} + * @api public + */ + +Node.isNode = function(node) { + return utils.isNode(node); +}; + +/** + * Define a non-enumberable property on the node instance. + * Useful for adding properties that shouldn't be extended + * or visible during debugging. + * + * ```js + * var node = new Node(); + * node.define('foo', 'something non-enumerable'); + * ``` + * @param {String} `name` + * @param {any} `val` + * @return {Object} returns the node instance + * @api public + */ + +Node.prototype.define = function(name, val) { + define(this, name, val); + return this; +}; + +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * node.isEmpty(); //=> true + * node.val = 'foo'; + * node.isEmpty(); //=> false + * ``` + * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. + * @return {Boolean} + * @api public + */ + +Node.prototype.isEmpty = function(fn) { + return utils.isEmpty(this, fn); +}; + +/** + * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ + +Node.prototype.push = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); + + this.nodes = this.nodes || []; + return this.nodes.push(node); +}; + +/** + * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.unshift(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ + +Node.prototype.unshift = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); + + this.nodes = this.nodes || []; + return this.nodes.unshift(node); +}; + +/** + * Pop a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.pop(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Number} Returns the popped `node` + * @api public + */ + +Node.prototype.pop = function() { + return this.nodes && this.nodes.pop(); +}; + +/** + * Shift a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.shift(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Object} Returns the shifted `node` + * @api public + */ + +Node.prototype.shift = function() { + return this.nodes && this.nodes.shift(); +}; + +/** + * Remove `node` from `node.nodes`. + * + * ```js + * node.remove(childNode); + * ``` + * @param {Object} `node` + * @return {Object} Returns the removed node. + * @api public + */ + +Node.prototype.remove = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + this.nodes = this.nodes || []; + var idx = node.index; + if (idx !== -1) { + node.index = -1; + return this.nodes.splice(idx, 1); + } + return null; +}; + +/** + * Get the first child node from `node.nodes` that matches the given `type`. + * If `type` is a number, the child node at that index is returned. + * + * ```js + * var child = node.find(1); //<= index of the node to get + * var child = node.find('foo'); //<= node.type of a child node + * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type + * var child = node.find(['foo', 'bar']); //<= array of node.type(s) + * ``` + * @param {String} `type` + * @return {Object} Returns a child node or undefined. + * @api public + */ + +Node.prototype.find = function(type) { + return utils.findNode(this.nodes, type); +}; + +/** + * Return true if the node is the given `type`. + * + * ```js + * var node = new Node({type: 'bar'}); + * cosole.log(node.isType('foo')); // false + * cosole.log(node.isType(/^(foo|bar)$/)); // true + * cosole.log(node.isType(['foo', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +Node.prototype.isType = function(type) { + return utils.isType(this, type); +}; + +/** + * Return true if the `node.nodes` has the given `type`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * + * cosole.log(foo.hasType('qux')); // false + * cosole.log(foo.hasType(/^(qux|bar)$/)); // true + * cosole.log(foo.hasType(['qux', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +Node.prototype.hasType = function(type) { + return utils.hasType(this, type); +}; + +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Array} + * @api public + */ + +Object.defineProperty(Node.prototype, 'siblings', { + set: function() { + throw new Error('node.siblings is a getter and cannot be defined'); + }, + get: function() { + return this.parent ? this.parent.nodes : null; + } +}); + +/** + * Get the node's current index from `node.parent.nodes`. + * This should always be correct, even when the parent adds nodes. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.unshift(qux); + * + * console.log(bar.index) // 1 + * console.log(baz.index) // 2 + * console.log(qux.index) // 0 + * ``` + * @return {Number} + * @api public + */ + +Object.defineProperty(Node.prototype, 'index', { + set: function(index) { + define(this, 'idx', index); + }, + get: function() { + if (!Array.isArray(this.siblings)) { + return -1; + } + var tok = this.idx !== -1 ? this.siblings[this.idx] : null; + if (tok !== this) { + this.idx = this.siblings.indexOf(this); + } + return this.idx; + } +}); + +/** + * Get the previous node from the siblings array or `null`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(baz.prev.type) // 'bar' + * ``` + * @return {Object} + * @api public + */ + +Object.defineProperty(Node.prototype, 'prev', { + set: function() { + throw new Error('node.prev is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index - 1] || this.parent.prev; + } + return null; + } +}); + +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Object} + * @api public + */ + +Object.defineProperty(Node.prototype, 'next', { + set: function() { + throw new Error('node.next is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index + 1] || this.parent.next; + } + return null; + } +}); + +/** + * Get the first node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.first.type) // 'bar' + * ``` + * @return {Object} The first node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'first', { + get: function() { + return this.nodes ? this.nodes[0] : null; + } +}); + +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'last', { + get: function() { + return this.nodes ? utils.last(this.nodes) : null; + } +}); + +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'scope', { + get: function() { + if (this.isScope !== true) { + return this.parent ? this.parent.scope : this; + } + return this; + } +}); + +/** + * Get own property names from Node prototype, but only the + * first time `Node` is instantiated + */ + +function lazyKeys() { + if (!ownNames) { + ownNames = Object.getOwnPropertyNames(Node.prototype); + } +} + +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ + +function assert(val, message) { + if (!val) throw new Error(message); +} + +/** + * Expose `Node` + */ + +exports = module.exports = Node; + + +/***/ }), + +/***/ 88599: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(44133); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), + +/***/ 82071: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var typeOf = __webpack_require__(48865); +var utils = module.exports; + +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isNode(node)); //=> true + * console.log(utils.isNode({})); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Boolean} + * @api public + */ + +utils.isNode = function(node) { + return typeOf(node) === 'object' && node.isNode === true; +}; + +/** + * Emit an empty string for the given `node`. + * + * ```js + * // do nothing for beginning-of-string + * snapdragon.compiler.set('bos', utils.noop); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ + +utils.noop = function(node) { + append(this, '', node); +}; + +/** + * Appdend `node.val` to `compiler.output`, exactly as it was created + * by the parser. + * + * ```js + * snapdragon.compiler.set('text', utils.identity); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ + +utils.identity = function(node) { + append(this, node.val, node); +}; + +/** + * Previously named `.emit`, this method appends the given `val` + * to `compiler.output` for the given node. Useful when you know + * what value should be appended advance, regardless of the actual + * value of `node.val`. + * + * ```js + * snapdragon.compiler + * .set('i', function(node) { + * this.mapVisit(node); + * }) + * .set('i.open', utils.append('')) + * .set('i.close', utils.append('')) + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Function} Returns a compiler middleware function. + * @api public + */ + +utils.append = function(val) { + return function(node) { + append(this, val, node); + }; +}; + +/** + * Used in compiler middleware, this onverts an AST node into + * an empty `text` node and deletes `node.nodes` if it exists. + * The advantage of this method is that, as opposed to completely + * removing the node, indices will not need to be re-calculated + * in sibling nodes, and nothing is appended to the output. + * + * ```js + * utils.toNoop(node); + * // convert `node.nodes` to the given value instead of deleting it + * utils.toNoop(node, []); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. + * @api public + */ + +utils.toNoop = function(node, nodes) { + if (nodes) { + node.nodes = nodes; + } else { + delete node.nodes; + node.type = 'text'; + node.val = ''; + } +}; + +/** + * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon + * automatically calls registered compilers, this allows you to pass a visitor + * function. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.visit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Object} returns the node after recursively visiting all child nodes. + * @api public + */ + +utils.visit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(fn), 'expected a visitor function'); + fn(node); + return node.nodes ? utils.mapVisit(node, fn) : node; +}; + +/** + * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by + * [visit](#visit), use this method if you do not want `fn` to be called on + * the first node. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.mapVisit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Object} `options` + * @param {Function} `fn` + * @return {Object} returns the node + * @api public + */ + +utils.mapVisit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isArray(node.nodes), 'expected node.nodes to be an array'); + assert(isFunction(fn), 'expected a visitor function'); + + for (var i = 0; i < node.nodes.length; i++) { + utils.visit(node.nodes[i], fn); + } + return node; +}; + +/** + * Unshift an `*.open` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^{/); + * if (match) { + * var parent = new Node({type: 'brace'}); + * utils.addOpen(parent, Node); + * console.log(parent.nodes[0]): + * // { type: 'brace.open', val: '' }; + * + * // push the parent "brace" node onto the stack + * this.push(parent); + * + * // return the parent node, so it's also added to the AST + * return brace; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created opening node. + * @api public + */ + +utils.addOpen = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + if (typeof val === 'function') { + filter = val; + val = ''; + } + + if (typeof filter === 'function' && !filter(node)) return; + var open = new Node({ type: node.type + '.open', val: val}); + var unshift = node.unshift || node.unshiftNode; + if (typeof unshift === 'function') { + unshift.call(node, open); + } else { + utils.unshiftNode(node, open); + } + return open; +}; + +/** + * Push a `*.close` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^}/); + * if (match) { + * var parent = this.parent(); + * if (parent.type !== 'brace') { + * throw new Error('missing opening: ' + '}'); + * } + * + * utils.addClose(parent, Node); + * console.log(parent.nodes[parent.nodes.length - 1]): + * // { type: 'brace.close', val: '' }; + * + * // no need to return a node, since the parent + * // was already added to the AST + * return; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created closing node. + * @api public + */ + +utils.addClose = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + if (typeof val === 'function') { + filter = val; + val = ''; + } + + if (typeof filter === 'function' && !filter(node)) return; + var close = new Node({ type: node.type + '.close', val: val}); + var push = node.push || node.pushNode; + if (typeof push === 'function') { + push.call(node, close); + } else { + utils.pushNode(node, close); + } + return close; +}; + +/** + * Wraps the given `node` with `*.open` and `*.close` nodes. + * + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the node + * @api public + */ + +utils.wrapNodes = function(node, Node, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + utils.addOpen(node, Node, filter); + utils.addClose(node, Node, filter); + return node; +}; + +/** + * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.pushNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object} Returns the child node + * @api public + */ + +utils.pushNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.push(node); + return node; +}; + +/** + * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.unshiftNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {undefined} + * @api public + */ + +utils.unshiftNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.unshift(node); +}; + +/** + * Pop the last `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.popNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ + +utils.popNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.pop === 'function') { + return node.pop(); + } + return node.nodes && node.nodes.pop(); +}; + +/** + * Shift the first `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.shiftNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ + +utils.shiftNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.shift === 'function') { + return node.shift(); + } + return node.nodes && node.nodes.shift(); +}; + +/** + * Remove the specified `node` from `parent.nodes`. + * + * ```js + * var parent = new Node({type: 'abc'}); + * var foo = new Node({type: 'foo'}); + * utils.pushNode(parent, foo); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.removeNode(parent, foo); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. + * @api public + */ + +utils.removeNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + if (!parent.nodes) { + return null; + } + + if (typeof parent.remove === 'function') { + return parent.remove(node); + } + + var idx = parent.nodes.indexOf(node); + if (idx !== -1) { + return parent.nodes.splice(idx, 1); + } +}; + +/** + * Returns true if `node.type` matches the given `type`. Throws a + * `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isType(node, 'foo')); // false + * console.log(utils.isType(node, 'bar')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.isType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + switch (typeOf(type)) { + case 'array': + var types = type.slice(); + for (var i = 0; i < types.length; i++) { + if (utils.isType(node, types[i])) { + return true; + } + } + return false; + case 'string': + return node.type === type; + case 'regexp': + return type.test(node.type); + default: { + throw new TypeError('expected "type" to be an array, string or regexp'); + } + } +}; + +/** + * Returns true if the given `node` has the given `type` in `node.nodes`. + * Throws a `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'bar'}), + * new Node({type: 'baz'}) + * ] + * }); + * console.log(utils.hasType(node, 'xyz')); // false + * console.log(utils.hasType(node, 'baz')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.hasType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (!Array.isArray(node.nodes)) return false; + for (var i = 0; i < node.nodes.length; i++) { + if (utils.isType(node.nodes[i], type)) { + return true; + } + } + return false; +}; + +/** + * Returns the first node from `node.nodes` of the given `type` + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var textNode = utils.firstOfType(node.nodes, 'text'); + * console.log(textNode.val); + * //=> 'abc' + * ``` + * @param {Array} `nodes` + * @param {String} `type` + * @return {Object|undefined} Returns the first matching node or undefined. + * @api public + */ + +utils.firstOfType = function(nodes, type) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (utils.isType(node, type)) { + return node; + } + } +}; + +/** + * Returns the node at the specified index, or the first node of the + * given `type` from `node.nodes`. + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var nodeOne = utils.findNode(node.nodes, 'text'); + * console.log(nodeOne.val); + * //=> 'abc' + * + * var nodeTwo = utils.findNode(node.nodes, 1); + * console.log(nodeTwo.val); + * //=> 'xyz' + * ``` + * + * @param {Array} `nodes` + * @param {String|Number} `type` Node type or index. + * @return {Object} Returns a node or undefined. + * @api public + */ + +utils.findNode = function(nodes, type) { + if (!Array.isArray(nodes)) { + return null; + } + if (typeof type === 'number') { + return nodes[type]; + } + return utils.firstOfType(nodes, type); +}; + +/** + * Returns true if the given node is an "*.open" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isOpen(brace)); // false + * console.log(utils.isOpen(open)); // true + * console.log(utils.isOpen(close)); // false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.isOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-5) === '.open'; +}; + +/** + * Returns true if the given node is a "*.close" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isClose(brace)); // false + * console.log(utils.isClose(open)); // false + * console.log(utils.isClose(close)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.isClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-6) === '.close'; +}; + +/** + * Returns true if `node.nodes` **has** an `.open` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * console.log(utils.hasOpen(brace)); // false + * + * brace.pushNode(open); + * console.log(utils.hasOpen(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var first = node.first || node.nodes ? node.nodes[0] : null; + if (utils.isNode(first)) { + return first.type === node.type + '.open'; + } + return false; +}; + +/** + * Returns true if `node.nodes` **has** a `.close` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(close); + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; + if (utils.isNode(last)) { + return last.type === node.type + '.close'; + } + return false; +}; + +/** + * Returns true if `node.nodes` has both `.open` and `.close` nodes + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasOpen(brace)); // false + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(open); + * brace.pushNode(close); + * console.log(utils.hasOpen(brace)); // true + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasOpenAndClose = function(node) { + return utils.hasOpen(node) && utils.hasClose(node); +}; + +/** + * Push the given `node` onto the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ + +utils.addType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.open$/, ''); + + if (!state.hasOwnProperty('inside')) { + state.inside = {}; + } + if (!state.inside.hasOwnProperty(type)) { + state.inside[type] = []; + } + + var arr = state.inside[type]; + arr.push(node); + return arr; +}; + +/** + * Remove the given `node` from the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * utils.removeType(state, node); + * //=> { brace: [] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ + +utils.removeType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.close$/, ''); + + if (state.inside.hasOwnProperty(type)) { + return state.inside[type].pop(); + } +}; + +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * utils.isEmpty(node); //=> true + * node.val = 'foo'; + * utils.isEmpty(node); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Boolean} + * @api public + */ + +utils.isEmpty = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + if (!Array.isArray(node.nodes)) { + if (node.type !== 'text') { + return true; + } + if (typeof fn === 'function') { + return fn(node, node.parent); + } + return !utils.trim(node.val); + } + + for (var i = 0; i < node.nodes.length; i++) { + var child = node.nodes[i]; + if (utils.isOpen(child) || utils.isClose(child)) { + continue; + } + if (!utils.isEmpty(child, fn)) { + return false; + } + } + + return true; +}; + +/** + * Returns true if the `state.inside` stack for the given type exists + * and has one or more nodes on it. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * utils.addType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> true + * utils.removeType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * ``` + * @param {Object} `state` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.isInsideType = function(state, type) { + assert(isObject(state), 'expected state to be an object'); + assert(isString(type), 'expected type to be a string'); + + if (!state.hasOwnProperty('inside')) { + return false; + } + + if (!state.inside.hasOwnProperty(type)) { + return false; + } + + return state.inside[type].length > 0; +}; + +/** + * Returns true if `node` is either a child or grand-child of the given `type`, + * or `state.inside[type]` is a non-empty array. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * console.log(utils.isInside(state, open, 'brace')); //=> false + * utils.pushNode(node, open); + * console.log(utils.isInside(state, open, 'brace')); //=> true + * ``` + * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` The `node.type` to check for. + * @return {Boolean} + * @api public + */ + +utils.isInside = function(state, node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i++) { + if (utils.isInside(state, node, type[i])) { + return true; + } + } + return false; + } + + var parent = node.parent; + if (typeof type === 'string') { + return (parent && parent.type === type) || utils.isInsideType(state, type); + } + + if (typeOf(type) === 'regexp') { + if (parent && parent.type && type.test(parent.type)) { + return true; + } + + var keys = Object.keys(state.inside); + var len = keys.length; + var idx = -1; + while (++idx < len) { + var key = keys[idx]; + var val = state.inside[key]; + + if (Array.isArray(val) && val.length !== 0 && type.test(key)) { + return true; + } + } + } + return false; +}; + +/** + * Get the last `n` element from the given `array`. Used for getting + * a node from `node.nodes.` + * + * @param {Array} `array` + * @param {Number} `n` + * @return {undefined} + * @api public + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +/** + * Cast the given `val` to an array. + * + * ```js + * console.log(utils.arrayify('')); + * //=> [] + * console.log(utils.arrayify('foo')); + * //=> ['foo'] + * console.log(utils.arrayify(['foo'])); + * //=> ['foo'] + * ``` + * @param {any} `val` + * @return {Array} + * @api public + */ + +utils.arrayify = function(val) { + if (typeof val === 'string' && val !== '') { + return [val]; + } + if (!Array.isArray(val)) { + return []; + } + return val; +}; + +/** + * Convert the given `val` to a string by joining with `,`. Useful + * for creating a cheerio/CSS/DOM-style selector from a list of strings. + * + * @param {any} `val` + * @return {Array} + * @api public + */ + +utils.stringify = function(val) { + return utils.arrayify(val).join(','); +}; + +/** + * Ensure that the given value is a string and call `.trim()` on it, + * or return an empty string. + * + * @param {String} `str` + * @return {String} + * @api public + */ + +utils.trim = function(str) { + return typeof str === 'string' ? str.trim() : ''; +}; + +/** + * Return true if val is an object + */ + +function isObject(val) { + return typeOf(val) === 'object'; +} + +/** + * Return true if val is a string + */ + +function isString(val) { + return typeof val === 'string'; +} + +/** + * Return true if val is a function + */ + +function isFunction(val) { + return typeof val === 'function'; +} + +/** + * Return true if val is an array + */ + +function isArray(val) { + return Array.isArray(val); +} + +/** + * Shim to ensure the `.append` methods work with any version of snapdragon + */ + +function append(compiler, val, node) { + if (typeof compiler.append !== 'function') { + return compiler.emit(val, node); + } + return compiler.append(val, node); +} + +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ + +function assert(val, message) { + if (!val) throw new Error(message); +} + + +/***/ }), + +/***/ 79285: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Base = __webpack_require__(87263); +var define = __webpack_require__(5477); +var Compiler = __webpack_require__(33003); +var Parser = __webpack_require__(35573); +var utils = __webpack_require__(622); +var regexCache = {}; +var cache = {}; + +/** + * Create a new instance of `Snapdragon` with the given `options`. + * + * ```js + * var snapdragon = new Snapdragon(); + * ``` + * + * @param {Object} `options` + * @api public + */ + +function Snapdragon(options) { + Base.call(this, null, options); + this.options = utils.extend({source: 'string'}, this.options); + this.compiler = new Compiler(this.options); + this.parser = new Parser(this.options); + + Object.defineProperty(this, 'compilers', { + get: function() { + return this.compiler.compilers; + } + }); + + Object.defineProperty(this, 'parsers', { + get: function() { + return this.parser.parsers; + } + }); + + Object.defineProperty(this, 'regex', { + get: function() { + return this.parser.regex; + } + }); +} + +/** + * Inherit Base + */ + +Base.extend(Snapdragon); + +/** + * Add a parser to `snapdragon.parsers` for capturing the given `type` using + * the specified regex or parser function. A function is useful if you need + * to customize how the token is created and/or have access to the parser + * instance to check options, etc. + * + * ```js + * snapdragon + * .capture('slash', /^\//) + * .capture('dot', function() { + * var pos = this.position(); + * var m = this.match(/^\./); + * if (!m) return; + * return pos({ + * type: 'dot', + * val: m[0] + * }); + * }); + * ``` + * @param {String} `type` + * @param {RegExp|Function} `regex` + * @return {Object} Returns the parser instance for chaining + * @api public + */ + +Snapdragon.prototype.capture = function() { + return this.parser.capture.apply(this.parser, arguments); +}; + +/** + * Register a plugin `fn`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * snapdragon.use(function() { + * console.log(this); //<= snapdragon instance + * console.log(this.parser); //<= parser instance + * console.log(this.compiler); //<= compiler instance + * }); + * ``` + * @param {Object} `fn` + * @api public + */ + +Snapdragon.prototype.use = function(fn) { + fn.call(this, this); + return this; +}; + +/** + * Parse the given `str`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register parsers + * snapdragon.parser.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * console.log(ast); + * ``` + * @param {String} `str` + * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. + * @return {Object} Returns an AST. + * @api public + */ + +Snapdragon.prototype.parse = function(str, options) { + this.options = utils.extend({}, this.options, options); + var parsed = this.parser.parse(str, this.options); + + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; +}; + +/** + * Compile the given `AST`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register plugins + * snapdragon.use(function() {}); + * // register parser plugins + * snapdragon.parser.use(function() {}); + * // register compiler plugins + * snapdragon.compiler.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * + * // compile + * var res = snapdragon.compile(ast); + * console.log(res.output); + * ``` + * @param {Object} `ast` + * @param {Object} `options` + * @return {Object} Returns an object with an `output` property with the rendered string. + * @api public + */ + +Snapdragon.prototype.compile = function(ast, options) { + this.options = utils.extend({}, this.options, options); + var compiled = this.compiler.compile(ast, this.options); + + // add non-enumerable compiler reference + define(compiled, 'compiler', this.compiler); + return compiled; +}; + +/** + * Expose `Snapdragon` + */ + +module.exports = Snapdragon; + +/** + * Expose `Parser` and `Compiler` + */ + +module.exports.Compiler = Compiler; +module.exports.Parser = Parser; + + +/***/ }), + +/***/ 33003: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var use = __webpack_require__(77709); +var define = __webpack_require__(5477); +var debug = __webpack_require__(31185)('snapdragon:compiler'); +var utils = __webpack_require__(622); + +/** + * Create a new `Compiler` with the given `options`. + * @param {Object} `options` + */ + +function Compiler(options, state) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.state = state || {}; + this.compilers = {}; + this.output = ''; + this.set('eos', function(node) { + return this.emit(node.val, node); + }); + this.set('noop', function(node) { + return this.emit(node.val, node); + }); + this.set('bos', function(node) { + return this.emit(node.val, node); + }); + use(this); +} + +/** + * Prototype methods + */ + +Compiler.prototype = { + + /** + * Throw an error message with details including the cursor position. + * @param {String} `msg` Message to use in the Error. + */ + + error: function(msg, node) { + var pos = node.position || {start: {column: 0}}; + var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; + + var err = new Error(message); + err.reason = msg; + err.column = pos.start.column; + err.source = this.pattern; + + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, + + /** + * Define a non-enumberable property on the `Compiler` instance. + * + * ```js + * compiler.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Compiler instance for chaining. + * @api public + */ + + define: function(key, val) { + define(this, key, val); + return this; + }, + + /** + * Emit `node.val` + */ + + emit: function(str, node) { + this.output += str; + return str; + }, + + /** + * Add a compiler `fn` with the given `name` + */ + + set: function(name, fn) { + this.compilers[name] = fn; + return this; + }, + + /** + * Get compiler `name`. + */ + + get: function(name) { + return this.compilers[name]; + }, + + /** + * Get the previous AST node. + */ + + prev: function(n) { + return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; + }, + + /** + * Get the next AST node. + */ + + next: function(n) { + return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; + }, + + /** + * Visit `node`. + */ + + visit: function(node, nodes, i) { + var fn = this.compilers[node.type]; + this.idx = i; + + if (typeof fn !== 'function') { + throw this.error('compiler "' + node.type + '" is not registered', node); + } + return fn.call(this, node, nodes, i); + }, + + /** + * Map visit over array of `nodes`. + */ + + mapVisit: function(nodes) { + if (!Array.isArray(nodes)) { + throw new TypeError('expected an array'); + } + var len = nodes.length; + var idx = -1; + while (++idx < len) { + this.visit(nodes[idx], nodes, idx); + } + return this; + }, + + /** + * Compile `ast`. + */ + + compile: function(ast, options) { + var opts = utils.extend({}, this.options, options); + this.ast = ast; + this.parsingErrors = this.ast.errors; + this.output = ''; + + // source map support + if (opts.sourcemap) { + var sourcemaps = __webpack_require__(59657); + sourcemaps(this); + this.mapVisit(this.ast.nodes); + this.applySourceMaps(); + this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); + return this; + } + + this.mapVisit(this.ast.nodes); + return this; + } +}; + +/** + * Expose `Compiler` + */ + +module.exports = Compiler; + + +/***/ }), + +/***/ 35573: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var use = __webpack_require__(77709); +var util = __webpack_require__(31669); +var Cache = __webpack_require__(4337); +var define = __webpack_require__(5477); +var debug = __webpack_require__(31185)('snapdragon:parser'); +var Position = __webpack_require__(7974); +var utils = __webpack_require__(622); + +/** + * Create a new `Parser` with the given `input` and `options`. + * @param {String} `input` + * @param {Object} `options` + * @api public + */ + +function Parser(options) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.init(this.options); + use(this); +} + +/** + * Prototype methods + */ + +Parser.prototype = { + constructor: Parser, + + init: function(options) { + this.orig = ''; + this.input = ''; + this.parsed = ''; + + this.column = 1; + this.line = 1; + + this.regex = new Cache(); + this.errors = this.errors || []; + this.parsers = this.parsers || {}; + this.types = this.types || []; + this.sets = this.sets || {}; + this.fns = this.fns || []; + this.currentType = 'root'; + + var pos = this.position(); + this.bos = pos({type: 'bos', val: ''}); + + this.ast = { + type: 'root', + errors: this.errors, + nodes: [this.bos] + }; + + define(this.bos, 'parent', this.ast); + this.nodes = [this.ast]; + + this.count = 0; + this.setCount = 0; + this.stack = []; + }, + + /** + * Throw a formatted error with the cursor column and `msg`. + * @param {String} `msg` Message to use in the Error. + */ + + error: function(msg, node) { + var pos = node.position || {start: {column: 0, line: 0}}; + var line = pos.start.line; + var column = pos.start.column; + var source = this.options.source; + + var message = source + ' : ' + msg; + var err = new Error(message); + err.source = source; + err.reason = msg; + err.pos = pos; + + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, + + /** + * Define a non-enumberable property on the `Parser` instance. + * + * ```js + * parser.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Parser instance for chaining. + * @api public + */ + + define: function(key, val) { + define(this, key, val); + return this; + }, + + /** + * Mark position and patch `node.position`. + */ + + position: function() { + var start = { line: this.line, column: this.column }; + var self = this; + + return function(node) { + define(node, 'position', new Position(start, self)); + return node; + }; + }, + + /** + * Set parser `name` with the given `fn` + * @param {String} `name` + * @param {Function} `fn` + * @api public + */ + + set: function(type, fn) { + if (this.types.indexOf(type) === -1) { + this.types.push(type); + } + this.parsers[type] = fn.bind(this); + return this; + }, + + /** + * Get parser `name` + * @param {String} `name` + * @api public + */ + + get: function(name) { + return this.parsers[name]; + }, + + /** + * Push a `token` onto the `type` stack. + * + * @param {String} `type` + * @return {Object} `token` + * @api public + */ + + push: function(type, token) { + this.sets[type] = this.sets[type] || []; + this.count++; + this.stack.push(token); + return this.sets[type].push(token); + }, + + /** + * Pop a token off of the `type` stack + * @param {String} `type` + * @returns {Object} Returns a token + * @api public + */ + + pop: function(type) { + this.sets[type] = this.sets[type] || []; + this.count--; + this.stack.pop(); + return this.sets[type].pop(); + }, + + /** + * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. + * + * @param {String} `type` + * @return {Boolean} + * @api public + */ + + isInside: function(type) { + this.sets[type] = this.sets[type] || []; + return this.sets[type].length > 0; + }, + + /** + * Return true if `node` is the given `type`. + * + * ```js + * parser.isType(node, 'brace'); + * ``` + * @param {Object} `node` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + + isType: function(node, type) { + return node && node.type === type; + }, + + /** + * Get the previous AST node + * @return {Object} + */ + + prev: function(n) { + return this.stack.length > 0 + ? utils.last(this.stack, n) + : utils.last(this.nodes, n); + }, + + /** + * Update line and column based on `str`. + */ + + consume: function(len) { + this.input = this.input.substr(len); + }, + + /** + * Update column based on `str`. + */ + + updatePosition: function(str, len) { + var lines = str.match(/\n/g); + if (lines) this.line += lines.length; + var i = str.lastIndexOf('\n'); + this.column = ~i ? len - i : this.column + len; + this.parsed += str; + this.consume(len); + }, + + /** + * Match `regex`, return captures, and update the cursor position by `match[0]` length. + * @param {RegExp} `regex` + * @return {Object} + */ + + match: function(regex) { + var m = regex.exec(this.input); + if (m) { + this.updatePosition(m[0], m[0].length); + return m; + } + }, + + /** + * Capture `type` with the given regex. + * @param {String} `type` + * @param {RegExp} `regex` + * @return {Function} + */ + + capture: function(type, regex) { + if (typeof regex === 'function') { + return this.set.apply(this, arguments); + } + + this.regex.set(type, regex); + this.set(type, function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(regex); + if (!m || !m[0]) return; + + var prev = this.prev(); + var node = pos({ + type: type, + val: m[0], + parsed: parsed, + rest: this.input + }); + + if (m[1]) { + node.inner = m[1]; + } + + define(node, 'inside', this.stack.length > 0); + define(node, 'parent', prev); + prev.nodes.push(node); + }.bind(this)); + return this; + }, + + /** + * Create a parser with open and close for parens, + * brackets or braces + */ + + capturePair: function(type, openRegex, closeRegex, fn) { + this.sets[type] = this.sets[type] || []; + + /** + * Open + */ + + this.set(type + '.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(openRegex); + if (!m || !m[0]) return; + + var val = m[0]; + this.setCount++; + this.specialChars = true; + var open = pos({ + type: type + '.open', + val: val, + rest: this.input + }); + + if (typeof m[1] !== 'undefined') { + open.inner = m[1]; + } + + var prev = this.prev(); + var node = pos({ + type: type, + nodes: [open] + }); + + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'prefix', m[1]); + define(node, 'parent', prev); + define(open, 'parent', node); + + if (typeof fn === 'function') { + fn.call(this, open, node); + } + + this.push(type, node); + prev.nodes.push(node); + }); + + /** + * Close + */ + + this.set(type + '.close', function() { + var pos = this.position(); + var m = this.match(closeRegex); + if (!m || !m[0]) return; + + var parent = this.pop(type); + var node = pos({ + type: type + '.close', + rest: this.input, + suffix: m[1], + val: m[0] + }); + + if (!this.isType(parent, type)) { + if (this.options.strict) { + throw new Error('missing opening "' + type + '"'); + } + + this.setCount--; + node.escaped = true; + return node; + } + + if (node.suffix === '\\') { + parent.escaped = true; + node.escaped = true; + } + + parent.nodes.push(node); + define(node, 'parent', parent); + }); + + return this; + }, + + /** + * Capture end-of-string + */ + + eos: function() { + var pos = this.position(); + if (this.input) return; + var prev = this.prev(); + + while (prev.type !== 'root' && !prev.visited) { + if (this.options.strict === true) { + throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); + } + + if (!hasDelims(prev)) { + prev.parent.escaped = true; + prev.escaped = true; + } + + visit(prev, function(node) { + if (!hasDelims(node.parent)) { + node.parent.escaped = true; + node.escaped = true; + } + }); + + prev = prev.parent; + } + + var tok = pos({ + type: 'eos', + val: this.append || '' + }); + + define(tok, 'parent', this.ast); + return tok; + }, + + /** + * Run parsers to advance the cursor position + */ + + next: function() { + var parsed = this.parsed; + var len = this.types.length; + var idx = -1; + var tok; + + while (++idx < len) { + if ((tok = this.parsers[this.types[idx]].call(this))) { + define(tok, 'rest', this.input); + define(tok, 'parsed', parsed); + this.last = tok; + return tok; + } + } + }, + + /** + * Parse the given string. + * @return {Array} + */ + + parse: function(input) { + if (typeof input !== 'string') { + throw new TypeError('expected a string'); + } + + this.init(this.options); + this.orig = input; + this.input = input; + var self = this; + + function parse() { + // check input before calling `.next()` + input = self.input; + + // get the next AST ndoe + var node = self.next(); + if (node) { + var prev = self.prev(); + if (prev) { + define(node, 'parent', prev); + if (prev.nodes) { + prev.nodes.push(node); + } + } + + if (self.sets.hasOwnProperty(prev.type)) { + self.currentType = prev.type; + } + } + + // if we got here but input is not changed, throw an error + if (self.input && input === self.input) { + throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); + } + } + + while (this.input) parse(); + if (this.stack.length && this.options.strict) { + var node = this.stack.pop(); + throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); + } + + var eos = this.eos(); + var tok = this.prev(); + if (tok.type !== 'eos') { + this.ast.nodes.push(eos); + } + + return this.ast; + } +}; + +/** + * Visit `node` with the given `fn` + */ + +function visit(node, fn) { + if (!node.visited) { + define(node, 'visited', true); + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + return node; +} + +/** + * Map visit over array of `nodes`. + */ + +function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } +} + +function hasOpen(node) { + return node.nodes && node.nodes[0].type === (node.type + '.open'); +} + +function hasClose(node) { + return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); +} + +function hasDelims(node) { + return hasOpen(node) && hasClose(node); +} + +/** + * Expose `Parser` + */ + +module.exports = Parser; + + +/***/ }), + +/***/ 7974: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(5477); + +/** + * Store position for a node + */ + +module.exports = function Position(start, parser) { + this.start = start; + this.end = { line: parser.line, column: parser.column }; + define(this, 'content', parser.orig); + define(this, 'source', parser.options.source); +}; + + +/***/ }), + +/***/ 59657: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +var fs = __webpack_require__(35747); +var path = __webpack_require__(85622); +var define = __webpack_require__(5477); +var utils = __webpack_require__(622); + +/** + * Expose `mixin()`. + * This code is based on `source-maps-support.js` in reworkcss/css + * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js + * Copyright (c) 2012 TJ Holowaychuk + */ + +module.exports = mixin; + +/** + * Mixin source map support into `compiler`. + * + * @param {Object} `compiler` + * @api public + */ + +function mixin(compiler) { + define(compiler, '_comment', compiler.comment); + compiler.map = new utils.SourceMap.SourceMapGenerator(); + compiler.position = { line: 1, column: 1 }; + compiler.content = {}; + compiler.files = {}; + + for (var key in exports) { + define(compiler, key, exports[key]); + } +} + +/** + * Update position. + * + * @param {String} str + */ + +exports.updatePosition = function(str) { + var lines = str.match(/\n/g); + if (lines) this.position.line += lines.length; + var i = str.lastIndexOf('\n'); + this.position.column = ~i ? str.length - i : this.position.column + str.length; +}; + +/** + * Emit `str` with `position`. + * + * @param {String} str + * @param {Object} [pos] + * @return {String} + */ + +exports.emit = function(str, node) { + var position = node.position || {}; + var source = position.source; + if (source) { + if (position.filepath) { + source = utils.unixify(position.filepath); + } + + this.map.addMapping({ + source: source, + generated: { + line: this.position.line, + column: Math.max(this.position.column - 1, 0) + }, + original: { + line: position.start.line, + column: position.start.column - 1 + } + }); + + if (position.content) { + this.addContent(source, position); + } + if (position.filepath) { + this.addFile(source, position); + } + + this.updatePosition(str); + this.output += str; + } + return str; +}; + +/** + * Adds a file to the source map output if it has not already been added + * @param {String} `file` + * @param {Object} `pos` + */ + +exports.addFile = function(file, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.files, file)) return; + this.files[file] = position.content; +}; + +/** + * Adds a content source to the source map output if it has not already been added + * @param {String} `source` + * @param {Object} `position` + */ + +exports.addContent = function(source, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.content, source)) return; + this.map.setSourceContent(source, position.content); +}; + +/** + * Applies any original source maps to the output and embeds the source file + * contents in the source map. + */ + +exports.applySourceMaps = function() { + Object.keys(this.files).forEach(function(file) { + var content = this.files[file]; + this.map.setSourceContent(file, content); + + if (this.options.inputSourcemaps === true) { + var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); + if (originalMap) { + var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); + var relativeTo = originalMap.sourcesRelativeTo; + this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); + } + } + }, this); +}; + +/** + * Process comments, drops sourceMap comments. + * @param {Object} node + */ + +exports.comment = function(node) { + if (/^# sourceMappingURL=/.test(node.comment)) { + return this.emit('', node.position); + } + return this._comment(node); +}; + + +/***/ }), + +/***/ 622: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +/** + * Module dependencies + */ + +exports.extend = __webpack_require__(28727); +exports.SourceMap = __webpack_require__(96241); +exports.sourceMapResolve = __webpack_require__(10227); + +/** + * Convert backslash in the given string to forward slashes + */ + +exports.unixify = function(fp) { + return fp.split(/\\+/).join('/'); +}; + +/** + * Return true if `val` is a non-empty string + * + * @param {String} `str` + * @return {Boolean} + */ + +exports.isString = function(str) { + return str && typeof str === 'string'; +}; + +/** + * Cast `val` to an array + * @return {Array} + */ + +exports.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Get the last `n` element from the given `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + + +/***/ }), + +/***/ 56609: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var decodeUriComponent = __webpack_require__(95748) + +function customDecodeUriComponent(string) { + // `decodeUriComponent` turns `+` into ` `, but that's not wanted. + return decodeUriComponent(string.replace(/\+/g, "%2B")) +} + +module.exports = customDecodeUriComponent + + +/***/ }), + +/***/ 89825: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var url = __webpack_require__(78835) + +function resolveUrl(/* ...urls */) { + return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { + return url.resolve(resolved, nextUrl) + }) +} + +module.exports = resolveUrl + + +/***/ }), + +/***/ 10227: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var sourceMappingURL = __webpack_require__(21707) + +var resolveUrl = __webpack_require__(89825) +var decodeUriComponent = __webpack_require__(56609) +var urix = __webpack_require__(67806) +var atob = __webpack_require__(83327) + + + +function callbackAsync(callback, error, result) { + setImmediate(function() { callback(error, result) }) +} + +function parseMapToJSON(string, data) { + try { + return JSON.parse(string.replace(/^\)\]\}'/, "")) + } catch (error) { + error.sourceMapData = data + throw error + } +} + +function readSync(read, url, data) { + var readUrl = decodeUriComponent(url) + try { + return String(read(readUrl)) + } catch (error) { + error.sourceMapData = data + throw error + } +} + + + +function resolveSourceMap(code, codeUrl, read, callback) { + var mapData + try { + mapData = resolveSourceMapHelper(code, codeUrl) + } catch (error) { + return callbackAsync(callback, error) + } + if (!mapData || mapData.map) { + return callbackAsync(callback, null, mapData) + } + var readUrl = decodeUriComponent(mapData.url) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = mapData + return callback(error) + } + mapData.map = String(result) + try { + mapData.map = parseMapToJSON(mapData.map, mapData) + } catch (error) { + return callback(error) + } + callback(null, mapData) + }) +} + +function resolveSourceMapSync(code, codeUrl, read) { + var mapData = resolveSourceMapHelper(code, codeUrl) + if (!mapData || mapData.map) { + return mapData + } + mapData.map = readSync(read, mapData.url, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + return mapData +} + +var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ + +/** + * The media type for JSON text is application/json. + * + * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations } + * + * `text/json` is non-standard media type + */ +var jsonMimeTypeRegex = /^(?:application|text)\/json$/ + +/** + * JSON text exchanged between systems that are not part of a closed ecosystem + * MUST be encoded using UTF-8. + * + * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding} + */ +var jsonCharacterEncoding = "utf-8" + +function base64ToBuf(b64) { + var binStr = atob(b64) + var len = binStr.length + var arr = new Uint8Array(len) + for (var i = 0; i < len; i++) { + arr[i] = binStr.charCodeAt(i) + } + return arr +} + +function decodeBase64String(b64) { + if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { + return atob(b64) + } + var buf = base64ToBuf(b64); + // Note: `decoder.decode` method will throw a `DOMException` with the + // `"EncodingError"` value when an coding error is found. + var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true}) + return decoder.decode(buf); +} + +function resolveSourceMapHelper(code, codeUrl) { + codeUrl = urix(codeUrl) + + var url = sourceMappingURL.getFrom(code) + if (!url) { + return null + } + + var dataUri = url.match(dataUriRegex) + if (dataUri) { + var mimeType = dataUri[1] || "text/plain" + var lastParameter = dataUri[2] || "" + var encoded = dataUri[3] || "" + var data = { + sourceMappingURL: url, + url: null, + sourcesRelativeTo: codeUrl, + map: encoded + } + if (!jsonMimeTypeRegex.test(mimeType)) { + var error = new Error("Unuseful data uri mime type: " + mimeType) + error.sourceMapData = data + throw error + } + try { + data.map = parseMapToJSON( + lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), + data + ) + } catch (error) { + error.sourceMapData = data + throw error + } + return data + } + + var mapUrl = resolveUrl(codeUrl, url) + return { + sourceMappingURL: url, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } +} + + + +function resolveSources(map, mapUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + var pending = map.sources ? map.sources.length : 0 + var result = { + sourcesResolved: [], + sourcesContent: [] + } + + if (pending === 0) { + callbackAsync(callback, null, result) + return + } + + var done = function() { + pending-- + if (pending === 0) { + callback(null, result) + } + } + + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + callbackAsync(done, null) + } else { + var readUrl = decodeUriComponent(fullUrl) + read(readUrl, function(error, source) { + result.sourcesContent[index] = error ? error : String(source) + done() + }) + } + }) +} + +function resolveSourcesSync(map, mapUrl, read, options) { + var result = { + sourcesResolved: [], + sourcesContent: [] + } + + if (!map.sources || map.sources.length === 0) { + return result + } + + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (read !== null) { + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + } else { + var readUrl = decodeUriComponent(fullUrl) + try { + result.sourcesContent[index] = String(read(readUrl)) + } catch (error) { + result.sourcesContent[index] = error + } + } + } + }) + + return result +} + +var endingSlash = /\/?$/ + +function resolveSourcesHelper(map, mapUrl, options, fn) { + options = options || {} + mapUrl = urix(mapUrl) + var fullUrl + var sourceContent + var sourceRoot + for (var index = 0, len = map.sources.length; index < len; index++) { + sourceRoot = null + if (typeof options.sourceRoot === "string") { + sourceRoot = options.sourceRoot + } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { + sourceRoot = map.sourceRoot + } + // If the sourceRoot is the empty string, it is equivalent to not setting + // the property at all. + if (sourceRoot === null || sourceRoot === '') { + fullUrl = resolveUrl(mapUrl, map.sources[index]) + } else { + // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes + // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root + // does not make sense. + fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) + } + sourceContent = (map.sourcesContent || [])[index] + fn(fullUrl, sourceContent, index) + } +} + + + +function resolve(code, codeUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + if (code === null) { + var mapUrl = codeUrl + var data = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + var readUrl = decodeUriComponent(mapUrl) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = data + return callback(error) + } + data.map = String(result) + try { + data.map = parseMapToJSON(data.map, data) + } catch (error) { + return callback(error) + } + _resolveSources(data) + }) + } else { + resolveSourceMap(code, codeUrl, read, function(error, mapData) { + if (error) { + return callback(error) + } + if (!mapData) { + return callback(null, null) + } + _resolveSources(mapData) + }) + } + + function _resolveSources(mapData) { + resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { + if (error) { + return callback(error) + } + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + callback(null, mapData) + }) + } +} + +function resolveSync(code, codeUrl, read, options) { + var mapData + if (code === null) { + var mapUrl = codeUrl + mapData = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + mapData.map = readSync(read, mapUrl, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + } else { + mapData = resolveSourceMapSync(code, codeUrl, read) + if (!mapData) { + return null + } + } + var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + return mapData +} + + + +module.exports = { + resolveSourceMap: resolveSourceMap, + resolveSourceMapSync: resolveSourceMapSync, + resolveSources: resolveSources, + resolveSourcesSync: resolveSourcesSync, + resolve: resolve, + resolveSync: resolveSync, + parseMapToJSON: parseMapToJSON +} + + +/***/ }), + +/***/ 21707: +/***/ (function(module) { + +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +void (function(root, factory) { + if (typeof define === "function" && define.amd) { + define(factory) + } else if (true) { + module.exports = factory() + } else {} +}(this, function() { + + var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ + + var regex = RegExp( + "(?:" + + "/\\*" + + "(?:\\s*\r?\n(?://)?)?" + + "(?:" + innerRegex.source + ")" + + "\\s*" + + "\\*/" + + "|" + + "//(?:" + innerRegex.source + ")" + + ")" + + "\\s*" + ) + + return { + + regex: regex, + _innerRegex: innerRegex, + + getFrom: function(code) { + var match = code.match(regex) + return (match ? match[1] || match[2] || "" : null) + }, + + existsIn: function(code) { + return regex.test(code) + }, + + removeFrom: function(code) { + return code.replace(regex, "") + }, + + insertBefore: function(code, string) { + var match = code.match(regex) + if (match) { + return code.slice(0, match.index) + string + code.slice(match.index) + } else { + return code + string + } + } + } + +})); + + +/***/ }), + +/***/ 33218: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * split-string + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var extend = __webpack_require__(66889); + +module.exports = function(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + if (typeof options === 'function') { + fn = options; + options = null; + } + + // allow separator to be defined as a string + if (typeof options === 'string') { + options = { sep: options }; + } + + var opts = extend({sep: '.'}, options); + var quotes = opts.quotes || ['"', "'", '`']; + var brackets; + + if (opts.brackets === true) { + brackets = { + '<': '>', + '(': ')', + '[': ']', + '{': '}' + }; + } else if (opts.brackets) { + brackets = opts.brackets; + } + + var tokens = []; + var stack = []; + var arr = ['']; + var sep = opts.sep; + var len = str.length; + var idx = -1; + var closeIdx; + + function expected() { + if (brackets && stack.length) { + return brackets[stack[stack.length - 1]]; + } + } + + while (++idx < len) { + var ch = str[idx]; + var next = str[idx + 1]; + var tok = { val: ch, idx: idx, arr: arr, str: str }; + tokens.push(tok); + + if (ch === '\\') { + tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; + tok.escaped = true; + if (typeof fn === 'function') { + fn(tok); + } + arr[arr.length - 1] += tok.val; + idx++; + continue; + } + + if (brackets && brackets[ch]) { + stack.push(ch); + var e = expected(); + var i = idx + 1; + + if (str.indexOf(e, i + 1) !== -1) { + while (stack.length && i < len) { + var s = str[++i]; + if (s === '\\') { + s++; + continue; + } + + if (quotes.indexOf(s) !== -1) { + i = getClosingQuote(str, s, i + 1); + continue; + } + + e = expected(); + if (stack.length && str.indexOf(e, i + 1) === -1) { + break; + } + + if (brackets[s]) { + stack.push(s); + continue; + } + + if (e === s) { + stack.pop(); + } + } + } + + closeIdx = i; + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } + + ch = str.slice(idx, closeIdx + 1); + tok.val = ch; + tok.idx = idx = closeIdx; + } + + if (quotes.indexOf(ch) !== -1) { + closeIdx = getClosingQuote(str, ch, idx + 1); + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } + + if (keepQuotes(ch, opts) === true) { + ch = str.slice(idx, closeIdx + 1); + } else { + ch = str.slice(idx + 1, closeIdx); + } + + tok.val = ch; + tok.idx = idx = closeIdx; + } + + if (typeof fn === 'function') { + fn(tok, tokens); + ch = tok.val; + idx = tok.idx; + } + + if (tok.val === sep && tok.split !== false) { + arr.push(''); + continue; + } + + arr[arr.length - 1] += tok.val; + } + + return arr; +}; + +function getClosingQuote(str, ch, i, brackets) { + var idx = str.indexOf(ch, i); + if (str.charAt(idx - 1) === '\\') { + return getClosingQuote(str, ch, idx + 1); + } + return idx; +} + +function keepQuotes(ch, opts) { + if (opts.keepDoubleQuotes === true && ch === '"') return true; + if (opts.keepSingleQuotes === true && ch === "'") return true; + return opts.keepQuotes; +} + +function keepEscaping(opts, str, idx) { + if (typeof opts.keepEscaping === 'function') { + return opts.keepEscaping(str, idx); + } + return opts.keepEscaping === true || str[idx + 1] === '\\'; +} + + +/***/ }), + +/***/ 66889: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(28730); +var assignSymbols = __webpack_require__(64353); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), + +/***/ 28730: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 69457: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * static-extend + * + * Copyright (c) 2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var copy = __webpack_require__(31368); +var define = __webpack_require__(5477); +var util = __webpack_require__(31669); + +/** + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. + * + * ```js + * var extend = require('static-extend'); + * Parent.extend = extend(Parent); + * + * // optionally pass a custom merge function as the second arg + * Parent.extend = extend(Parent, function(Child) { + * Child.prototype.mixin = function(key, val) { + * Child.prototype[key] = val; + * }; + * }); + * + * // extend "child" constructors + * Parent.extend(Child); + * + * // optionally define prototype methods as the second arg + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public + */ + +function extend(Parent, extendFn) { + if (typeof Parent !== 'function') { + throw new TypeError('expected Parent to be a function.'); + } + + return function(Ctor, proto) { + if (typeof Ctor !== 'function') { + throw new TypeError('expected Ctor to be a function.'); + } + + util.inherits(Ctor, Parent); + copy(Ctor, Parent); + + // proto can be null or a plain object + if (typeof proto === 'object') { + var obj = Object.create(proto); + + for (var k in obj) { + Ctor.prototype[k] = obj[k]; + } + } + + // keep a reference to the parent prototype + define(Ctor.prototype, '_parent_', { + configurable: true, + set: function() {}, + get: function() { + return Parent.prototype; + } + }); + + if (typeof extendFn === 'function') { + extendFn(Ctor, Parent); + } + + Ctor.extend = extend(Ctor, extendFn); + }; +}; + +/** + * Expose `extend` + */ + +module.exports = extend; + + +/***/ }), + +/***/ 27836: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + let code = ""; + code += `var _results = new Array(${this.options.taps.length});\n`; + code += "var _checkDone = () => {\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; + } +} + +const factory = new AsyncParallelBailHookCodeFactory(); + +class AsyncParallelBailHook extends Hook { + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +Object.defineProperties(AsyncParallelBailHook.prototype, { + _call: { value: undefined, configurable: true, writable: true } +}); + +module.exports = AsyncParallelBailHook; + + +/***/ }), + +/***/ 14616: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncParallelHookCodeFactory(); + +class AsyncParallelHook extends Hook { + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +Object.defineProperties(AsyncParallelHook.prototype, { + _call: { value: undefined, configurable: true, writable: true } +}); + +module.exports = AsyncParallelHook; + + +/***/ }), + +/***/ 89674: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +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 + }); + } +} + +const factory = new AsyncSeriesBailHookCodeFactory(); + +class AsyncSeriesBailHook extends Hook { + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +Object.defineProperties(AsyncSeriesBailHook.prototype, { + _call: { value: undefined, configurable: true, writable: true } +}); + +module.exports = AsyncSeriesBailHook; + + +/***/ }), + +/***/ 55328: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesHookCodeFactory(); + +class AsyncSeriesHook extends Hook { + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +Object.defineProperties(AsyncSeriesHook.prototype, { + _call: { value: undefined, configurable: true, writable: true } +}); + +module.exports = AsyncSeriesHook; + + +/***/ }), + +/***/ 14568: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +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 factory = new AsyncSeriesWaterfallHookCodeFactory(); + +class AsyncSeriesWaterfallHook extends Hook { + constructor(args) { + super(args); + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + } + + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +Object.defineProperties(AsyncSeriesWaterfallHook.prototype, { + _call: { value: undefined, configurable: true, writable: true } +}); + +module.exports = AsyncSeriesWaterfallHook; + + +/***/ }), + +/***/ 12233: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class Hook { + constructor(args) { + if (!Array.isArray(args)) args = []; + this._args = args; + this.taps = []; + this.interceptors = []; + this.call = this._call; + this.promise = this._promise; + this.callAsync = this._callAsync; + this._x = undefined; + } + + compile(options) { + throw new Error("Abstract: should be overriden"); + } + + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type: type + }); + } + + tap(options, fn) { + if (typeof options === "string") options = { name: options }; + if (typeof options !== "object" || options === null) + throw new Error( + "Invalid arguments to tap(options: Object, fn: function)" + ); + options = Object.assign({ type: "sync", fn: fn }, options); + if (typeof options.name !== "string" || options.name === "") + throw new Error("Missing name for tap"); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + tapAsync(options, fn) { + if (typeof options === "string") options = { name: options }; + if (typeof options !== "object" || options === null) + throw new Error( + "Invalid arguments to tapAsync(options: Object, fn: function)" + ); + options = Object.assign({ type: "async", fn: fn }, options); + if (typeof options.name !== "string" || options.name === "") + throw new Error("Missing name for tapAsync"); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + tapPromise(options, fn) { + if (typeof options === "string") options = { name: options }; + if (typeof options !== "object" || options === null) + throw new Error( + "Invalid arguments to tapPromise(options: Object, fn: function)" + ); + options = Object.assign({ type: "promise", fn: fn }, options); + if (typeof options.name !== "string" || options.name === "") + throw new Error("Missing name for tapPromise"); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + _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); + + // Prevent creating endless prototype chains + options = Object.assign({}, options, this._withOptions); + const base = this._withOptionsBase || this; + const newHook = Object.create(base); + + (newHook.tapAsync = (opt, fn) => base.tapAsync(mergeOptions(opt), fn)), + (newHook.tap = (opt, fn) => base.tap(mergeOptions(opt), fn)); + newHook.tapPromise = (opt, fn) => base.tapPromise(mergeOptions(opt), fn); + newHook._withOptions = options; + newHook._withOptionsBase = base; + return newHook; + } + + 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; + } +} + +function createCompileDelegate(name, type) { + return function lazyCompileHook(...args) { + this[name] = this._createCall(type); + return this[name](...args); + }; +} + +Object.defineProperties(Hook.prototype, { + _call: { + value: createCompileDelegate("call", "sync"), + configurable: true, + writable: true + }, + _promise: { + value: createCompileDelegate("promise", "promise"), + configurable: true, + writable: true + }, + _callAsync: { + value: createCompileDelegate("callAsync", "async"), + configurable: true, + writable: true + } +}); + +module.exports = Hook; + + +/***/ }), + +/***/ 64288: +/***/ ((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; + } + + create(options) { + this.init(options); + let fn; + switch (this.options.type) { + case "sync": + fn = new Function( + this.args(), + '"use strict";\n' + + this.header() + + this.content({ + 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.content({ + onError: err => `_callback(${err});\n`, + onResult: result => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + }) + ); + break; + case "promise": + let errorHelperUsed = false; + const content = this.content({ + onError: err => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: result => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += "return new Promise((_resolve, _reject) => {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += "_resolve(Promise.resolve().then(() => { throw _err; }));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += this.header(); + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "});\n"; + fn = new Function(this.args(), code); + break; + } + this.deinit(); + return fn; + } + + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); + } + + /** + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options + */ + init(options) { + this.options = options; + this._args = options.args.slice(); + } + + deinit() { + this.options = undefined; + this._args = undefined; + } + + 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"; + } + 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`; + } + } + return code; + } + + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; + } + + 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 += `(_err${tapIndex}, _result${tapIndex}) => {\n`; + else cbCode += `_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(_result${tapIndex} => {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}, _err${tapIndex} => {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError(`_err${tapIndex}`); + code += "});\n"; + break; + } + return code; + } + + 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 || false; + let code = ""; + let current = onDone; + for (let j = this.options.taps.length - 1; j >= 0; j--) { + const i = j; + const unroll = current !== onDone && this.options.taps[i].type !== "sync"; + if (unroll) { + 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 = () => {\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 = () => {\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; + } + + 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}]`; + } + + getInterceptor(idx) { + return `_interceptors[${idx}]`; + } +} + +module.exports = HookCodeFactory; + + +/***/ }), + +/***/ 35233: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class HookMap { + constructor(factory) { + this._map = new Map(); + this._factory = factory; + this._interceptors = []; + } + + get(key) { + return this._map.get(key); + } + + 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: (key, hook) => hook + }, + interceptor + ) + ); + } + + tap(key, options, fn) { + return this.for(key).tap(options, fn); + } + + tapAsync(key, options, fn) { + return this.for(key).tapAsync(options, fn); + } + + tapPromise(key, options, fn) { + return this.for(key).tapPromise(options, fn); + } +} + +module.exports = HookMap; + + +/***/ }), + +/***/ 93607: +/***/ ((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__(12233); + +class MultiHook { + constructor(hooks) { + this.hooks = hooks; + } + + 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); + } + } + + 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))); + } +} + +module.exports = MultiHook; + + +/***/ }), + +/***/ 16477: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +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 factory = new SyncBailHookCodeFactory(); + +class SyncBailHook extends Hook { + tapAsync() { + throw new Error("tapAsync is not supported on a SyncBailHook"); + } + + tapPromise() { + throw new Error("tapPromise is not supported on a SyncBailHook"); + } + + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +module.exports = SyncBailHook; + + +/***/ }), + +/***/ 77633: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncHookCodeFactory(); + +class SyncHook extends Hook { + tapAsync() { + throw new Error("tapAsync is not supported on a SyncHook"); + } + + tapPromise() { + throw new Error("tapPromise is not supported on a SyncHook"); + } + + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +module.exports = SyncHook; + + +/***/ }), + +/***/ 13608: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncLoopHookCodeFactory(); + +class SyncLoopHook extends Hook { + tapAsync() { + throw new Error("tapAsync is not supported on a SyncLoopHook"); + } + + tapPromise() { + throw new Error("tapPromise is not supported on a SyncLoopHook"); + } + + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +module.exports = SyncLoopHook; + + +/***/ }), + +/***/ 6548: +/***/ ((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__(12233); +const HookCodeFactory = __webpack_require__(64288); + +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 + }); + } +} + +const factory = new SyncWaterfallHookCodeFactory(); + +class SyncWaterfallHook extends Hook { + constructor(args) { + super(args); + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + } + + tapAsync() { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); + } + + tapPromise() { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); + } + + compile(options) { + factory.setup(this, options); + return factory.create(options); + } +} + +module.exports = SyncWaterfallHook; + + +/***/ }), + +/***/ 72693: +/***/ ((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__(31669); +const SyncBailHook = __webpack_require__(16477); + +function Tapable() { + this._pluginCompat = new SyncBailHook(["options"]); + this._pluginCompat.tap( + { + name: "Tapable camelCase", + stage: 100 + }, + options => { + options.names.add( + options.name.replace(/[- ]([a-z])/g, (str, ch) => ch.toUpperCase()) + ); + } + ); + this._pluginCompat.tap( + { + name: "Tapable this.hooks", + stage: 200 + }, + options => { + let hook; + for (const name of options.names) { + hook = this.hooks[name]; + if (hook !== undefined) { + break; + } + } + if (hook !== undefined) { + const tapOpt = { + name: options.fn.name || "unnamed compat plugin", + stage: options.stage || 0 + }; + if (options.async) hook.tapAsync(tapOpt, options.fn); + else hook.tap(tapOpt, options.fn); + return true; + } + } + ); +} +module.exports = Tapable; + +Tapable.addCompatLayer = function addCompatLayer(instance) { + Tapable.call(instance); + instance.plugin = Tapable.prototype.plugin; + instance.apply = Tapable.prototype.apply; +}; + +Tapable.prototype.plugin = util.deprecate(function plugin(name, fn) { + if (Array.isArray(name)) { + name.forEach(function(name) { + this.plugin(name, fn); + }, this); + return; + } + const result = this._pluginCompat.call({ + name: name, + fn: fn, + names: new Set([name]) + }); + if (!result) { + throw new Error( + `Plugin could not be registered at '${name}'. Hook was not found.\n` + + "BREAKING CHANGE: There need to exist a hook at 'this.hooks'. " + + "To create a compatibility layer for this hook, hook into 'this._pluginCompat'." + ); + } +}, "Tapable.plugin is deprecated. Use new API on `.hooks` instead"); + +Tapable.prototype.apply = util.deprecate(function apply() { + for (var i = 0; i < arguments.length; i++) { + arguments[i].apply(this); + } +}, "Tapable.apply is deprecated. Call apply on the plugin directly instead"); + + +/***/ }), + +/***/ 92402: +/***/ ((__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.Tapable = __webpack_require__(72693); +exports.SyncHook = __webpack_require__(77633); +exports.SyncBailHook = __webpack_require__(16477); +exports.SyncWaterfallHook = __webpack_require__(6548); +exports.SyncLoopHook = __webpack_require__(13608); +exports.AsyncParallelHook = __webpack_require__(14616); +exports.AsyncParallelBailHook = __webpack_require__(27836); +exports.AsyncSeriesHook = __webpack_require__(55328); +exports.AsyncSeriesBailHook = __webpack_require__(89674); +exports.AsyncSeriesWaterfallHook = __webpack_require__(14568); +exports.HookMap = __webpack_require__(35233); +exports.MultiHook = __webpack_require__(93607); + + +/***/ }), + +/***/ 16326: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var _os = _interopRequireDefault(__webpack_require__(12087)); + +var _cacache = _interopRequireDefault(__webpack_require__(36801)); + +var _findCacheDir = _interopRequireDefault(__webpack_require__(61844)); + +var _workerFarm = _interopRequireDefault(__webpack_require__(18921)); + +var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); + +var _isWsl = _interopRequireDefault(__webpack_require__(47543)); + +var _minify = _interopRequireDefault(__webpack_require__(30787)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const worker = __webpack_require__.ab + "worker.js"; + +class TaskRunner { + constructor(options = {}) { + const { + cache, + parallel + } = options; + this.cacheDir = cache === true ? (0, _findCacheDir.default)({ + name: 'terser-webpack-plugin' + }) || _os.default.tmpdir() : cache; // In some cases cpus() returns undefined + // https://github.com/nodejs/node/issues/19022 + + const cpus = _os.default.cpus() || { + length: 1 + }; // WSL sometimes freezes, error seems to be on the WSL side + // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21 + + this.maxConcurrentWorkers = _isWsl.default ? 1 : parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); + } + + run(tasks, callback) { + /* istanbul ignore if */ + if (!tasks.length) { + callback(null, []); + return; + } + + if (this.maxConcurrentWorkers > 1) { + const workerOptions = process.platform === 'win32' ? { + maxConcurrentWorkers: this.maxConcurrentWorkers, + maxConcurrentCallsPerWorker: 1 + } : { + maxConcurrentWorkers: this.maxConcurrentWorkers + }; + this.workers = (0, _workerFarm.default)(workerOptions, __webpack_require__.ab + "worker.js"); + + this.boundWorkers = (options, cb) => { + try { + this.workers((0, _serializeJavascript.default)(options), cb); + } catch (error) { + // worker-farm can fail with ENOMEM or something else + cb(error); + } + }; + } else { + this.boundWorkers = (options, cb) => { + try { + cb(null, (0, _minify.default)(options)); + } catch (error) { + cb(error); + } + }; + } + + let toRun = tasks.length; + const results = []; + + const step = (index, data) => { + toRun -= 1; + results[index] = data; + + if (!toRun) { + callback(null, results); + } + }; + + tasks.forEach((task, index) => { + const enqueue = () => { + this.boundWorkers(task, (error, data) => { + const result = error ? { + error + } : data; + + const done = () => step(index, result); + + if (this.cacheDir && !result.error) { + _cacache.default.put(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys), JSON.stringify(data)).then(done, done); + } else { + done(); + } + }); + }; + + if (this.cacheDir) { + _cacache.default.get(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys)).then(({ + data + }) => step(index, JSON.parse(data)), enqueue); + } else { + enqueue(); + } + }); + } + + exit() { + if (this.workers) { + _workerFarm.default.end(this.workers); + } + } + +} + +exports.default = TaskRunner; + +/***/ }), + +/***/ 89301: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const plugin = __webpack_require__(43884); + +module.exports = plugin.default; + +/***/ }), + +/***/ 43884: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var _crypto = _interopRequireDefault(__webpack_require__(76417)); + +var _path = _interopRequireDefault(__webpack_require__(85622)); + +var _sourceMap = __webpack_require__(96241); + +var _webpackSources = __webpack_require__(53665); + +var _RequestShortener = _interopRequireDefault(__webpack_require__(54254)); + +var _ModuleFilenameHelpers = _interopRequireDefault(__webpack_require__(71474)); + +var _schemaUtils = _interopRequireDefault(__webpack_require__(33225)); + +var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); + +var _package = _interopRequireDefault(__webpack_require__(92203)); + +var _options = _interopRequireDefault(__webpack_require__(11840)); + +var _TaskRunner = _interopRequireDefault(__webpack_require__(16326)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/; + +class TerserPlugin { + constructor(options = {}) { + (0, _schemaUtils.default)(_options.default, options, 'Terser Plugin'); + const { + minify, + terserOptions = {}, + test = /\.m?js(\?.*)?$/i, + chunkFilter = () => true, + warningsFilter = () => true, + extractComments = false, + sourceMap = false, + cache = false, + cacheKeys = defaultCacheKeys => defaultCacheKeys, + parallel = false, + include, + exclude + } = options; + this.options = { + test, + chunkFilter, + warningsFilter, + extractComments, + sourceMap, + cache, + cacheKeys, + parallel, + include, + exclude, + minify, + terserOptions: _objectSpread({ + output: { + comments: extractComments ? false : /^\**!|@preserve|@license|@cc_on/i + } + }, terserOptions) + }; + } + + static isSourceMap(input) { + // All required options for `new SourceMapConsumer(...options)` + // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap + return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string'); + } + + static buildSourceMap(inputSourceMap) { + if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) { + return null; + } + + return new _sourceMap.SourceMapConsumer(inputSourceMap); + } + + static buildError(err, file, sourceMap, requestShortener) { + // Handling error which should have line, col, filename and message + if (err.line) { + const original = sourceMap && sourceMap.originalPositionFor({ + line: err.line, + column: err.col + }); + + if (original && original.source && requestShortener) { + return new Error(`${file} from Terser\n${err.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${err.line},${err.col}]`); + } + + return new Error(`${file} from Terser\n${err.message} [${file}:${err.line},${err.col}]`); + } else if (err.stack) { + return new Error(`${file} from Terser\n${err.stack}`); + } + + return new Error(`${file} from Terser\n${err.message}`); + } + + static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) { + let warningMessage = warning; + let locationMessage = ''; + let source = null; + + if (sourceMap) { + const match = warningRegex.exec(warning); + + if (match) { + const line = +match[1]; + const column = +match[2]; + const original = sourceMap.originalPositionFor({ + line, + column + }); + + if (original && original.source && original.source !== file && requestShortener) { + ({ + source + } = original); + warningMessage = `${warningMessage.replace(warningRegex, '')}`; + locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`; + } + } + } + + if (warningsFilter && !warningsFilter(warning, source)) { + return null; + } + + return `Terser Plugin: ${warningMessage}${locationMessage}`; + } + + apply(compiler) { + const buildModuleFn = moduleArg => { + // to get detailed location info about errors + moduleArg.useSourceMap = true; + }; + + const optimizeFn = (compilation, chunks, callback) => { + const taskRunner = new _TaskRunner.default({ + cache: this.options.cache, + parallel: this.options.parallel + }); + const processedAssets = new WeakSet(); + const tasks = []; + const { + chunkFilter + } = this.options; + Array.from(chunks).filter(chunk => chunkFilter && chunkFilter(chunk)).reduce((acc, chunk) => acc.concat(chunk.files || []), []).concat(compilation.additionalChunkAssets || []).filter(_ModuleFilenameHelpers.default.matchObject.bind(null, this.options)).forEach(file => { + let inputSourceMap; + const asset = compilation.assets[file]; + + if (processedAssets.has(asset)) { + return; + } + + try { + let input; + + if (this.options.sourceMap && asset.sourceAndMap) { + const { + source, + map + } = asset.sourceAndMap(); + input = source; + + if (TerserPlugin.isSourceMap(map)) { + inputSourceMap = map; + } else { + inputSourceMap = map; + compilation.warnings.push(new Error(`${file} contains invalid source map`)); + } + } else { + input = asset.source(); + inputSourceMap = null; + } // Handling comment extraction + + + let commentsFile = false; + + if (this.options.extractComments) { + commentsFile = this.options.extractComments.filename || `${file}.LICENSE`; + + if (typeof commentsFile === 'function') { + commentsFile = commentsFile(file); + } + } + + const task = { + file, + input, + inputSourceMap, + commentsFile, + extractComments: this.options.extractComments, + terserOptions: this.options.terserOptions, + minify: this.options.minify + }; + + if (this.options.cache) { + const defaultCacheKeys = { + terser: _package.default.version, + node_version: process.version, + // eslint-disable-next-line global-require + 'terser-webpack-plugin': __webpack_require__(9122)/* .version */ .i8, + 'terser-webpack-plugin-options': this.options, + hash: _crypto.default.createHash('md4').update(input).digest('hex') + }; + task.cacheKeys = this.options.cacheKeys(defaultCacheKeys, file); + } + + tasks.push(task); + } catch (error) { + compilation.errors.push(TerserPlugin.buildError(error, file, TerserPlugin.buildSourceMap(inputSourceMap), new _RequestShortener.default(compiler.context))); + } + }); + taskRunner.run(tasks, (tasksError, results) => { + if (tasksError) { + compilation.errors.push(tasksError); + return; + } + + results.forEach((data, index) => { + const { + file, + input, + inputSourceMap, + commentsFile + } = tasks[index]; + const { + error, + map, + code, + warnings + } = data; + let { + extractedComments + } = data; + let sourceMap = null; + + if (error || warnings && warnings.length > 0) { + sourceMap = TerserPlugin.buildSourceMap(inputSourceMap); + } // Handling results + // Error case: add errors, and go to next file + + + if (error) { + compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context))); + return; + } + + let outputSource; + + if (map) { + outputSource = new _webpackSources.SourceMapSource(code, file, JSON.parse(map), input, inputSourceMap, true); + } else { + outputSource = new _webpackSources.RawSource(code); + } // Write extracted comments to commentsFile + + + if (commentsFile && extractedComments && extractedComments.length > 0) { + if (commentsFile in compilation.assets) { + const commentsFileSource = compilation.assets[commentsFile].source(); + extractedComments = extractedComments.filter(comment => !commentsFileSource.includes(comment)); + } + + if (extractedComments.length > 0) { + // Add a banner to the original file + if (this.options.extractComments.banner !== false) { + let banner = this.options.extractComments.banner || `For license information please see ${_path.default.posix.basename(commentsFile)}`; + + if (typeof banner === 'function') { + banner = banner(commentsFile); + } + + if (banner) { + outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource); + } + } + + const commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`); + + if (commentsFile in compilation.assets) { + // commentsFile already exists, append new comments... + if (compilation.assets[commentsFile] instanceof _webpackSources.ConcatSource) { + compilation.assets[commentsFile].add('\n'); + compilation.assets[commentsFile].add(commentsSource); + } else { + compilation.assets[commentsFile] = new _webpackSources.ConcatSource(compilation.assets[commentsFile], '\n', commentsSource); + } + } else { + compilation.assets[commentsFile] = commentsSource; + } + } + } // Updating assets + + + processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings + + if (warnings && warnings.length > 0) { + warnings.forEach(warning => { + const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter); + + if (builtWarning) { + compilation.warnings.push(builtWarning); + } + }); + } + }); + taskRunner.exit(); + callback(); + }); + }; + + const plugin = { + name: this.constructor.name + }; + compiler.hooks.compilation.tap(plugin, compilation => { + if (this.options.sourceMap) { + compilation.hooks.buildModule.tap(plugin, buildModuleFn); + } + + const { + mainTemplate, + chunkTemplate + } = compilation; // Regenerate `contenthash` for minified assets + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.hashForChunk.tap(plugin, hash => { + const data = (0, _serializeJavascript.default)({ + terser: _package.default.version, + terserOptions: this.options.terserOptions + }); + hash.update('TerserPlugin'); + hash.update(data); + }); + } + + compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation)); + }); + } + +} + +var _default = TerserPlugin; +exports.default = _default; + +/***/ }), + +/***/ 30787: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var _terser = __webpack_require__(54775); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +const buildTerserOptions = ({ + ecma, + warnings, + parse = {}, + compress = {}, + mangle, + module, + output, + toplevel, + nameCache, + ie8, + + /* eslint-disable camelcase */ + keep_classnames, + keep_fnames, + + /* eslint-enable camelcase */ + safari10 +} = {}) => ({ + ecma, + warnings, + parse: _objectSpread({}, parse), + compress: typeof compress === 'boolean' ? compress : _objectSpread({}, compress), + // eslint-disable-next-line no-nested-ternary + mangle: mangle == null ? true : typeof mangle === 'boolean' ? mangle : _objectSpread({}, mangle), + output: _objectSpread({ + shebang: true, + comments: false, + beautify: false, + semicolons: true + }, output), + module, + // Ignoring sourceMap from options + sourceMap: null, + toplevel, + nameCache, + ie8, + keep_classnames, + keep_fnames, + safari10 +}); + +const buildComments = (options, terserOptions, extractedComments) => { + const condition = {}; + const commentsOpts = terserOptions.output.comments; // Use /^\**!|@preserve|@license|@cc_on/i RegExp + + if (typeof options.extractComments === 'boolean') { + condition.preserve = commentsOpts; + condition.extract = /^\**!|@preserve|@license|@cc_on/i; + } else if (typeof options.extractComments === 'string' || options.extractComments instanceof RegExp) { + // extractComments specifies the extract condition and commentsOpts specifies the preserve condition + condition.preserve = commentsOpts; + condition.extract = options.extractComments; + } else if (typeof options.extractComments === 'function') { + condition.preserve = commentsOpts; + condition.extract = options.extractComments; + } else if (Object.prototype.hasOwnProperty.call(options.extractComments, 'condition')) { + // Extract condition is given in extractComments.condition + condition.preserve = commentsOpts; + condition.extract = options.extractComments.condition; + } else { + // No extract condition is given. Extract comments that match commentsOpts instead of preserving them + condition.preserve = false; + condition.extract = commentsOpts; + } // Ensure that both conditions are functions + + + ['preserve', 'extract'].forEach(key => { + let regexStr; + let regex; + + switch (typeof condition[key]) { + case 'boolean': + condition[key] = condition[key] ? () => true : () => false; + break; + + case 'function': + break; + + case 'string': + if (condition[key] === 'all') { + condition[key] = () => true; + + break; + } + + if (condition[key] === 'some') { + condition[key] = (astNode, comment) => { + return comment.type === 'comment2' && /^\**!|@preserve|@license|@cc_on/i.test(comment.value); + }; + + break; + } + + regexStr = condition[key]; + + condition[key] = (astNode, comment) => { + return new RegExp(regexStr).test(comment.value); + }; + + break; + + default: + regex = condition[key]; + + condition[key] = (astNode, comment) => regex.test(comment.value); + + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions + + return (astNode, comment) => { + if (condition.extract(astNode, comment)) { + const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + + return condition.preserve(astNode, comment); + }; +}; + +const minify = options => { + const { + file, + input, + inputSourceMap, + extractComments, + minify: minifyFn + } = options; + + if (minifyFn) { + return minifyFn({ + [file]: input + }, inputSourceMap); + } // Copy terser options + + + const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap + + if (inputSourceMap) { + terserOptions.sourceMap = true; + } + + const extractedComments = []; + + if (extractComments) { + terserOptions.output.comments = buildComments(options, terserOptions, extractedComments); + } + + const { + error, + map, + code, + warnings + } = (0, _terser.minify)({ + [file]: input + }, terserOptions); + return { + error, + map, + code, + warnings, + extractedComments + }; +}; + +var _default = minify; +exports.default = _default; + +/***/ }), + +/***/ 71708: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * to-object-path + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(48865); + +module.exports = function toPath(args) { + if (typeOf(args) !== 'arguments') { + args = arguments; + } + return filter(args).join('.'); +}; + +function filter(arr) { + var len = arr.length; + var idx = -1; + var res = []; + + while (++idx < len) { + var ele = arr[idx]; + if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { + res.push.apply(res, filter(ele)); + } else if (typeof ele === 'string') { + res.push(ele); + } + } + return res; +} + + +/***/ }), + +/***/ 1353: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * to-regex-range + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var repeat = __webpack_require__(6332); +var isNumber = __webpack_require__(87218); +var cache = {}; + +function toRegexRange(min, max, options) { + if (isNumber(min) === false) { + throw new RangeError('toRegexRange: first argument is invalid.'); + } + + if (typeof max === 'undefined' || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new RangeError('toRegexRange: second argument is invalid.'); + } + + options = options || {}; + var relax = String(options.relaxZeros); + var shorthand = String(options.shorthand); + var capture = String(options.capture); + var key = min + ':' + max + '=' + relax + shorthand + capture; + if (cache.hasOwnProperty(key)) { + return cache[key].result; + } + + var a = Math.min(min, max); + var b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + var result = min + '|' + max; + if (options.capture) { + return '(' + result + ')'; + } + return result; + } + + var isPadded = padding(min) || padding(max); + var positives = []; + var negatives = []; + + var tok = {min: min, max: max, a: a, b: b}; + if (isPadded) { + tok.isPadded = isPadded; + tok.maxLen = String(tok.max).length; + } + + if (a < 0) { + var newMin = b < 0 ? Math.abs(b) : 1; + var newMax = Math.abs(a); + negatives = splitToPatterns(newMin, newMax, tok, options); + a = tok.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, tok, options); + } + + tok.negatives = negatives; + tok.positives = positives; + tok.result = siftPatterns(negatives, positives, options); + + if (options.capture && (positives.length + negatives.length) > 1) { + tok.result = '(' + tok.result + ')'; + } + + cache[key] = tok; + return tok.result; +} + +function siftPatterns(neg, pos, options) { + var onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + var onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + var intersected = filterPatterns(neg, pos, '-?', true, options) || []; + var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + min = Number(min); + max = Number(max); + + var nines = 1; + var stops = [max]; + var stop = +countNines(min, nines); + + while (min <= stop && stop <= max) { + stops = push(stops, stop); + nines += 1; + stop = +countNines(min, nines); + } + + var zeros = 1; + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops = push(stops, stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return {pattern: String(start), digits: []}; + } + + var zipped = zip(String(start), String(stop)); + var len = zipped.length, i = -1; + + var pattern = ''; + var digits = 0; + + while (++i < len) { + var numbers = zipped[i]; + var startDigit = numbers[0]; + var stopDigit = numbers[1]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + digits += 1; + } + } + + if (digits) { + pattern += options.shorthand ? '\\d' : '[0-9]'; + } + + return { pattern: pattern, digits: [digits] }; +} + +function splitToPatterns(min, max, tok, options) { + var ranges = splitToRanges(min, max); + var len = ranges.length; + var idx = -1; + + var tokens = []; + var start = min; + var prev; + + while (++idx < len) { + var range = ranges[idx]; + var obj = rangeToPattern(start, range, options); + var zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.digits.length > 1) { + prev.digits.pop(); + } + prev.digits.push(obj.digits[0]); + prev.string = prev.pattern + toQuantifier(prev.digits); + start = range + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(range, tok); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.digits); + tokens.push(obj); + start = range + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + var res = []; + + for (var i = 0; i < arr.length; i++) { + var tok = arr[i]; + var ele = tok.string; + + if (options.relaxZeros !== false) { + if (prefix === '-' && ele.charAt(0) === '0') { + if (ele.charAt(1) === '{') { + ele = '0*' + ele.replace(/^0\{\d+\}/, ''); + } else { + ele = '0*' + ele.slice(1); + } + } + } + + if (!intersection && !contains(comparison, 'string', ele)) { + res.push(prefix + ele); + } + + if (intersection && contains(comparison, 'string', ele)) { + res.push(prefix + ele); + } + } + return res; +} + +/** + * Zip strings (`for in` can be used on string characters) + */ + +function zip(a, b) { + var arr = []; + for (var ch in a) arr.push([a[ch], b[ch]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function push(arr, ele) { + if (arr.indexOf(ele) === -1) arr.push(ele); + return arr; +} + +function contains(arr, key, val) { + for (var i = 0; i < arr.length; i++) { + if (arr[i][key] === val) { + return true; + } + } + return false; +} + +function countNines(min, len) { + return String(min).slice(0, -len) + repeat('9', len); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + var start = digits[0]; + var stop = digits[1] ? (',' + digits[1]) : ''; + if (!stop && (!start || start === 1)) { + return ''; + } + return '{' + start + stop + '}'; +} + +function toCharacterClass(a, b) { + return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; +} + +function padding(str) { + return /^-?(0+)\d/.exec(str); +} + +function padZeros(val, tok) { + if (tok.isPadded) { + var diff = Math.abs(tok.maxLen - String(val).length); + switch (diff) { + case 0: + return ''; + case 1: + return '0'; + default: { + return '0{' + diff + '}'; + } + } + } + return val; +} + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; + + +/***/ }), + +/***/ 51279: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var safe = __webpack_require__(71217); +var define = __webpack_require__(74998); +var extend = __webpack_require__(99793); +var not = __webpack_require__(30931); +var MAX_LENGTH = 1024 * 64; + +/** + * Session cache + */ + +var cache = {}; + +/** + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +module.exports = function(patterns, options) { + if (!Array.isArray(patterns)) { + return makeRe(patterns, options); + } + return makeRe(patterns.join('|'), options); +}; + +/** + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +function makeRe(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + var key = pattern; + // do this before shallow cloning options, it's a lot faster + if (!options || (options && options.cache !== false)) { + key = createKey(pattern, options); + + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + } + + var opts = extend({}, options); + if (opts.contains === true) { + if (opts.negate === true) { + opts.strictNegate = false; + } else { + opts.strict = false; + } + } + + if (opts.strict === false) { + opts.strictOpen = false; + opts.strictClose = false; + } + + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var flags = opts.flags || ''; + var regex; + + if (opts.nocase === true && !/i/.test(flags)) { + flags += 'i'; + } + + try { + if (opts.negate || typeof opts.strictNegate === 'boolean') { + pattern = not.create(pattern, opts); + } + + var str = open + '(?:' + pattern + ')' + close; + regex = new RegExp(str, flags); + + if (opts.safe === true && safe(regex) === false) { + throw new Error('potentially unsafe regular expression: ' + regex.source); + } + + } catch (err) { + if (opts.strictErrors === true || opts.safe === true) { + err.key = key; + err.pattern = pattern; + err.originalOptions = options; + err.createdOptions = opts; + throw err; + } + + try { + regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); + } catch (err) { + regex = /.^/; //<= match nothing + } + } + + if (opts.cache !== false) { + memoize(regex, key, pattern, opts); + } + return regex; +} + +/** + * Memoize generated regex. This can result in dramatic speed improvements + * and simplify debugging by adding options and pattern to the regex. It can be + * disabled by passing setting `options.cache` to false. + */ + +function memoize(regex, key, pattern, options) { + define(regex, 'cached', true); + define(regex, 'pattern', pattern); + define(regex, 'options', options); + define(regex, 'key', key); + cache[key] = regex; +} + +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +function createKey(pattern, options) { + if (!options) return pattern; + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; +} + +/** + * Expose `makeRe` + */ + +module.exports.makeRe = makeRe; + + +/***/ }), + +/***/ 74998: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; + +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); + } + + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } + + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; +}; + + +/***/ }), + +/***/ 99793: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isExtendable = __webpack_require__(78947); +var assignSymbols = __webpack_require__(64353); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), + +/***/ 78947: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 29859: +/***/ ((module) => { + +/*! ***************************************************************************** +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); +}); + + +/***/ }), + +/***/ 7716: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isObject = __webpack_require__(18493); +var union = __webpack_require__(69123); +var get = __webpack_require__(89304); +var set = __webpack_require__(34857); + +module.exports = function unionValue(obj, prop, value) { + if (!isObject(obj)) { + throw new TypeError('union-value expects the first argument to be an object.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('union-value expects `prop` to be a string.'); + } + + var arr = arrayify(get(obj, prop)); + set(obj, prop, union(arr, arrayify(value))); + return obj; +}; + +function arrayify(val) { + if (val === null || typeof val === 'undefined') { + return []; + } + if (Array.isArray(val)) { + return val; + } + return [val]; +} + + +/***/ }), + +/***/ 5834: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * unset-value + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(96667); +var has = __webpack_require__(77735); + +module.exports = function unset(obj, prop) { + if (!isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (obj.hasOwnProperty(prop)) { + delete obj[prop]; + return true; + } + + if (has(obj, prop)) { + var segs = prop.split('.'); + var last = segs.pop(); + while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { + last = segs.pop().slice(0, -1) + '.' + last; + } + while (segs.length) obj = obj[prop = segs.shift()]; + return (delete obj[last]); + } + return true; +}; + + +/***/ }), + +/***/ 77735: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * has-value + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isObject = __webpack_require__(78037); +var hasValues = __webpack_require__(38719); +var get = __webpack_require__(89304); + +module.exports = function(obj, prop, noZero) { + if (isObject(obj)) { + return hasValues(get(obj, prop), noZero); + } + return hasValues(obj, prop); +}; + + +/***/ }), + +/***/ 78037: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isArray = __webpack_require__(21352); + +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; +}; + + +/***/ }), + +/***/ 38719: +/***/ ((module) => { + +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function hasValue(o, noZero) { + if (o === null || o === undefined) { + return false; + } + + if (typeof o === 'boolean') { + return true; + } + + if (typeof o === 'number') { + if (o === 0 && noZero === true) { + return false; + } + return true; + } + + if (o.length !== undefined) { + return o.length !== 0; + } + + for (var key in o) { + if (o.hasOwnProperty(key)) { + return true; + } + } + return false; +}; + + +/***/ }), + +/***/ 94007: +/***/ (function(__unused_webpack_module, exports) { + +/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; + +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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 GARY COURT ``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 GARY COURT OR + * CONTRIBUTORS 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number") { + uriTokens.push(":"); + uriTokens.push(components.port.toString(10)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + //normalize the default port + if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$2 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$3 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$4 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=uri.all.js.map + + +/***/ }), + +/***/ 67806: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +var path = __webpack_require__(85622) + +"use strict" + +function urix(aPath) { + if (path.sep === "\\") { + return aPath + .replace(/\\/g, "/") + .replace(/^[a-z]:\/?/i, "/") + } + return aPath +} + +module.exports = urix + + +/***/ }), + +/***/ 77709: +/***/ ((module) => { + +"use strict"; +/*! + * use + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function base(app, options) { + if (!isObject(app) && typeof app !== 'function') { + throw new TypeError('expected an object or function'); + } + + var opts = isObject(options) ? options : {}; + var prop = typeof opts.prop === 'string' ? opts.prop : 'fns'; + if (!Array.isArray(app[prop])) { + define(app, prop, []); + } + + /** + * Define a plugin function to be passed to use. The only + * parameter exposed to the plugin is `app`, the object or function. + * passed to `use(app)`. `app` is also exposed as `this` in plugins. + * + * Additionally, **if a plugin returns a function, the function will + * be pushed onto the `fns` array**, allowing the plugin to be + * called at a later point by the `run` method. + * + * ```js + * var use = require('use'); + * + * // define a plugin + * function foo(app) { + * // do stuff + * } + * + * var app = function(){}; + * use(app); + * + * // register plugins + * app.use(foo); + * app.use(bar); + * app.use(baz); + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @api public + */ + + define(app, 'use', use); + + /** + * Run all plugins on `fns`. Any plugin that returns a function + * when called by `use` is pushed onto the `fns` array. + * + * ```js + * var config = {}; + * app.run(config); + * ``` + * @name .run + * @param {Object} `value` Object to be modified by plugins. + * @return {Object} Returns the object passed to `run` + * @api public + */ + + define(app, 'run', function(val) { + if (!isObject(val)) return; + + if (!val.use || !val.run) { + define(val, prop, val[prop] || []); + define(val, 'use', use); + } + + if (!val[prop] || val[prop].indexOf(base) === -1) { + val.use(base); + } + + var self = this || app; + var fns = self[prop]; + var len = fns.length; + var idx = -1; + + while (++idx < len) { + val.use(fns[idx]); + } + return val; + }); + + /** + * Call plugin `fn`. If a function is returned push it into the + * `fns` array to be called by the `run` method. + */ + + function use(type, fn, options) { + var offset = 1; + + if (typeof type === 'string' || Array.isArray(type)) { + fn = wrap(type, fn); + offset++; + } else { + options = fn; + fn = type; + } + + if (typeof fn !== 'function') { + throw new TypeError('expected a function'); + } + + var self = this || app; + var fns = self[prop]; + + var args = [].slice.call(arguments, offset); + args.unshift(self); + + if (typeof opts.hook === 'function') { + opts.hook.apply(self, args); + } + + var val = fn.apply(self, args); + if (typeof val === 'function' && fns.indexOf(val) === -1) { + fns.push(val); + } + return self; + } + + /** + * Wrap a named plugin function so that it's only called on objects of the + * given `type` + * + * @param {String} `type` + * @param {Function} `fn` Plugin function + * @return {Function} + */ + + function wrap(type, fn) { + return function plugin() { + return this.type === type ? fn.apply(this, arguments) : plugin; + }; + } + + return app; +}; + +function isObject(val) { + return val && typeof val === 'object' && !Array.isArray(val); +} + +function define(obj, key, val) { + Object.defineProperty(obj, key, { + configurable: true, + writable: true, + value: val + }); +} + + +/***/ }), + +/***/ 92262: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(31669).deprecate; + + +/***/ }), + +/***/ 24059: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(47257); + + +/***/ }), + +/***/ 71118: +/***/ ((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__(71101); +const ParserHelpers = __webpack_require__(23999); + +const NullFactory = __webpack_require__(40438); + +/* eslint-disable camelcase */ +const REPLACEMENTS = { + __webpack_require__: "__webpack_require__", + __webpack_public_path__: "__webpack_require__.p", + __webpack_modules__: "__webpack_require__.m", + __webpack_chunk_load__: "__webpack_require__.e", + __non_webpack_require__: "require", + __webpack_nonce__: "__webpack_require__.nc", + "require.onError": "__webpack_require__.oe" +}; +const NO_WEBPACK_REQUIRE = { + __non_webpack_require__: true +}; +const REPLACEMENT_TYPES = { + __webpack_public_path__: "string", + __webpack_require__: "function", + __webpack_modules__: "object", + __webpack_chunk_load__: "function", + __webpack_nonce__: "string" +}; +/* eslint-enable camelcase */ + +class APIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "APIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = parser => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "APIPlugin", + NO_WEBPACK_REQUIRE[key] + ? ParserHelpers.toConstantDependency( + parser, + REPLACEMENTS[key] + ) + : ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + const type = REPLACEMENT_TYPES[key]; + if (type) { + parser.hooks.evaluateTypeof + .for(key) + .tap("APIPlugin", ParserHelpers.evaluateToString(type)); + } + }); + }; + + 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; + + +/***/ }), + +/***/ 36104: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const WebpackError = __webpack_require__(97391); +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() { + 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 overriden. + * } + * } + * + */ +class AbstractMethodError extends WebpackError { + constructor() { + super(new Message().message); + this.name = "AbstractMethodError"; + } +} + +module.exports = AbstractMethodError; + + +/***/ }), + +/***/ 9701: +/***/ ((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__(53665); +const Template = __webpack_require__(96066); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @typedef {Object} AmdMainTemplatePluginOptions + * @param {string=} name the library name + * @property {boolean=} requireAsWrapper + */ + +class AmdMainTemplatePlugin { + /** + * @param {AmdMainTemplatePluginOptions} options the plugin options + */ + constructor(options) { + if (!options || typeof options === "string") { + this.name = options; + this.requireAsWrapper = false; + } else { + this.name = options.name; + this.requireAsWrapper = options.requireAsWrapper; + } + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const externals = chunk.getModules().filter(m => m.external); + const externalsDepsArray = JSON.stringify( + externals.map(m => + typeof m.request === "object" ? m.request.amd : m.request + ) + ); + const externalsArguments = externals + .map( + m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + + if (this.requireAsWrapper) { + return new ConcatSource( + `require(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (this.name) { + const name = mainTemplate.getAssetPath(this.name, { + hash, + chunk + }); + + return new ConcatSource( + `define(${JSON.stringify( + name + )}, ${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (externalsArguments) { + return new ConcatSource( + `define(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else { + return new ConcatSource("define(function() { return ", source, "});"); + } + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "AmdMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + }); + + mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { + hash.update("exports amd"); + if (this.name) { + hash.update(this.name); + } + }); + } +} + +module.exports = AmdMainTemplatePlugin; + + +/***/ }), + +/***/ 22814: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependenciesBlock = __webpack_require__(16071); + +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {TODO} GroupOptions */ + +module.exports = class AsyncDependenciesBlock extends DependenciesBlock { + /** + * @param {GroupOptions} groupOptions options for the group + * @param {Module} module the Module object + * @param {DependencyLocation=} loc the line of code + * @param {TODO=} request the request + */ + constructor(groupOptions, module, loc, request) { + super(); + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } else if (!groupOptions) { + groupOptions = { name: undefined }; + } + this.groupOptions = groupOptions; + /** @type {ChunkGroup=} */ + this.chunkGroup = undefined; + this.module = module; + this.loc = loc; + this.request = request; + /** @type {DependenciesBlock} */ + this.parent = undefined; + } + + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } + + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + this.groupOptions.name = value; + } + + /** + * @returns {never} this throws and should never be called + */ + get chunks() { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } + + /** + * @param {never} value setter value + * @returns {never} this is going to throw therefore we should throw type + * assertions by returning never + */ + set chunks(value) { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } + + /** + * @param {Hash} hash the hash used to track block changes, from "crypto" module + * @returns {void} + */ + updateHash(hash) { + hash.update(JSON.stringify(this.groupOptions)); + hash.update( + (this.chunkGroup && + this.chunkGroup.chunks + .map(chunk => { + return chunk.id !== null ? chunk.id : ""; + }) + .join(",")) || + "" + ); + super.updateHash(hash); + } + + /** + * @returns {void} + */ + disconnect() { + this.chunkGroup = undefined; + super.disconnect(); + } + + /** + * @returns {void} + */ + unseal() { + this.chunkGroup = undefined; + super.unseal(); + } + + /** + * @returns {void} + */ + sortItems() { + super.sortItems(); + } +}; + + +/***/ }), + +/***/ 67089: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ + +class AsyncDependencyToInitialChunkError extends WebpackError { + /** + * Creates an instance of AsyncDependencyToInitialChunkError. + * @param {string} chunkName Name of Chunk + * @param {Module} module module tied to dependency + * @param {TODO} loc location of dependency + */ + constructor(chunkName, module, loc) { + super( + `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` + ); + + this.name = "AsyncDependencyToInitialChunkError"; + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = AsyncDependencyToInitialChunkError; + + +/***/ }), + +/***/ 51596: +/***/ ((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__(36386); +const PrefetchDependency = __webpack_require__(14237); +const NormalModule = __webpack_require__(25963); + +/** @typedef {import("./Compiler")} Compiler */ + +class AutomaticPrefetchPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "AutomaticPrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + let lastModules = null; + compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { + lastModules = compilation.modules + .filter(m => m instanceof NormalModule) + .map((/** @type {NormalModule} */ m) => ({ + context: m.context, + request: m.request + })); + }); + compiler.hooks.make.tapAsync( + "AutomaticPrefetchPlugin", + (compilation, callback) => { + if (!lastModules) return callback(); + asyncLib.forEach( + lastModules, + (m, callback) => { + compilation.prefetch( + m.context || compiler.context, + new PrefetchDependency(m.request), + callback + ); + }, + callback + ); + } + ); + } +} +module.exports = AutomaticPrefetchPlugin; + + +/***/ }), + +/***/ 4009: +/***/ ((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__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const Template = __webpack_require__(96066); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(10171); + +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ + +const wrapComment = str => { + if (!str.includes("\n")) { + return Template.toComment(str); + } + return `/*!\n * ${str + .replace(/\*\//g, "* /") + .split("\n") + .join("\n * ")}\n */`; +}; + +class BannerPlugin { + /** + * @param {BannerPluginArgument} options options object + */ + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "BannerPlugin only takes one argument (pass an options object)" + ); + } + + validateOptions(schema, options, "Banner Plugin"); + + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } + + /** @type {BannerPluginOptions} */ + this.options = options; + + const bannerOption = options.banner; + if (typeof bannerOption === "function") { + const getBanner = bannerOption; + this.banner = this.options.raw + ? getBanner + : data => wrapComment(getBanner(data)); + } else { + const banner = this.options.raw + ? bannerOption + : wrapComment(bannerOption); + this.banner = () => banner; + } + } + + apply(compiler) { + const options = this.options; + const banner = this.banner; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + + compiler.hooks.compilation.tap("BannerPlugin", compilation => { + compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { + for (const chunk of chunks) { + if (options.entryOnly && !chunk.canBeInitial()) { + continue; + } + + for (const file of chunk.files) { + if (!matchObject(file)) { + continue; + } + + let query = ""; + let filename = file; + const hash = compilation.hash; + const querySplit = filename.indexOf("?"); + + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } + + const lastSlashIndex = filename.lastIndexOf("/"); + + const basename = + lastSlashIndex === -1 + ? filename + : filename.substr(lastSlashIndex + 1); + + const data = { + hash, + chunk, + filename, + basename, + query + }; + + const comment = compilation.getPath(banner(data), data); + + compilation.updateAsset( + file, + old => new ConcatSource(comment, "\n", old) + ); + } + } + }); + }); + } +} + +module.exports = BannerPlugin; + + +/***/ }), + +/***/ 96770: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const TypeUnknown = 0; +const TypeNull = 1; +const TypeString = 2; +const TypeNumber = 3; +const TypeBoolean = 4; +const TypeRegExp = 5; +const TypeConditional = 6; +const TypeArray = 7; +const TypeConstArray = 8; +const TypeIdentifier = 9; +const TypeWrapped = 10; +const TypeTemplateString = 11; + +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + this.range = null; + this.falsy = false; + this.truthy = false; + this.bool = null; + this.number = null; + this.regExp = null; + this.string = null; + this.quasis = null; + this.parts = null; + this.array = null; + this.items = null; + this.options = null; + this.prefix = null; + this.postfix = null; + this.wrappedInnerExpressions = null; + this.expression = null; + } + + isNull() { + return this.type === TypeNull; + } + + isString() { + return this.type === TypeString; + } + + isNumber() { + return this.type === TypeNumber; + } + + isBoolean() { + return this.type === TypeBoolean; + } + + isRegExp() { + return this.type === TypeRegExp; + } + + isConditional() { + return this.type === TypeConditional; + } + + isArray() { + return this.type === TypeArray; + } + + isConstArray() { + return this.type === TypeConstArray; + } + + isIdentifier() { + return this.type === TypeIdentifier; + } + + isWrapped() { + return this.type === TypeWrapped; + } + + isTemplateString() { + return this.type === TypeTemplateString; + } + + isTruthy() { + return this.truthy; + } + + isFalsy() { + return this.falsy; + } + + asBool() { + if (this.truthy) return true; + if (this.falsy) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + const str = this.asString(); + if (typeof str === "string") return str !== ""; + } + return undefined; + } + + asString() { + if (this.isBoolean()) return `${this.bool}`; + if (this.isNull()) return "null"; + if (this.isString()) return this.string; + if (this.isNumber()) return `${this.number}`; + 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; + return this; + } + + setNull() { + this.type = TypeNull; + return this; + } + + setNumber(number) { + this.type = TypeNumber; + this.number = number; + return this; + } + + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + return this; + } + + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + return this; + } + + setIdentifier(identifier) { + this.type = TypeIdentifier; + this.identifier = identifier; + return this; + } + + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + return this; + } + + setOptions(options) { + this.type = TypeConditional; + this.options = options; + return this; + } + + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + } + for (const item of options) { + this.options.push(item); + } + return this; + } + + setItems(items) { + this.type = TypeArray; + this.items = items; + return this; + } + + setArray(array) { + this.type = TypeConstArray; + this.array = array; + return this; + } + + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + return this; + } + + setTruthy() { + this.falsy = false; + this.truthy = true; + return this; + } + + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } + + setRange(range) { + this.range = range; + return this; + } + + setExpression(expression) { + this.expression = expression; + return this; + } +} + +module.exports = BasicEvaluatedExpression; + + +/***/ }), + +/***/ 6465: +/***/ ((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__(36386); + +class CachePlugin { + constructor(cache) { + this.cache = cache || {}; + this.FS_ACCURACY = 2000; + } + + apply(compiler) { + if (Array.isArray(compiler.compilers)) { + compiler.compilers.forEach((c, idx) => { + new CachePlugin((this.cache[idx] = this.cache[idx] || {})).apply(c); + }); + } else { + const registerCacheToCompiler = (compiler, cache) => { + compiler.hooks.thisCompilation.tap("CachePlugin", compilation => { + compilation.cache = cache; + compilation.hooks.childCompiler.tap( + "CachePlugin", + (childCompiler, compilerName, compilerIndex) => { + let childCache; + if (!cache.children) { + cache.children = {}; + } + if (!cache.children[compilerName]) { + cache.children[compilerName] = []; + } + if (cache.children[compilerName][compilerIndex]) { + childCache = cache.children[compilerName][compilerIndex]; + } else { + cache.children[compilerName].push((childCache = {})); + } + registerCacheToCompiler(childCompiler, childCache); + } + ); + }); + }; + registerCacheToCompiler(compiler, this.cache); + compiler.hooks.watchRun.tap("CachePlugin", () => { + this.watching = true; + }); + compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { + if (!compiler._lastCompilationFileDependencies) { + return callback(); + } + const fs = compiler.inputFileSystem; + const fileTs = (compiler.fileTimestamps = new Map()); + asyncLib.forEach( + compiler._lastCompilationFileDependencies, + (file, callback) => { + fs.stat(file, (err, stat) => { + if (err) { + if (err.code === "ENOENT") return callback(); + return callback(err); + } + + if (stat.mtime) this.applyMtime(+stat.mtime); + + fileTs.set(file, +stat.mtime || Infinity); + + callback(); + }); + }, + err => { + if (err) return callback(err); + + for (const [file, ts] of fileTs) { + fileTs.set(file, ts + this.FS_ACCURACY); + } + + callback(); + } + ); + }); + compiler.hooks.afterCompile.tap("CachePlugin", compilation => { + compilation.compiler._lastCompilationFileDependencies = + compilation.fileDependencies; + compilation.compiler._lastCompilationContextDependencies = + compilation.contextDependencies; + }); + } + } + + /* istanbul ignore next */ + applyMtime(mtime) { + if (this.FS_ACCURACY > 1 && mtime % 2 !== 0) this.FS_ACCURACY = 1; + else if (this.FS_ACCURACY > 10 && mtime % 20 !== 0) this.FS_ACCURACY = 10; + else if (this.FS_ACCURACY > 100 && mtime % 200 !== 0) + this.FS_ACCURACY = 100; + else if (this.FS_ACCURACY > 1000 && mtime % 2000 !== 0) + this.FS_ACCURACY = 1000; + } +} +module.exports = CachePlugin; + + +/***/ }), + +/***/ 8335: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ + +/** + * @param {Module[]} modules the modules to be sorted + * @returns {Module[]} sorted version of original modules + */ +const sortModules = modules => { + return modules.slice().sort((a, b) => { + const aIdent = a.identifier(); + const bIdent = b.identifier(); + /* istanbul ignore next */ + if (aIdent < bIdent) return -1; + /* istanbul ignore next */ + if (aIdent > bIdent) return 1; + /* istanbul ignore next */ + return 0; + }); +}; + +/** + * @param {Module[]} modules each module from throw + * @returns {string} each message from provided moduels + */ +const createModulesListMessage = modules => { + return modules + .map(m => { + let message = `* ${m.identifier()}`; + const validReasons = m.reasons.filter(reason => reason.module); + + if (validReasons.length > 0) { + message += `\n Used by ${validReasons.length} module(s), i. e.`; + message += `\n ${validReasons[0].module.identifier()}`; + } + return message; + }) + .join("\n"); +}; + +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Module[]} modules modules that were detected + */ + constructor(modules) { + const sortedModules = sortModules(modules); + const modulesList = createModulesListMessage(sortedModules); + super(`There are multiple modules with names that only differ in casing. +This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. +Use equal casing. Compare these module identifiers: +${modulesList}`); + + this.name = "CaseSensitiveModulesWarning"; + this.origin = this.module = sortedModules[0]; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = CaseSensitiveModulesWarning; + + +/***/ }), + +/***/ 2919: +/***/ ((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__(31669); +const SortableSet = __webpack_require__(50071); +const intersect = __webpack_require__(54262).intersect; +const GraphHelpers = __webpack_require__(32973); +const Entrypoint = __webpack_require__(71931); +let debugId = 1000; +const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()"; +const ERR_CHUNK_INITIAL = + "Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"; + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./ModuleReason")} ModuleReason */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +/** + * @typedef {Object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ + +/** + * Compare two Modules based on their ids for sorting + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} sort value + */ + +// TODO use @callback +/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ + +const sortModuleById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; + +/** + * Compare two ChunkGroups based on their ids for sorting + * @param {ChunkGroup} a chunk group + * @param {ChunkGroup} b chunk group + * @returns {-1|0|1} sort value + */ +const sortChunkGroupById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; + +/** + * Compare two Identifiables , based on their ids for sorting + * @param {Module} a first object with ident fn + * @param {Module} b second object with ident fn + * @returns {-1|0|1} The order number of the sort + */ +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; + +/** + * @returns {string} a concatenation of module identifiers sorted + * @param {SortableSet} set to pull module identifiers from + */ +const getModulesIdent = set => { + set.sort(); + let str = ""; + for (const m of set) { + str += m.identifier() + "#"; + } + return str; +}; + +/** + * @template T + * @param {SortableSet} set the sortable set to convert to array + * @returns {Array} the array returned from Array.from(set) + */ +const getArray = set => Array.from(set); + +/** + * @param {SortableSet} set the sortable Set to get the count/size of + * @returns {number} the size of the modules + */ +const getModulesSize = set => { + let size = 0; + for (const module of set) { + size += module.size(); + } + return size; +}; + +/** + * A Chunk is a unit of encapsulation for Modules. + * Chunks are "rendered" into bundles that get emitted when the build completes. + */ +class Chunk { + /** + * @param {string=} name of chunk being created, is optional (for subclasses) + */ + constructor(name) { + /** @type {number | null} */ + this.id = null; + /** @type {number[] | null} */ + this.ids = null; + /** @type {number} */ + this.debugId = debugId++; + /** @type {string} */ + this.name = name; + /** @type {boolean} */ + this.preventIntegration = false; + /** @type {Module=} */ + this.entryModule = undefined; + /** @private @type {SortableSet} */ + this._modules = new SortableSet(undefined, sortByIdentifier); + /** @type {string?} */ + this.filenameTemplate = undefined; + /** @private @type {SortableSet} */ + this._groups = new SortableSet(undefined, sortChunkGroupById); + /** @type {string[]} */ + this.files = []; + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Object} */ + this.contentHash = Object.create(null); + /** @type {string=} */ + this.renderedHash = undefined; + /** @type {string=} */ + this.chunkReason = undefined; + /** @type {boolean} */ + this.extraAsync = false; + this.removedModules = undefined; + } + + /** + * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead + * @returns {never} Throws an error trying to access this property + */ + get entry() { + throw new Error(ERR_CHUNK_ENTRY); + } + + /** + * @deprecated .entry has been deprecated. Please use .hasRuntime() instead + * @param {never} data The data that was attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set entry(data) { + throw new Error(ERR_CHUNK_ENTRY); + } + + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @returns {never} Throws an error trying to access this property + */ + get initial() { + throw new Error(ERR_CHUNK_INITIAL); + } + + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @param {never} data The data attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set initial(data) { + throw new Error(ERR_CHUNK_INITIAL); + } + + /** + * @returns {boolean} whether or not the Chunk will have a runtime + */ + hasRuntime() { + for (const chunkGroup of this._groups) { + if ( + chunkGroup.isInitial() && + chunkGroup instanceof Entrypoint && + chunkGroup.getRuntimeChunk() === this + ) { + return true; + } + } + return false; + } + + /** + * @returns {boolean} whether or not this chunk can be an initial chunk + */ + canBeInitial() { + for (const chunkGroup of this._groups) { + if (chunkGroup.isInitial()) return true; + } + return false; + } + + /** + * @returns {boolean} whether this chunk can only be an initial chunk + */ + isOnlyInitial() { + if (this._groups.size <= 0) return false; + for (const chunkGroup of this._groups) { + if (!chunkGroup.isInitial()) return false; + } + return true; + } + + /** + * @returns {boolean} if this chunk contains the entry module + */ + hasEntryModule() { + return !!this.entryModule; + } + + /** + * @param {Module} module the module that will be added to this chunk. + * @returns {boolean} returns true if the chunk doesn't have the module and it was added + */ + addModule(module) { + if (!this._modules.has(module)) { + this._modules.add(module); + return true; + } + return false; + } + + /** + * @param {Module} module the module that will be removed from this chunk + * @returns {boolean} returns true if chunk exists and is successfully deleted + */ + removeModule(module) { + if (this._modules.delete(module)) { + module.removeChunk(this); + return true; + } + return false; + } + + /** + * @param {Module[]} modules the new modules to be set + * @returns {void} set new modules to this chunk and return nothing + */ + setModules(modules) { + this._modules = new SortableSet(modules, sortByIdentifier); + } + + /** + * @returns {number} the amount of modules in chunk + */ + getNumberOfModules() { + return this._modules.size; + } + + /** + * @returns {SortableSet} return the modules SortableSet for this chunk + */ + get modulesIterable() { + return this._modules; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {boolean} returns true if chunk is not apart of chunkGroup and is added successfully + */ + addGroup(chunkGroup) { + if (this._groups.has(chunkGroup)) return false; + this._groups.add(chunkGroup); + return true; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed + */ + removeGroup(chunkGroup) { + if (!this._groups.has(chunkGroup)) return false; + this._groups.delete(chunkGroup); + return true; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup to check + * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup + */ + isInGroup(chunkGroup) { + return this._groups.has(chunkGroup); + } + + /** + * @returns {number} the amount of groups said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; + } + + /** + * @returns {SortableSet} the chunkGroups that said chunk is referenced in + */ + get groupsIterable() { + return this._groups; + } + + /** + * @param {Chunk} otherChunk the chunk to compare itself with + * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order + */ + compareTo(otherChunk) { + if (this.name && !otherChunk.name) return -1; + if (!this.name && otherChunk.name) return 1; + if (this.name < otherChunk.name) return -1; + if (this.name > otherChunk.name) return 1; + if (this._modules.size > otherChunk._modules.size) return -1; + if (this._modules.size < otherChunk._modules.size) return 1; + this._modules.sort(); + otherChunk._modules.sort(); + const a = this._modules[Symbol.iterator](); + const b = otherChunk._modules[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + if (aItem.done) return 0; + const bItem = b.next(); + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier < bModuleIdentifier) return -1; + if (aModuleIdentifier > bModuleIdentifier) return 1; + } + } + + /** + * @param {Module} module Module to check + * @returns {boolean} returns true if module does exist in this chunk + */ + containsModule(module) { + return this._modules.has(module); + } + + /** + * @returns {Module[]} an array of modules (do not modify) + */ + getModules() { + return this._modules.getFromCache(getArray); + } + + getModulesIdent() { + return this._modules.getFromUnorderedCache(getModulesIdent); + } + + /** + * @param {string=} reason reason why chunk is removed + * @returns {void} + */ + remove(reason) { + // cleanup modules + // Array.from is used here to create a clone, because removeChunk modifies this._modules + for (const module of Array.from(this._modules)) { + module.removeChunk(this); + } + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } + } + + /** + * + * @param {Module} module module to move + * @param {Chunk} otherChunk other chunk to move it to + * @returns {void} + */ + moveModule(module, otherChunk) { + GraphHelpers.disconnectChunkAndModule(this, module); + GraphHelpers.connectChunkAndModule(otherChunk, module); + module.rewriteChunkInReasons(this, [otherChunk]); + } + + /** + * + * @param {Chunk} otherChunk the chunk to integrate with + * @param {string} reason reason why the module is being integrated + * @returns {boolean} returns true or false if integration succeeds or fails + */ + integrate(otherChunk, reason) { + if (!this.canBeIntegrated(otherChunk)) { + return false; + } + + // Pick a new name for the integrated chunk + if (this.name && otherChunk.name) { + if (this.hasEntryModule() === otherChunk.hasEntryModule()) { + // When both chunks have entry modules or none have one, use + // shortest name + if (this.name.length !== otherChunk.name.length) { + this.name = + this.name.length < otherChunk.name.length + ? this.name + : otherChunk.name; + } else { + this.name = this.name < otherChunk.name ? this.name : otherChunk.name; + } + } else if (otherChunk.hasEntryModule()) { + // Pick the name of the chunk with the entry module + this.name = otherChunk.name; + } + } else if (otherChunk.name) { + this.name = otherChunk.name; + } + + // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules + for (const module of Array.from(otherChunk._modules)) { + otherChunk.moveModule(module, this); + } + otherChunk._modules.clear(); + + if (otherChunk.entryModule) { + this.entryModule = otherChunk.entryModule; + } + + for (const chunkGroup of otherChunk._groups) { + chunkGroup.replaceChunk(otherChunk, this); + this.addGroup(chunkGroup); + } + otherChunk._groups.clear(); + + return true; + } + + /** + * @param {Chunk} newChunk the new chunk that will be split out of the current chunk + * @returns {void} + */ + split(newChunk) { + for (const chunkGroup of this._groups) { + chunkGroup.insertChunk(newChunk, this); + newChunk.addGroup(chunkGroup); + } + } + + isEmpty() { + return this._modules.size === 0; + } + + updateHash(hash) { + hash.update(`${this.id} `); + hash.update(this.ids ? this.ids.join(",") : ""); + hash.update(`${this.name || ""} `); + for (const m of this._modules) { + hash.update(m.hash); + } + } + + canBeIntegrated(otherChunk) { + if (this.preventIntegration || otherChunk.preventIntegration) { + return false; + } + + /** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {boolean} true, if a is always available when b is reached + */ + const isAvailable = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return true; + }; + + const selfHasRuntime = this.hasRuntime(); + const otherChunkHasRuntime = otherChunk.hasRuntime(); + + if (selfHasRuntime !== otherChunkHasRuntime) { + if (selfHasRuntime) { + return isAvailable(this, otherChunk); + } else if (otherChunkHasRuntime) { + return isAvailable(otherChunk, this); + } else { + return false; + } + } + + if (this.hasEntryModule() || otherChunk.hasEntryModule()) { + return false; + } + + return true; + } + + /** + * + * @param {number} size the size + * @param {Object} options the options passed in + * @returns {number} the multiplier returned + */ + addMultiplierAndOverhead(size, options) { + const overhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const multiplicator = this.canBeInitial() + ? options.entryChunkMultiplicator || 10 + : 1; + + return size * multiplicator + overhead; + } + + /** + * @returns {number} the size of all modules + */ + modulesSize() { + return this._modules.getFromUnorderedCache(getModulesSize); + } + + /** + * @param {Object} options the size display options + * @returns {number} the chunk size + */ + size(options = {}) { + return this.addMultiplierAndOverhead(this.modulesSize(), options); + } + + /** + * @param {Chunk} otherChunk the other chunk + * @param {TODO} options the options for this function + * @returns {number | false} the size, or false if it can't be integrated + */ + integratedSize(otherChunk, options) { + // Chunk if it's possible to integrate this chunk + if (!this.canBeIntegrated(otherChunk)) { + return false; + } + + let integratedModulesSize = this.modulesSize(); + // only count modules that do not exist in this chunk! + for (const otherModule of otherChunk._modules) { + if (!this._modules.has(otherModule)) { + integratedModulesSize += otherModule.size(); + } + } + + return this.addMultiplierAndOverhead(integratedModulesSize, options); + } + + /** + * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules + * @returns {void} + */ + sortModules(sortByFn) { + this._modules.sortWith(sortByFn || sortModuleById); + } + + sortItems() { + this.sortModules(); + } + + /** + * @returns {Set} a set of all the async chunks + */ + getAllAsyncChunks() { + const queue = new Set(); + const chunks = new Set(); + + const initialChunks = intersect( + Array.from(this.groupsIterable, g => new Set(g.chunks)) + ); + + for (const chunkGroup of this.groupsIterable) { + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + chunks.add(chunk); + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return chunks; + } + + /** + * @typedef {Object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name + */ + + /** + * @param {boolean} realHash should the full hash or the rendered hash 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); + } + chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; + } + if (chunk.name) { + chunkNameMap[chunk.id] = chunk.name; + } + } + + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; + } + + /** + * @returns {Record[]>} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders() { + const lists = new Map(); + for (const group of this.groupsIterable) { + if (group.chunks[group.chunks.length - 1] === this) { + for (const childGroup of group.childrenIterable) { + // TODO webpack 5 remove this check for options + if (typeof childGroup.options === "object") { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.substr(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) lists.set(name, (list = [])); + list.push({ + order: childGroup.options[key], + group: childGroup + }); + } + } + } + } + } + } + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + // TODO webpack 5 remove this check of compareTo + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } + return 0; + }); + result[name] = Array.from( + list.reduce((set, item) => { + for (const chunk of item.group.chunks) { + set.add(chunk.id); + } + return set; + }, new Set()) + ); + } + return result; + } + + getChildIdsByOrdersMap(includeDirectChildren) { + const chunkMaps = Object.create(null); + + const addChildIdsByOrdersToMap = chunk => { + const data = chunk.getChildIdsByOrders(); + for (const key of Object.keys(data)) { + let chunkMap = chunkMaps[key]; + if (chunkMap === undefined) { + chunkMaps[key] = chunkMap = Object.create(null); + } + chunkMap[chunk.id] = data[key]; + } + }; + + if (includeDirectChildren) { + const chunks = new Set(); + for (const chunkGroup of this.groupsIterable) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + } + for (const chunk of chunks) { + addChildIdsByOrdersToMap(chunk); + } + } + + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } + + return chunkMaps; + } + + /** + * @typedef {Object} ChunkModuleMaps + * @property {Record} id + * @property {Record} hash + */ + + /** + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @returns {ChunkModuleMaps} module map information + */ + getChunkModuleMaps(filterFn) { + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record} */ + const chunkModuleHashMap = Object.create(null); + + for (const chunk of this.getAllAsyncChunks()) { + /** @type {(string|number)[]} */ + let array; + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[chunk.id] = array; + } + array.push(module.id); + chunkModuleHashMap[module.id] = module.renderedHash; + } + } + if (array !== undefined) { + array.sort(); + } + } + + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } + + /** + * + * @param {function(Module): boolean} filterFn predicate function used to filter modules + * @param {function(Chunk): boolean} filterChunkFn predicate function used to filter chunks + * @returns {boolean} return true if module exists in graph + */ + hasModuleInGraph(filterFn, filterChunkFn) { + const queue = new Set(this.groupsIterable); + const chunksProcessed = new Set(); + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!chunksProcessed.has(chunk)) { + chunksProcessed.add(chunk); + if (!filterChunkFn || filterChunkFn(chunk)) { + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + return true; + } + } + } + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; + } + + toString() { + return `Chunk[${Array.from(this._modules).join()}]`; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "forEachModule", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, any, Set): void} ForEachModuleCallback + * @param {ForEachModuleCallback} fn Callback function + * @returns {void} + */ + function(fn) { + this._modules.forEach(fn); + }, + "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "mapModules", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, number): any} MapModulesCallback + * @param {MapModulesCallback} fn Callback function + * @returns {TODO[]} result of mapped modules + */ + function(fn) { + return Array.from(this._modules, fn); + }, + "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "chunks", { + configurable: false, + get() { + throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead"); + }, + set() { + throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "parents", { + configurable: false, + get() { + throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead"); + }, + set() { + throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "blocks", { + configurable: false, + get() { + throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead"); + }, + set() { + throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "entrypoints", { + configurable: false, + get() { + throw new Error( + "Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead" + ); + }, + set() { + throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead"); + } +}); + +module.exports = Chunk; + + +/***/ }), + +/***/ 52911: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const SortableSet = __webpack_require__(50071); +const compareLocations = __webpack_require__(22562); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleReason")} ModuleReason */ + +/** @typedef {{module: Module, loc: TODO, request: string}} OriginRecord */ +/** @typedef {string|{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 { + /** + * Creates an instance of ChunkGroup. + * @param {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); + this._parents = 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._moduleIndices = new Map(); + /** Indices in bottom-up order */ + /** @private @type {Map} */ + this._moduleIndices2 = new Map(); + } + + /** + * 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; + } + + /** + * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's + * @returns {string} a unique concatenation of chunk debugId's + */ + get debugId() { + return Array.from(this.chunks, x => x.debugId).join("+"); + } + + /** + * get a unique id for ChunkGroup, made up of its member Chunk id's + * @returns {string} a unique concatenation of chunk ids + */ + get id() { + return Array.from(this.chunks, x => x.id).join("+"); + } + + /** + * Performs an unshift of a specific chunk + * @param {Chunk} chunk chunk being unshifted + * @returns {boolean} returns true if attempted chunk shift is accepted + */ + unshiftChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx > 0) { + this.chunks.splice(oldIdx, 1); + this.chunks.unshift(chunk); + } else if (oldIdx < 0) { + this.chunks.unshift(chunk); + return true; + } + return false; + } + + /** + * inserts a chunk before another existing chunk in group + * @param {Chunk} chunk Chunk being inserted + * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point + * @returns {boolean} return true if insertion was successful + */ + insertChunk(chunk, before) { + const oldIdx = this.chunks.indexOf(chunk); + const idx = this.chunks.indexOf(before); + if (idx < 0) { + throw new Error("before chunk not found"); + } + if (oldIdx >= 0 && oldIdx > idx) { + this.chunks.splice(oldIdx, 1); + this.chunks.splice(idx, 0, chunk); + } else if (oldIdx < 0) { + this.chunks.splice(idx, 0, chunk); + return true; + } + return false; + } + + /** + * add a chunk into ChunkGroup. Is pushed on or prepended + * @param {Chunk} chunk chunk being pushed into ChunkGroupS + * @returns {boolean} returns true if chunk addition was successful. + */ + pushChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx >= 0) { + return false; + } + this.chunks.push(chunk); + return true; + } + + /** + * @param {Chunk} oldChunk chunk to be replaced + * @param {Chunk} newChunk New chunk that will be replaced with + * @returns {boolean} returns true if the replacement was successful + */ + replaceChunk(oldChunk, newChunk) { + const oldIdx = this.chunks.indexOf(oldChunk); + if (oldIdx < 0) return false; + const newIdx = this.chunks.indexOf(newChunk); + if (newIdx < 0) { + this.chunks[oldIdx] = newChunk; + return true; + } + if (newIdx < oldIdx) { + this.chunks.splice(oldIdx, 1); + return true; + } else if (newIdx !== oldIdx) { + this.chunks[oldIdx] = newChunk; + this.chunks.splice(newIdx, 1); + return true; + } + } + + removeChunk(chunk) { + const idx = this.chunks.indexOf(chunk); + if (idx >= 0) { + this.chunks.splice(idx, 1); + return true; + } + return false; + } + + isInitial() { + return false; + } + + addChild(chunk) { + if (this._children.has(chunk)) { + return false; + } + this._children.add(chunk); + return true; + } + + getChildren() { + return this._children.getFromCache(getArray); + } + + getNumberOfChildren() { + return this._children.size; + } + + get childrenIterable() { + return this._children; + } + + removeChild(chunk) { + if (!this._children.has(chunk)) { + return false; + } + + this._children.delete(chunk); + chunk.removeParent(this); + return true; + } + + addParent(parentChunk) { + if (!this._parents.has(parentChunk)) { + this._parents.add(parentChunk); + return true; + } + return false; + } + + getParents() { + return this._parents.getFromCache(getArray); + } + + setParents(newParents) { + this._parents.clear(); + for (const p of newParents) { + this._parents.add(p); + } + } + + getNumberOfParents() { + return this._parents.size; + } + + hasParent(parent) { + return this._parents.has(parent); + } + + get parentsIterable() { + return this._parents; + } + + removeParent(chunk) { + if (this._parents.delete(chunk)) { + chunk.removeChunk(this); + return true; + } + return false; + } + + /** + * @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); + } + + get blocksIterable() { + return this._blocks; + } + + addBlock(block) { + if (!this._blocks.has(block)) { + this._blocks.add(block); + return true; + } + return false; + } + + addOrigin(module, loc, request) { + this.origins.push({ + module, + loc, + request + }); + } + + containsModule(module) { + for (const chunk of this.chunks) { + if (chunk.containsModule(module)) return true; + } + return false; + } + + getFiles() { + const files = new Set(); + + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); + } + } + + return Array.from(files); + } + + /** + * @param {string=} reason reason for removing ChunkGroup + * @returns {void} + */ + remove(reason) { + // cleanup parents + for (const parentChunkGroup of this._parents) { + // remove this chunk from its parents + parentChunkGroup._children.delete(this); + + // cleanup "sub chunks" + for (const chunkGroup of this._children) { + /** + * remove this chunk as "intermediary" and connect + * it "sub chunks" and parents directly + */ + // add parent to each "sub chunk" + chunkGroup.addParent(parentChunkGroup); + // add "sub chunk" to parent + parentChunkGroup.addChild(chunkGroup); + } + } + + /** + * we need to iterate again over the children + * to remove this from the child's parents. + * This can not be done in the above loop + * as it is not guaranteed that `this._parents` contains anything. + */ + for (const chunkGroup of this._children) { + // remove this as parent of every "sub chunk" + chunkGroup._parents.delete(this); + } + + // cleanup blocks + for (const block of this._blocks) { + block.chunkGroup = null; + } + + // remove chunks + for (const chunk of this.chunks) { + chunk.removeGroup(this); + } + } + + sortItems() { + this.origins.sort(sortOrigin); + this._parents.sort(); + this._children.sort(); + } + + /** + * Sorting predicate which allows current ChunkGroup to be compared against another. + * Sorting values are based off of number of chunks in ChunkGroup. + * + * @param {ChunkGroup} otherGroup the chunkGroup to compare this against + * @returns {-1|0|1} sort position for comparison + */ + compareTo(otherGroup) { + if (this.chunks.length > otherGroup.chunks.length) return -1; + if (this.chunks.length < otherGroup.chunks.length) return 1; + const a = this.chunks[Symbol.iterator](); + const b = otherGroup.chunks[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done) return 0; + const cmp = aItem.value.compareTo(bItem.value); + if (cmp !== 0) return cmp; + } + } + + getChildrenByOrders() { + const lists = new Map(); + for (const childGroup of this._children) { + // TODO webpack 5 remove this check for options + if (typeof childGroup.options === "object") { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.substr(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) { + lists.set(name, (list = [])); + } + list.push({ + order: childGroup.options[key], + group: childGroup + }); + } + } + } + } + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + // TODO webpack 5 remove this check of compareTo + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } + return 0; + }); + result[name] = list.map(i => i.group); + } + return result; + } + + /** + * Sets the top-down index of a module in this ChunkGroup + * @param {Module} module module for which the index should be set + * @param {number} index the index of the module + * @returns {void} + */ + setModuleIndex(module, index) { + this._moduleIndices.set(module, index); + } + + /** + * Gets the top-down index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number} index + */ + getModuleIndex(module) { + return this._moduleIndices.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} + */ + setModuleIndex2(module, index) { + this._moduleIndices2.set(module, index); + } + + /** + * Gets the bottom-up index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number} index + */ + getModuleIndex2(module) { + return this._moduleIndices2.get(module); + } + + 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}` + ); + } + } + } +} + +module.exports = ChunkGroup; + + +/***/ }), + +/***/ 69865: +/***/ ((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__(97391); + +/** @typedef {import("./Chunk")} Chunk */ + +class ChunkRenderError extends WebpackError { + /** + * Create a new ChunkRenderError + * @param {Chunk} chunk A chunk + * @param {string} file Related file + * @param {Error} error Original error + */ + constructor(chunk, file, error) { + super(); + + this.name = "ChunkRenderError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.file = file; + this.chunk = chunk; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ChunkRenderError; + + +/***/ }), + +/***/ 6170: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(92402); + +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map} dependencyTemplates + */ + +module.exports = class ChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]) + }; + } + + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + + this.hooks.renderManifest.call(result, options); + + return result; + } + + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("ChunkTemplate"); + hash.update("2"); + this.hooks.hash.call(hash); + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + } +}; + + +/***/ }), + +/***/ 51760: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class CommentCompilationWarning extends WebpackError { + /** + * + * @param {string} message warning message + * @param {Module} module affected module + * @param {DependencyLocation} loc affected lines of code + */ + constructor(message, module, loc) { + super(message); + + this.name = "CommentCompilationWarning"; + + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = CommentCompilationWarning; + + +/***/ }), + +/***/ 85736: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); + +class CommonJsStuffPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "CommonJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + parser.hooks.expression + .for("require.main.require") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("require.main") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c[__webpack_require__.s]" + ) + ); + parser.hooks.expression + .for("module.loaded") + .tap("CommonJsStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.loaded"; + return ParserHelpers.toConstantDependency( + parser, + "module.l" + )(expr); + }); + parser.hooks.expression + .for("module.id") + .tap("CommonJsStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.id"; + return ParserHelpers.toConstantDependency( + parser, + "module.i" + )(expr); + }); + parser.hooks.expression + .for("module.exports") + .tap("CommonJsStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = + module.buildMeta && module.buildMeta.exportsType; + if (!isHarmony) return true; + }); + parser.hooks.evaluateIdentifier + .for("module.hot") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.evaluateToIdentifier("module.hot", false) + ); + parser.hooks.expression + .for("module") + .tap("CommonJsStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = + module.buildMeta && module.buildMeta.exportsType; + let moduleJsPath = isHarmony ? __webpack_require__.ab + "harmony-module.js" : __webpack_require__.ab + "module.js"; + if (module.context) { + moduleJsPath = path.relative( + parser.state.module.context, + moduleJsPath + ); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; + } + } + return ParserHelpers.addParsedVariableToModule( + parser, + "module", + `require(${JSON.stringify(moduleJsPath)})(module)` + ); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsStuffPlugin", handler); + } + ); + } +} +module.exports = CommonJsStuffPlugin; + + +/***/ }), + +/***/ 85918: +/***/ ((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__(71101); + +const NullFactory = __webpack_require__(40438); + +/** @typedef {import("./Compiler")} Compiler */ + +class CompatibilityPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "CompatibilityPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", (parser, parserOptions) => { + if ( + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) + return; + + parser.hooks.call + .for("require") + .tap("CompatibilityPlugin", expr => { + // support for browserify style require delegator: "require(o, !0)" + if (expr.arguments.length !== 2) return; + const second = parser.evaluateExpression(expr.arguments[1]); + if (!second.isBoolean()) return; + if (second.asBool() !== true) return; + const dep = new ConstDependency("require", expr.callee.range); + dep.loc = expr.loc; + if (parser.state.current.dependencies.length > 1) { + const last = + parser.state.current.dependencies[ + parser.state.current.dependencies.length - 1 + ]; + if ( + last.critical && + last.options && + last.options.request === "." && + last.userRequest === "." && + last.options.recursive + ) + parser.state.current.dependencies.pop(); + } + parser.state.current.addDependency(dep); + return true; + }); + }); + } + ); + } +} +module.exports = CompatibilityPlugin; + + +/***/ }), + +/***/ 34968: +/***/ ((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__(36386); +const util = __webpack_require__(31669); +const { CachedSource } = __webpack_require__(53665); +const { + Tapable, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook +} = __webpack_require__(92402); +const EntryModuleNotFoundError = __webpack_require__(99531); +const ModuleNotFoundError = __webpack_require__(71638); +const ModuleDependencyWarning = __webpack_require__(59136); +const ModuleDependencyError = __webpack_require__(14953); +const ChunkGroup = __webpack_require__(52911); +const Chunk = __webpack_require__(2919); +const Entrypoint = __webpack_require__(71931); +const MainTemplate = __webpack_require__(43626); +const ChunkTemplate = __webpack_require__(6170); +const HotUpdateChunkTemplate = __webpack_require__(66062); +const ModuleTemplate = __webpack_require__(75100); +const RuntimeTemplate = __webpack_require__(44006); +const ChunkRenderError = __webpack_require__(69865); +const Stats = __webpack_require__(99977); +const Semaphore = __webpack_require__(33349); +const createHash = __webpack_require__(15660); +const SortableSet = __webpack_require__(50071); +const GraphHelpers = __webpack_require__(32973); +const ModuleDependency = __webpack_require__(90865); +const compareLocations = __webpack_require__(22562); +const { Logger, LogType } = __webpack_require__(47194); +const ErrorHelpers = __webpack_require__(80140); +const buildChunkGraph = __webpack_require__(52337); +const WebpackError = __webpack_require__(97391); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {import("./dependencies/SingleEntryDependency")} SingleEntryDependency */ +/** @typedef {import("./dependencies/MultiEntryDependency")} MultiEntryDependency */ +/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ +/** @typedef {import("./dependencies/DependencyReference")} DependencyReference */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +// TODO use @callback +/** @typedef {{[assetName: string]: Source}} CompilationAssets */ +/** @typedef {(err: Error|null, result?: Module) => void } ModuleCallback */ +/** @typedef {(err?: Error|null, result?: Module) => void } ModuleChainCallback */ +/** @typedef {(module: Module) => void} OnModuleCallback */ +/** @typedef {(err?: Error|null) => void} Callback */ +/** @typedef {(d: Dependency) => any} DepBlockVarDependenciesCallback */ +/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ +/** @typedef {{apply: () => void}} Plugin */ + +/** + * @typedef {Object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {string} compiler + */ + +/** + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {any=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ + +/** + * @typedef {Object} ModuleFactory + * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create + */ + +/** + * @typedef {Object} SortedDependency + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + */ + +/** + * @typedef {Object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + * @property {DependenciesBlockVariable[]} variables + */ + +/** + * @typedef {Object} LogEntry + * @property {string} type + * @property {any[]} args + * @property {number} time + * @property {string[]=} trace + */ + +/** + * @typedef {Object} AssetInfo + * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) + * @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) + */ + +/** + * @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 {Chunk} a first chunk to sort by id + * @param {Chunk} b second chunk to sort by id + * @returns {-1|0|1} sort value + */ +const byId = (a, b) => { + if (typeof a.id !== typeof b.id) { + return typeof a.id < typeof b.id ? -1 : 1; + } + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + return 0; +}; + +/** + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value + */ +const byIdOrIdentifier = (a, b) => { + if (typeof a.id !== typeof b.id) { + return typeof a.id < typeof b.id ? -1 : 1; + } + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; + +/** + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value + */ +const byIndexOrIdentifier = (a, b) => { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; + +/** + * @param {Compilation} a first compilation to sort by + * @param {Compilation} b second compilation to sort by + * @returns {-1|0|1} sort value + */ +const byNameOrHash = (a, b) => { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + if (a.fullHash < b.fullHash) return -1; + if (a.fullHash > b.fullHash) return 1; + return 0; +}; + +/** + * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over + * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements + * @returns {void} + */ +const iterationBlockVariable = (variables, fn) => { + for ( + let indexVariable = 0; + indexVariable < variables.length; + indexVariable++ + ) { + const varDep = variables[indexVariable].dependencies; + for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { + fn(varDep[indexVDep]); + } + } +}; + +/** + * @template T + * @param {T[]} arr array of elements to iterate over + * @param {function(T): void} fn callback applied to each element + * @returns {void} + */ +const iterationOfArrayCallback = (arr, fn) => { + for (let index = 0; index < arr.length; index++) { + fn(arr[index]); + } +}; + +/** + * @template T + * @param {Set} set set to add items to + * @param {Set} otherSet set to add items from + * @returns {void} + */ +const addAllToSet = (set, otherSet) => { + for (const item of otherSet) { + set.add(item); + } +}; + +/** + * @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; + // TODO webpack 5: check .buffer() instead, it's called anyway during emit + /** @type {Buffer|string} */ + let aSource = a.source(); + /** @type {Buffer|string} */ + let bSource = 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 Compilation extends Tapable { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + */ + constructor(compiler) { + super(); + this.hooks = { + /** @type {SyncHook} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook} */ + succeedModule: new SyncHook(["module"]), + + /** @type {SyncHook} */ + addEntry: new SyncHook(["entry", "name"]), + /** @type {SyncHook} */ + failedEntry: new SyncHook(["entry", "name", "error"]), + /** @type {SyncHook} */ + succeedEntry: new SyncHook(["entry", "name", "module"]), + + /** @type {SyncWaterfallHook} */ + dependencyReference: new SyncWaterfallHook([ + "dependencyReference", + "dependency", + "module" + ]), + + /** @type {AsyncSeriesHook} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {SyncHook} */ + finishRebuildingModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + unseal: new SyncHook([]), + /** @type {SyncHook} */ + seal: new SyncHook([]), + + /** @type {SyncHook} */ + beforeChunks: new SyncHook([]), + /** @type {SyncHook} */ + afterChunks: new SyncHook(["chunks"]), + + /** @type {SyncBailHook} */ + optimizeDependenciesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + afterOptimizeDependencies: new SyncHook(["modules"]), + + /** @type {SyncHook} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook} */ + optimizeModulesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeModulesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncHook} */ + afterOptimizeModules: new SyncHook(["modules"]), + + /** @type {SyncBailHook} */ + optimizeChunksBasic: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook} */ + optimizeChunksAdvanced: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), + + /** @type {AsyncSeriesHook} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), + + /** @type {SyncBailHook} */ + optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncHook} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + shouldRecord: new SyncBailHook([]), + + /** @type {SyncHook} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook} */ + optimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook} */ + advancedOptimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), + + /** @type {SyncHook} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook} */ + optimizeChunkOrder: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), + + /** @type {SyncHook} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook} */ + recordChunks: new SyncHook(["chunks", "records"]), + + /** @type {SyncHook} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook} */ + afterHash: new SyncHook([]), + /** @type {SyncHook} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook} */ + record: new SyncHook(["compilation", "records"]), + + /** @type {SyncHook} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook} */ + beforeChunkAssets: new SyncHook([]), + /** @type {SyncHook} */ + additionalChunkAssets: new SyncHook(["chunks"]), + + /** @type {AsyncSeriesHook} */ + additionalAssets: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook} */ + optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeChunkAssets: new SyncHook(["chunks"]), + /** @type {AsyncSeriesHook} */ + optimizeAssets: new AsyncSeriesHook(["assets"]), + /** @type {SyncHook} */ + afterOptimizeAssets: new SyncHook(["assets"]), + + /** @type {SyncBailHook} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook} */ + afterSeal: new AsyncSeriesHook([]), + + /** @type {SyncHook} */ + chunkHash: new SyncHook(["chunk", "chunkHash"]), + /** @type {SyncHook} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook} */ + chunkAsset: new SyncHook(["chunk", "filename"]), + + /** @type {SyncWaterfallHook} */ + assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate + + /** @type {SyncBailHook} */ + needAdditionalPass: new SyncBailHook([]), + + /** @type {SyncHook} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), + + /** @type {SyncBailHook} */ + log: new SyncBailHook(["origin", "logEntry"]), + + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook} */ + normalModuleLoader: new SyncHook(["loaderContext", "module"]), + + /** @type {SyncBailHook} */ + optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunks: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeExtractedChunks: new SyncHook(["chunks"]) + }; + this._pluginCompat.tap("Compilation", options => { + switch (options.name) { + case "optimize-tree": + case "additional-assets": + case "optimize-chunk-assets": + case "optimize-assets": + case "after-seal": + options.async = true; + break; + } + }); + /** @type {string=} */ + this.name = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + this.inputFileSystem = compiler.inputFileSystem; + this.requestShortener = compiler.requestShortener; + + const options = compiler.options; + this.options = options; + this.outputOptions = options && options.output; + /** @type {boolean=} */ + this.bail = options && options.bail; + this.profile = options && options.profile; + this.performance = options && options.performance; + + this.mainTemplate = new MainTemplate(this.outputOptions); + this.chunkTemplate = new ChunkTemplate(this.outputOptions); + this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate( + this.outputOptions + ); + this.runtimeTemplate = new RuntimeTemplate( + this.outputOptions, + this.requestShortener + ); + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"), + webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly") + }; + + this.semaphore = new Semaphore(options.parallelism || 100); + + this.entries = []; + /** @private @type {{name: string, request: string, module: Module}[]} */ + this._preparedEntrypoints = []; + /** @type {Map} */ + this.entrypoints = new Map(); + /** @type {Chunk[]} */ + this.chunks = []; + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map} */ + this.namedChunkGroups = new Map(); + /** @type {Map} */ + this.namedChunks = new Map(); + /** @type {Module[]} */ + this.modules = []; + /** @private @type {Map} */ + this._modules = new Map(); + this.cache = null; + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {Map} */ + this.assetsInfo = 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 {Map} */ + this.dependencyTemplates = new Map(); + // TODO refactor this in webpack 5 to a custom DependencyTemplates class with a hash property + // @ts-ignore + this.dependencyTemplates.set("hash", ""); + this.childrenCounters = {}; + /** @type {Set} */ + this.usedChunkIds = null; + /** @type {Set} */ + this.usedModuleIds = null; + /** @type {Map=} */ + this.fileTimestamps = undefined; + /** @type {Map=} */ + this.contextTimestamps = undefined; + /** @type {Set=} */ + this.compilationDependencies = undefined; + /** @private @type {Map} */ + this._buildingModules = new Map(); + /** @private @type {Map} */ + this._rebuildingModules = new Map(); + /** @type {Set} */ + this.emittedAssets = new Set(); + } + + getStats() { + return new Stats(this); + } + + /** + * @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]}`); + } + } + } + }); + } + + /** + * @typedef {Object} AddModuleResult + * @property {Module} module the added or existing module + * @property {boolean} issuer was this the first request for this module + * @property {boolean} build should the module be build + * @property {boolean} dependencies should dependencies be walked + */ + + /** + * @param {Module} module module to be added that was created + * @param {any=} cacheGroup cacheGroup it is apart of + * @returns {AddModuleResult} returns meta about whether or not the module had built + * had an issuer, or any dependnecies + */ + addModule(module, cacheGroup) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return { + module: alreadyAddedModule, + issuer: false, + build: false, + dependencies: false + }; + } + const cacheName = (cacheGroup || "m") + identifier; + if (this.cache && this.cache[cacheName]) { + const cacheModule = this.cache[cacheName]; + + if (typeof cacheModule.updateCacheModule === "function") { + cacheModule.updateCacheModule(module); + } + + let rebuild = true; + if (this.fileTimestamps && this.contextTimestamps) { + rebuild = cacheModule.needRebuild( + this.fileTimestamps, + this.contextTimestamps + ); + } + + if (!rebuild) { + cacheModule.disconnect(); + this._modules.set(identifier, cacheModule); + this.modules.push(cacheModule); + for (const err of cacheModule.errors) { + this.errors.push(err); + } + for (const err of cacheModule.warnings) { + this.warnings.push(err); + } + return { + module: cacheModule, + issuer: true, + build: false, + dependencies: true + }; + } + cacheModule.unbuild(); + module = cacheModule; + } + this._modules.set(identifier, module); + if (this.cache) { + this.cache[cacheName] = module; + } + this.modules.push(module); + return { + module: module, + issuer: true, + build: true, + dependencies: true + }; + } + + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return this._modules.get(identifier); + } + + /** + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined + */ + findModule(identifier) { + return this._modules.get(identifier); + } + + /** + * @param {Module} module module with its callback list + * @param {Callback} callback the callback function + * @returns {void} + */ + waitForBuildingFinished(module, callback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(() => callback()); + } else { + process.nextTick(callback); + } + } + + /** + * Builds the module object + * + * @param {Module} module module to be built + * @param {boolean} optional optional flag + * @param {Module=} origin origin module this module build was requested from + * @param {Dependency[]=} dependencies optional dependencies from the module to be built + * @param {TODO} thisCallback the callback + * @returns {TODO} returns the callback function with results + */ + buildModule(module, optional, origin, dependencies, thisCallback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._buildingModules.set(module, (callbackList = [thisCallback])); + + const callback = err => { + this._buildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; + + this.hooks.buildModule.call(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + this.inputFileSystem, + error => { + const errors = module.errors; + for (let indexError = 0; indexError < errors.length; indexError++) { + const err = errors[indexError]; + err.origin = origin; + err.dependencies = dependencies; + if (optional) { + this.warnings.push(err); + } else { + this.errors.push(err); + } + } + + const warnings = module.warnings; + for ( + let indexWarning = 0; + indexWarning < warnings.length; + indexWarning++ + ) { + const war = warnings[indexWarning]; + war.origin = origin; + war.dependencies = dependencies; + this.warnings.push(war); + } + const originalMap = module.dependencies.reduce((map, v, i) => { + map.set(v, i); + return map; + }, new Map()); + module.dependencies.sort((a, b) => { + const cmp = compareLocations(a.loc, b.loc); + if (cmp) return cmp; + return originalMap.get(a) - originalMap.get(b); + }); + if (error) { + this.hooks.failedModule.call(module, error); + return callback(error); + } + this.hooks.succeedModule.call(module); + return callback(); + } + ); + } + + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + const dependencies = new Map(); + + const addDependency = dep => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent) { + const factory = this.dependencyFactories.get(dep.constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ); + } + let innerMap = dependencies.get(factory); + if (innerMap === undefined) { + dependencies.set(factory, (innerMap = new Map())); + } + let list = innerMap.get(resourceIdent); + if (list === undefined) innerMap.set(resourceIdent, (list = [])); + list.push(dep); + } + }; + + const addDependenciesBlock = block => { + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, addDependency); + } + if (block.blocks) { + iterationOfArrayCallback(block.blocks, addDependenciesBlock); + } + if (block.variables) { + iterationBlockVariable(block.variables, addDependency); + } + }; + + try { + addDependenciesBlock(module); + } catch (e) { + callback(e); + } + + const sortedDependencies = []; + + for (const pair1 of dependencies) { + for (const pair2 of pair1[1]) { + sortedDependencies.push({ + factory: pair1[0], + dependencies: pair2[1] + }); + } + } + + this.addModuleDependencies( + module, + sortedDependencies, + this.bail, + null, + true, + callback + ); + } + + /** + * @param {Module} module module to add deps to + * @param {SortedDependency[]} dependencies set of sorted dependencies to iterate through + * @param {(boolean|null)=} bail whether to bail or not + * @param {TODO} cacheGroup optional cacheGroup + * @param {boolean} recursive whether it is recursive traversal + * @param {function} callback callback for when dependencies are finished being added + * @returns {void} + */ + addModuleDependencies( + module, + dependencies, + bail, + cacheGroup, + recursive, + callback + ) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; + + asyncLib.forEach( + dependencies, + (item, callback) => { + const dependencies = item.dependencies; + + const errorAndCallback = err => { + err.origin = module; + err.dependencies = dependencies; + this.errors.push(err); + if (bail) { + callback(err); + } else { + callback(); + } + }; + const warningAndCallback = err => { + err.origin = module; + this.warnings.push(err); + callback(); + }; + + const semaphore = this.semaphore; + semaphore.acquire(() => { + const factory = item.factory; + factory.create( + { + contextInfo: { + issuer: module.nameForCondition && module.nameForCondition(), + compiler: this.compiler.name + }, + resolveOptions: module.resolveOptions, + context: module.context, + dependencies: dependencies + }, + (err, dependentModule) => { + let afterFactory; + + const isOptional = () => { + return dependencies.every(d => d.optional); + }; + + const errorOrWarningAndCallback = err => { + if (isOptional()) { + return warningAndCallback(err); + } else { + return errorAndCallback(err); + } + }; + + if (err) { + semaphore.release(); + return errorOrWarningAndCallback( + new ModuleNotFoundError(module, err) + ); + } + if (!dependentModule) { + semaphore.release(); + return process.nextTick(callback); + } + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } + + const iterationDependencies = depend => { + for (let index = 0; index < depend.length; index++) { + const dep = depend[index]; + dep.module = dependentModule; + dependentModule.addReason(module, dep); + } + }; + + const addModuleResult = this.addModule( + dependentModule, + cacheGroup + ); + dependentModule = addModuleResult.module; + iterationDependencies(dependencies); + + const afterBuild = () => { + if (recursive && addModuleResult.dependencies) { + this.processModuleDependencies(dependentModule, callback); + } else { + return callback(); + } + }; + + if (addModuleResult.issuer) { + if (currentProfile) { + dependentModule.profile = currentProfile; + } + + dependentModule.issuer = module; + } else { + if (this.profile) { + if (module.profile) { + const time = Date.now() - start; + if ( + !module.profile.dependencies || + time > module.profile.dependencies + ) { + module.profile.dependencies = time; + } + } + } + } + + if (addModuleResult.build) { + this.buildModule( + dependentModule, + isOptional(), + module, + dependencies, + err => { + if (err) { + semaphore.release(); + return errorOrWarningAndCallback(err); + } + + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + semaphore.release(); + afterBuild(); + } + ); + } else { + semaphore.release(); + this.waitForBuildingFinished(dependentModule, afterBuild); + } + } + ); + }); + }, + err => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. + + if (err) { + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + return callback(err); + } + + return process.nextTick(callback); + } + ); + } + + /** + * + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {OnModuleCallback} onModule function invoked on modules creation + * @param {ModuleChainCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + _addModuleChain(context, dependency, onModule, callback) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; + + const errorAndCallback = this.bail + ? err => { + callback(err); + } + : err => { + err.dependencies = [dependency]; + this.errors.push(err); + callback(); + }; + + if ( + typeof dependency !== "object" || + dependency === null || + !dependency.constructor + ) { + throw new Error("Parameter 'dependency' must be a Dependency"); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + throw new Error( + `No dependency factory available for this dependency type: ${dependency.constructor.name}` + ); + } + + this.semaphore.acquire(() => { + moduleFactory.create( + { + contextInfo: { + issuer: "", + compiler: this.compiler.name + }, + context: context, + dependencies: [dependency] + }, + (err, module) => { + if (err) { + this.semaphore.release(); + return errorAndCallback(new EntryModuleNotFoundError(err)); + } + + let afterFactory; + + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } + + const addModuleResult = this.addModule(module); + module = addModuleResult.module; + + onModule(module); + + dependency.module = module; + module.addReason(null, dependency); + + const afterBuild = () => { + if (addModuleResult.dependencies) { + this.processModuleDependencies(module, err => { + if (err) return callback(err); + callback(null, module); + }); + } else { + return callback(null, module); + } + }; + + if (addModuleResult.issuer) { + if (currentProfile) { + module.profile = currentProfile; + } + } + + if (addModuleResult.build) { + this.buildModule(module, false, null, null, err => { + if (err) { + this.semaphore.release(); + return errorAndCallback(err); + } + + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + this.semaphore.release(); + afterBuild(); + }); + } else { + this.semaphore.release(); + this.waitForBuildingFinished(module, afterBuild); + } + } + ); + }); + } + + /** + * + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency being created + * @param {string} name name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addEntry(context, entry, name, callback) { + this.hooks.addEntry.call(entry, name); + + const slot = { + name: name, + // TODO webpack 5 remove `request` + request: null, + module: null + }; + + if (entry instanceof ModuleDependency) { + slot.request = entry.request; + } + + // TODO webpack 5: merge modules instead when multiple entry modules are supported + const idx = this._preparedEntrypoints.findIndex(slot => slot.name === name); + if (idx >= 0) { + // Overwrite existing entrypoint + this._preparedEntrypoints[idx] = slot; + } else { + this._preparedEntrypoints.push(slot); + } + this._addModuleChain( + context, + entry, + module => { + this.entries.push(module); + }, + (err, module) => { + if (err) { + this.hooks.failedEntry.call(entry, name, err); + return callback(err); + } + + if (module) { + slot.module = module; + } else { + const idx = this._preparedEntrypoints.indexOf(slot); + if (idx >= 0) { + this._preparedEntrypoints.splice(idx, 1); + } + } + this.hooks.succeedEntry.call(entry, name, module); + return callback(null, module); + } + ); + } + + /** + * @param {string} context context path string + * @param {Dependency} dependency dep used to create module + * @param {ModuleCallback} callback module callback sending module up a level + * @returns {void} + */ + prefetch(context, dependency, callback) { + this._addModuleChain( + context, + dependency, + module => { + module.prefetched = true; + }, + callback + ); + } + + /** + * @param {Module} module module to be rebuilt + * @param {Callback} thisCallback callback when module finishes rebuilding + * @returns {void} + */ + rebuildModule(module, thisCallback) { + let callbackList = this._rebuildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._rebuildingModules.set(module, (callbackList = [thisCallback])); + + const callback = err => { + this._rebuildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; + + this.hooks.rebuildModule.call(module); + const oldDependencies = module.dependencies.slice(); + const oldVariables = module.variables.slice(); + const oldBlocks = module.blocks.slice(); + module.unbuild(); + this.buildModule(module, false, module, null, err => { + if (err) { + this.hooks.finishRebuildingModule.call(module); + return callback(err); + } + + this.processModuleDependencies(module, err => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + variables: oldVariables, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.call(module); + callback(); + }); + }); + } + + finish(callback) { + const modules = this.modules; + this.hooks.finishModules.callAsync(modules, err => { + if (err) return callback(err); + + for (let index = 0; index < modules.length; index++) { + const module = modules[index]; + this.reportDependencyErrorsAndWarnings(module, [module]); + } + + callback(); + }); + } + + unseal() { + this.hooks.unseal.call(); + this.chunks.length = 0; + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + this.assetsInfo.clear(); + for (const module of this.modules) { + module.unseal(); + } + } + + /** + * @param {Callback} callback signals when the seal method is finishes + * @returns {void} + */ + seal(callback) { + this.hooks.seal.call(); + + while ( + this.hooks.optimizeDependenciesBasic.call(this.modules) || + this.hooks.optimizeDependencies.call(this.modules) || + this.hooks.optimizeDependenciesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + + this.hooks.beforeChunks.call(); + for (const preparedEntrypoint of this._preparedEntrypoints) { + const module = preparedEntrypoint.module; + const name = preparedEntrypoint.name; + const chunk = this.addChunk(name); + const entrypoint = new Entrypoint(name); + entrypoint.setRuntimeChunk(chunk); + entrypoint.addOrigin(null, name, preparedEntrypoint.request); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); + + GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); + GraphHelpers.connectChunkAndModule(chunk, module); + + chunk.entryModule = module; + chunk.name = name; + + this.assignDepth(module); + } + buildChunkGraph( + this, + /** @type {Entrypoint[]} */ (this.chunkGroups.slice()) + ); + this.sortModules(this.modules); + this.hooks.afterChunks.call(this.chunks); + + this.hooks.optimize.call(); + + while ( + this.hooks.optimizeModulesBasic.call(this.modules) || + this.hooks.optimizeModules.call(this.modules) || + this.hooks.optimizeModulesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeModules.call(this.modules); + + while ( + this.hooks.optimizeChunksBasic.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunksAdvanced.call(this.chunks, this.chunkGroups) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); + + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return callback(err); + } + + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + + while ( + this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); + + const shouldRecord = this.hooks.shouldRecord.call() !== false; + + this.hooks.reviveModules.call(this.modules, this.records); + this.hooks.optimizeModuleOrder.call(this.modules); + this.hooks.advancedOptimizeModuleOrder.call(this.modules); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.applyModuleIds(); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); + + this.sortItemsWithModuleIds(); + + this.hooks.reviveChunks.call(this.chunks, this.records); + this.hooks.optimizeChunkOrder.call(this.chunks); + this.hooks.beforeChunkIds.call(this.chunks); + this.applyChunkIds(); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); + + this.sortItemsWithChunkIds(); + + if (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } + + this.hooks.beforeHash.call(); + this.createHash(); + this.hooks.afterHash.call(); + + if (shouldRecord) { + this.hooks.recordHash.call(this.records); + } + + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets(); + } + this.hooks.additionalChunkAssets.call(this.chunks); + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } + + this.hooks.additionalAssets.callAsync(err => { + if (err) { + return callback(err); + } + this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeChunkAssets.call(this.chunks); + this.hooks.optimizeAssets.callAsync(this.assets, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeAssets.call(this.assets); + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); + } + return this.hooks.afterSeal.callAsync(callback); + }); + }); + }); + }); + } + + /** + * @param {Module[]} modules the modules array on compilation to perform the sort for + * @returns {void} + */ + sortModules(modules) { + // TODO webpack 5: this should only be enabled when `moduleIds: "natural"` + // TODO move it into a plugin (NaturalModuleIdsPlugin) and use this in WebpackOptionsApply + // TODO remove this method + modules.sort(byIndexOrIdentifier); + } + + /** + * @param {Module} module moulde to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {void} + */ + reportDependencyErrorsAndWarnings(module, blocks) { + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const block = blocks[indexBlock]; + const dependencies = block.dependencies; + + for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { + const d = dependencies[indexDep]; + + const warnings = d.getWarnings(); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; + + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + } + } + const errors = d.getErrors(); + if (errors) { + for (let indexErr = 0; indexErr < errors.length; indexErr++) { + const e = errors[indexErr]; + + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + } + } + } + + this.reportDependencyErrorsAndWarnings(module, block.blocks); + } + } + + /** + * @param {TODO} groupOptions options for the chunk group + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + chunkGroup.addOptions(groupOptions); + if (module) { + chunkGroup.addOrigin(module, loc, request); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) chunkGroup.addOrigin(module, loc, request); + const chunk = this.addChunk(name); + + GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); + + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; + } + + /** + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * + * @param {string=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) + */ + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } + } + const chunk = new Chunk(name); + this.chunks.push(chunk); + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; + } + + /** + * @param {Module} module module to assign depth + * @returns {void} + */ + assignDepth(module) { + const queue = new Set([module]); + let depth; + + module.depth = 0; + + /** + * @param {Module} module module for processeing + * @returns {void} + */ + const enqueueJob = module => { + const d = module.depth; + if (typeof d === "number" && d <= depth) return; + queue.add(module); + module.depth = depth; + }; + + /** + * @param {Dependency} dependency dependency to assign depth to + * @returns {void} + */ + const assignDepthToDependency = dependency => { + if (dependency.module) { + enqueueJob(dependency.module); + } + }; + + /** + * @param {DependenciesBlock} block block to assign depth to + * @returns {void} + */ + const assignDepthToDependencyBlock = block => { + if (block.variables) { + iterationBlockVariable(block.variables, assignDepthToDependency); + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, assignDepthToDependency); + } + + if (block.blocks) { + iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); + } + }; + + for (module of queue) { + queue.delete(module); + depth = module.depth; + + depth++; + assignDepthToDependencyBlock(module); + } + } + + /** + * @param {Module} module the module containing the dependency + * @param {Dependency} dependency the dependency + * @returns {DependencyReference} a reference for the dependency + */ + getDependencyReference(module, dependency) { + // TODO remove dep.getReference existence check in webpack 5 + if (typeof dependency.getReference !== "function") return null; + const ref = dependency.getReference(); + if (!ref) return null; + return this.hooks.dependencyReference.call(ref, dependency, module); + } + + /** + * + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block //TODO: good description + * @returns {void} + */ + removeReasonsOfDependencyBlock(module, block) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + if (d.module.removeReason(module, d)) { + for (const chunk of d.module.chunksIterable) { + this.patchChunksAfterReasonRemoval(d.module, chunk); + } + } + }; + + if (block.blocks) { + iterationOfArrayCallback(block.blocks, block => + this.removeReasonsOfDependencyBlock(module, block) + ); + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } + + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + } + + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} + */ + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons()) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk)) { + if (module.removeChunk(chunk)) { + this.removeChunkFromDependencies(module, chunk); + } + } + } + + /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} + */ + removeChunkFromDependencies(block, chunk) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + this.patchChunksAfterReasonRemoval(d.module, chunk); + }; + + const blocks = block.blocks; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const asyncBlock = blocks[indexBlock]; + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = asyncBlock.chunkGroup.chunks; + // For each chunk in chunkGroup + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const iteratedChunk = chunks[indexChunk]; + asyncBlock.chunkGroup.removeChunk(iteratedChunk); + asyncBlock.chunkGroup.removeParent(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } + + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + } + + applyModuleIds() { + const unusedIds = []; + let nextFreeModuleId = 0; + const usedIds = new Set(); + if (this.usedModuleIds) { + for (const id of this.usedModuleIds) { + usedIds.add(id); + } + } + + const modules1 = this.modules; + for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { + const module1 = modules1[indexModule1]; + if (module1.id !== null) { + usedIds.add(module1.id); + } + } + + if (usedIds.size > 0) { + let usedIdMax = -1; + for (const usedIdKey of usedIds) { + if (typeof usedIdKey !== "number") { + continue; + } + + usedIdMax = Math.max(usedIdMax, usedIdKey); + } + + let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); + + while (lengthFreeModules--) { + if (!usedIds.has(lengthFreeModules)) { + unusedIds.push(lengthFreeModules); + } + } + } + + const modules2 = this.modules; + for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { + const module2 = modules2[indexModule2]; + if (module2.id === null) { + if (unusedIds.length > 0) { + module2.id = unusedIds.pop(); + } else { + module2.id = nextFreeModuleId++; + } + } + } + } + + applyChunkIds() { + /** @type {Set} */ + const usedIds = new Set(); + + // Get used ids from usedChunkIds property (i. e. from records) + if (this.usedChunkIds) { + for (const id of this.usedChunkIds) { + if (typeof id !== "number") { + continue; + } + + usedIds.add(id); + } + } + + // Get used ids from existing chunks + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + const usedIdValue = chunk.id; + + if (typeof usedIdValue !== "number") { + continue; + } + + usedIds.add(usedIdValue); + } + + // Calculate maximum assigned chunk id + let nextFreeChunkId = -1; + for (const id of usedIds) { + nextFreeChunkId = Math.max(nextFreeChunkId, id); + } + nextFreeChunkId++; + + // Determine free chunk ids from 0 to maximum + /** @type {number[]} */ + const unusedIds = []; + if (nextFreeChunkId > 0) { + let index = nextFreeChunkId; + while (index--) { + if (!usedIds.has(index)) { + unusedIds.push(index); + } + } + } + + // Assign ids to chunk which has no id + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunk.id === null) { + if (unusedIds.length > 0) { + chunk.id = unusedIds.pop(); + } else { + chunk.id = nextFreeChunkId++; + } + } + if (!chunk.ids) { + chunk.ids = [chunk.id]; + } + } + } + + sortItemsWithModuleIds() { + this.modules.sort(byIdOrIdentifier); + + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + modules[indexModule].sortItems(false); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } + + chunks.sort((a, b) => a.compareTo(b)); + } + + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); + } + + this.chunks.sort(byId); + + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + this.modules[indexModule].sortItems(true); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } + + /** + * Used to sort errors and warnings in compilation. this.warnings, and + * this.errors contribute to the compilation hash and therefore should be + * updated whenever other references (having a chunk id) are sorted. This preserves the hash + * integrity + * + * @param {WebpackError} a first WebpackError instance (including subclasses) + * @param {WebpackError} b second WebpackError instance (including subclasses) + * @returns {-1|0|1} sort order index + */ + const byMessage = (a, b) => { + const ma = `${a.message}`; + const mb = `${b.message}`; + if (ma < mb) return -1; + if (mb < ma) return 1; + return 0; + }; + + this.errors.sort(byMessage); + this.warnings.sort(byMessage); + this.children.sort(byNameOrHash); + } + + summarizeDependencies() { + this.fileDependencies = new SortableSet(this.compilationDependencies); + this.contextDependencies = new SortableSet(); + this.missingDependencies = new SortableSet(); + + for ( + let indexChildren = 0; + indexChildren < this.children.length; + indexChildren++ + ) { + const child = this.children[indexChildren]; + + addAllToSet(this.fileDependencies, child.fileDependencies); + addAllToSet(this.contextDependencies, child.contextDependencies); + addAllToSet(this.missingDependencies, child.missingDependencies); + } + + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + const module = this.modules[indexModule]; + + if (module.buildInfo.fileDependencies) { + addAllToSet(this.fileDependencies, module.buildInfo.fileDependencies); + } + if (module.buildInfo.contextDependencies) { + addAllToSet( + this.contextDependencies, + module.buildInfo.contextDependencies + ); + } + } + for (const error of this.errors) { + if ( + typeof error.missing === "object" && + error.missing && + error.missing[Symbol.iterator] + ) { + addAllToSet(this.missingDependencies, error.missing); + } + } + this.fileDependencies.sort(); + this.contextDependencies.sort(); + this.missingDependencies.sort(); + } + + createHash() { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.mainTemplate.updateHash(hash); + this.chunkTemplate.updateHash(hash); + for (const key of Object.keys(this.moduleTemplates).sort()) { + this.moduleTemplates[key].updateHash(hash); + } + for (const child of this.children) { + hash.update(child.hash); + } + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + for (const error of this.errors) { + hash.update(`${error.message}`); + } + const modules = this.modules; + for (let i = 0; i < modules.length; i++) { + const module = modules[i]; + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash); + module.hash = /** @type {string} */ (moduleHash.digest(hashDigest)); + module.renderedHash = module.hash.substr(0, hashDigestLength); + } + // clone needed as sort below is inplace mutation + const chunks = this.chunks.slice(); + /** + * sort here will bring all "falsy" values to the beginning + * this is needed as the "hasRuntime()" chunks are dependent on the + * hashes of the non-runtime chunks. + */ + chunks.sort((a, b) => { + const aEntry = a.hasRuntime(); + const bEntry = b.hasRuntime(); + if (aEntry && !bEntry) return 1; + if (!aEntry && bEntry) return -1; + return byId(a, b); + }); + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const chunkHash = createHash(hashFunction); + try { + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash); + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + template.updateHashForChunk( + chunkHash, + chunk, + this.moduleTemplates.javascript, + this.dependencyTemplates + ); + this.hooks.chunkHash.call(chunk, chunkHash); + chunk.hash = /** @type {string} */ (chunkHash.digest(hashDigest)); + hash.update(chunk.hash); + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + } + } + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); + } + + /** + * @param {string} update extra information + * @returns {void} + */ + modifyHash(update) { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + hash.update(this.fullHash); + hash.update(update); + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); + } + + /** + * @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)) { + // TODO webpack 5: make this an error instead + this.warnings.push( + new WebpackError( + `Conflict: Multiple assets emit different content to the same filename ${file}` + ) + ); + this.assets[file] = source; + this.assetsInfo.set(file, assetInfo); + return; + } + const oldInfo = this.assetsInfo.get(file); + this.assetsInfo.set(file, Object.assign({}, oldInfo, assetInfo)); + return; + } + this.assets[file] = source; + this.assetsInfo.set(file, assetInfo); + } + + /** + * @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); + if (typeof assetInfoUpdateOrFunction === "function") { + this.assetsInfo.set(file, assetInfoUpdateOrFunction(oldInfo || {})); + } else { + this.assetsInfo.set( + file, + Object.assign({}, oldInfo, assetInfoUpdateOrFunction) + ); + } + } + } + + getAssets() { + /** @type {Asset[]} */ + 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) || {} + }); + } + } + return array; + } + + /** + * @param {string} name the name of the asset + * @returns {Asset | 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) || {} + }; + } + + createModuleAssets() { + for (let i = 0; i < this.modules.length; i++) { + const module = this.modules[i]; + if (module.buildInfo.assets) { + const assetsInfo = module.buildInfo.assetsInfo; + for (const assetName of Object.keys(module.buildInfo.assets)) { + const fileName = this.getPath(assetName); + this.emitAsset( + fileName, + module.buildInfo.assets[assetName], + assetsInfo ? assetsInfo.get(assetName) : undefined + ); + this.hooks.moduleAsset.call(module, fileName); + } + } + } + } + + createChunkAssets() { + const outputOptions = this.outputOptions; + const cachedSourceMap = new Map(); + /** @type {Map} */ + const alreadyWrittenFiles = new Map(); + for (let i = 0; i < this.chunks.length; i++) { + const chunk = this.chunks[i]; + chunk.files = []; + let source; + let file; + let filenameTemplate; + try { + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + const manifest = template.getRenderManifest({ + chunk, + hash: this.hash, + fullHash: this.fullHash, + outputOptions, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates + }); // [{ render(), filenameTemplate, pathOptions, identifier, hash }] + for (const fileManifest of manifest) { + const cacheName = fileManifest.identifier; + const usedHash = fileManifest.hash; + filenameTemplate = fileManifest.filenameTemplate; + const pathAndInfo = this.getPathWithInfo( + filenameTemplate, + fileManifest.pathOptions + ); + file = pathAndInfo.path; + const assetInfo = pathAndInfo.info; + + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash === usedHash) { + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source: alreadyWritten.source + }; + } + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + continue; + } else { + throw new Error( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ); + } + } + if ( + this.cache && + this.cache[cacheName] && + this.cache[cacheName].hash === usedHash + ) { + source = this.cache[cacheName].source; + } else { + source = fileManifest.render(); + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source + }; + } + } + this.emitAsset(file, source, assetInfo); + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + } + } catch (err) { + this.errors.push( + new ChunkRenderError(chunk, file || filenameTemplate, err) + ); + } + } + } + + /** + * @param {string} filename used to get asset path with hash + * @param {TODO=} data // TODO: figure out this param type + * @returns {string} interpolated path + */ + getPath(filename, data) { + data = data || {}; + data.hash = data.hash || this.hash; + return this.mainTemplate.getAssetPath(filename, data); + } + + /** + * @param {string} filename used to get asset path with hash + * @param {TODO=} data // TODO: figure out this param type + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + */ + getPathWithInfo(filename, data) { + data = data || {}; + data.hash = data.hash || this.hash; + return this.mainTemplate.getAssetPathWithInfo(filename, data); + } + + /** + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * + * @param {string} name name of the child compiler + * @param {TODO} outputOptions // Need to convert config schema to types for this + * @param {Plugin[]} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance + */ + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); + } + + checkConstraints() { + /** @type {Set} */ + const usedIds = new Set(); + + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + const moduleId = modules[indexModule].id; + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); + } + usedIds.add(moduleId); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunks.indexOf(chunk) !== indexChunk) { + throw new Error( + `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` + ); + } + } + + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } + } +} + +// TODO remove in webpack 5 +Compilation.prototype.applyPlugins = util.deprecate( + /** + * @deprecated + * @param {string} name Name + * @param {any[]} args Other arguments + * @returns {void} + * @this {Compilation} + */ + function(name, ...args) { + this.hooks[ + name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase()) + ].call(...args); + }, + "Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead" +); + +// TODO remove in webpack 5 +Object.defineProperty(Compilation.prototype, "moduleTemplate", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {Compilation} + * @returns {TODO} module template + */ + function() { + return this.moduleTemplates.javascript; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead" + ), + set: util.deprecate( + /** + * @deprecated + * @param {ModuleTemplate} value Template value + * @this {Compilation} + * @returns {void} + */ + function(value) { + this.moduleTemplates.javascript = value; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead." + ) +}); + +module.exports = Compilation; + + +/***/ }), + +/***/ 58705: +/***/ ((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__(48335); +const asyncLib = __webpack_require__(36386); +const path = __webpack_require__(85622); +const { Source } = __webpack_require__(53665); +const util = __webpack_require__(31669); +const { + Tapable, + SyncHook, + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook +} = __webpack_require__(92402); + +const Compilation = __webpack_require__(34968); +const Stats = __webpack_require__(99977); +const Watching = __webpack_require__(29580); +const NormalModuleFactory = __webpack_require__(22298); +const ContextModuleFactory = __webpack_require__(88239); +const ResolverFactory = __webpack_require__(50588); + +const RequestShortener = __webpack_require__(54254); +const { makePathsRelative } = __webpack_require__(94658); +const ConcurrentCompilationError = __webpack_require__(18933); +const { Logger } = __webpack_require__(47194); + +/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ + +/** + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + * @property {Set} compilationDependencies + */ + +class Compiler extends Tapable { + constructor(context) { + super(); + this.hooks = { + /** @type {SyncBailHook} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {AsyncSeriesHook<>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + assetEmitted: new AsyncSeriesHook(["file", "content"]), + /** @type {AsyncSeriesHook} */ + afterEmit: new AsyncSeriesHook(["compilation"]), + + /** @type {SyncHook} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook} */ + contextModuleFactory: new SyncHook(["contextModulefactory"]), + + /** @type {AsyncSeriesHook} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + afterCompile: new AsyncSeriesHook(["compilation"]), + + /** @type {AsyncSeriesHook} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook} */ + watchClose: new SyncHook([]), + + /** @type {SyncBailHook} */ + infrastructureLog: new SyncBailHook(["origin", "type", "args"]), + + // 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} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook} */ + entryOption: new SyncBailHook(["context", "entry"]) + }; + // TODO webpack 5 remove this + this.hooks.infrastructurelog = this.hooks.infrastructureLog; + + this._pluginCompat.tap("Compiler", options => { + switch (options.name) { + case "additional-pass": + case "before-run": + case "run": + case "emit": + case "after-emit": + case "before-compile": + case "make": + case "after-compile": + case "watch-run": + options.async = true; + break; + } + }); + + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {string} */ + this.outputPath = ""; + + this.outputFileSystem = null; + this.inputFileSystem = null; + + /** @type {string|null} */ + this.recordsInputPath = null; + /** @type {string|null} */ + this.recordsOutputPath = null; + this.records = {}; + this.removedFiles = new Set(); + /** @type {Map} */ + this.fileTimestamps = new Map(); + /** @type {Map} */ + this.contextTimestamps = new Map(); + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); + + this.infrastructureLogger = undefined; + + // TODO remove in webpack 5 + this.resolvers = { + normal: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + loader: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + context: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.apply(/* … */);\n}); instead.') + } + }; + + /** @type {WebpackOptions} */ + this.options = /** @type {WebpackOptions} */ ({}); + + this.context = context; + + this.requestShortener = new RequestShortener(context); + + /** @type {boolean} */ + this.running = false; + + /** @type {boolean} */ + this.watchMode = false; + + /** @private @type {WeakMap }>} */ + this._assetEmittingSourceCache = new WeakMap(); + /** @private @type {Map} */ + this._assetEmittingWrittenFiles = new Map(); + } + + /** + * @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); + } + } + }); + } + + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); + + this.running = true; + this.watchMode = true; + this.fileTimestamps = new Map(); + this.contextTimestamps = new Map(); + this.removedFiles = new Set(); + return new Watching(this, watchOptions, handler); + } + + run(callback) { + if (this.running) return callback(new ConcurrentCompilationError()); + + const finalCallback = (err, stats) => { + this.running = false; + + if (err) { + this.hooks.failed.call(err); + } + + if (callback !== undefined) return callback(err, stats); + }; + + const startTime = Date.now(); + + this.running = true; + + const onCompiled = (err, compilation) => { + if (err) return finalCallback(err); + + if (this.hooks.shouldEmit.call(compilation) === false) { + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; + } + + this.emitAssets(compilation, err => { + if (err) return finalCallback(err); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + + this.hooks.additionalPass.callAsync(err => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } + + this.emitRecords(err => { + if (err) return finalCallback(err); + + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + }); + }); + }; + + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); + + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); + + this.readRecords(err => { + if (err) return finalCallback(err); + + this.compile(onCompiled); + }); + }); + }); + } + + runAsChild(callback) { + this.compile((err, compilation) => { + if (err) return callback(err); + + this.parentCompilation.children.push(compilation); + for (const { name, source, info } of compilation.getAssets()) { + this.parentCompilation.emitAsset(name, source, info); + } + + const entries = Array.from( + compilation.entrypoints.values(), + ep => ep.chunks + ).reduce((array, chunks) => { + return array.concat(chunks); + }, []); + + return callback(null, entries, compilation); + }); + } + + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); + } + } + + emitAssets(compilation, callback) { + let outputPath; + const emitFiles = err => { + if (err) return callback(err); + + asyncLib.forEachLimit( + compilation.getAssets(), + 15, + ({ name: file, source }, callback) => { + let targetFile = file; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + } + + const writeOut = err => { + if (err) return callback(err); + const targetPath = this.outputFileSystem.join( + outputPath, + targetFile + ); + // TODO webpack 5 remove futureEmitAssets option and make it on by default + if (this.options.output.futureEmitAssets) { + // 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); + } + + // 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 skip writing the file + // as it's already there + // (we assume one doesn't remove files while the Compiler is running) + + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: cacheEntry.sizeOnlySource.size() + }); + + return callback(); + } + } + + // TODO webpack 5: if info.immutable check if file already exists in output + // skip emitting if it's already there + + // get the binary (Buffer) content from the Source + /** @type {Buffer} */ + let content; + if (typeof source.buffer === "function") { + content = source.buffer(); + } else { + const bufferOrString = source.source(); + if (Buffer.isBuffer(bufferOrString)) { + content = bufferOrString; + } else { + content = Buffer.from(bufferOrString, "utf8"); + } + } + + // 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) + cacheEntry.sizeOnlySource = new SizeOnlySource(content.length); + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: content.length + }); + + // Write the file to output file system + 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, callback); + }); + } else { + if (source.existsAt === targetPath) { + source.emitted = false; + return callback(); + } + let content = source.source(); + + if (!Buffer.isBuffer(content)) { + content = Buffer.from(content, "utf8"); + } + + source.existsAt = targetPath; + source.emitted = true; + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); + this.hooks.assetEmitted.callAsync(file, content, callback); + }); + } + }; + + if (targetFile.match(/\/|\\/)) { + const dir = path.dirname(targetFile); + this.outputFileSystem.mkdirp( + this.outputFileSystem.join(outputPath, dir), + writeOut + ); + } else { + writeOut(); + } + }, + err => { + if (err) return callback(err); + + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(); + }); + } + ); + }; + + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath); + this.outputFileSystem.mkdirp(outputPath, emitFiles); + }); + } + + emitRecords(callback) { + if (!this.recordsOutputPath) return callback(); + const idx1 = this.recordsOutputPath.lastIndexOf("/"); + const idx2 = this.recordsOutputPath.lastIndexOf("\\"); + let recordsOutputPathDirectory = null; + if (idx1 > idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); + } else if (idx1 < idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); + } + + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify(this.records, undefined, 2), + callback + ); + }; + + if (!recordsOutputPathDirectory) { + return writeFile(); + } + this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); + } + + readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); + } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); + + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); + + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } + + return callback(); + }); + }); + } + + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context); + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); + } + } + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) + ) { + if (childCompiler.hooks[name]) { + childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + } + } + } + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; + + const relativeCompilerName = makePathsRelative(this.context, compilerName); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; + } + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); + } + + childCompiler.options = Object.create(this.options); + childCompiler.options.output = Object.create(childCompiler.options.output); + for (const name in outputOptions) { + childCompiler.options.output[name] = outputOptions[name]; + } + childCompiler.parentCompilation = compilation; + + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); + + return childCompiler; + } + + isChild() { + return !!this.parentCompilation; + } + + createCompilation() { + return new Compilation(this); + } + + newCompilation(params) { + const compilation = this.createCompilation(); + compilation.fileTimestamps = this.fileTimestamps; + compilation.contextTimestamps = this.contextTimestamps; + compilation.name = this.name; + compilation.records = this.records; + compilation.compilationDependencies = params.compilationDependencies; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; + } + + createNormalModuleFactory() { + const normalModuleFactory = new NormalModuleFactory( + this.options.context, + this.resolverFactory, + this.options.module || {} + ); + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; + } + + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; + } + + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory(), + compilationDependencies: new Set() + }; + return params; + } + + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); + + this.hooks.compile.call(params); + + const compilation = this.newCompilation(params); + + this.hooks.make.callAsync(compilation, err => { + if (err) return callback(err); + + compilation.finish(err => { + if (err) return callback(err); + + compilation.seal(err => { + if (err) return callback(err); + + this.hooks.afterCompile.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(null, compilation); + }); + }); + }); + }); + }); + } +} + +module.exports = Compiler; + +class SizeOnlySource extends Source { + constructor(size) { + super(); + this._size = size; + } + + _error() { + return new Error( + "Content and Map of this Source is no longer available (only size() is supported)" + ); + } + + size() { + return this._size; + } + + /** + * @param {any} options options + * @returns {string} the source + */ + source(options) { + throw this._error(); + } + + node() { + throw this._error(); + } + + listMap() { + throw this._error(); + } + + map() { + throw this._error(); + } + + listNode() { + throw this._error(); + } + + updateHash() { + throw this._error(); + } +} + + +/***/ }), + +/***/ 18933: +/***/ ((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__(97391); + +module.exports = class ConcurrentCompilationError extends WebpackError { + constructor() { + super(); + + this.name = "ConcurrentCompilationError"; + this.message = + "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 84072: +/***/ ((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__(71101); +const NullFactory = __webpack_require__(40438); +const ParserHelpers = __webpack_require__(23999); + +const getQuery = request => { + const i = request.indexOf("?"); + return i !== -1 ? request.substr(i) : ""; +}; + +const collectDeclaration = (declarations, pattern) => { + const stack = [pattern]; + while (stack.length > 0) { + const node = stack.pop(); + switch (node.type) { + case "Identifier": + declarations.add(node.name); + break; + case "ArrayPattern": + for (const element of node.elements) { + if (element) { + stack.push(element); + } + } + break; + case "AssignmentPattern": + stack.push(node.left); + break; + case "ObjectPattern": + for (const property of node.properties) { + stack.push(property.value); + } + break; + case "RestElement": + stack.push(node.argument); + break; + } + } +}; + +const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { + const declarations = new Set(); + const stack = [branch]; + while (stack.length > 0) { + const node = stack.pop(); + // Some node could be `null` or `undefined`. + if (!node) continue; + switch (node.type) { + // Walk through control statements to look for hoisted declarations. + // Some branches are skipped since they do not allow declarations. + case "BlockStatement": + for (const stmt of node.body) { + stack.push(stmt); + } + break; + case "IfStatement": + stack.push(node.consequent); + stack.push(node.alternate); + break; + case "ForStatement": + stack.push(node.init); + stack.push(node.body); + break; + case "ForInStatement": + case "ForOfStatement": + stack.push(node.left); + stack.push(node.body); + break; + case "DoWhileStatement": + case "WhileStatement": + case "LabeledStatement": + stack.push(node.body); + break; + case "SwitchStatement": + for (const cs of node.cases) { + for (const consequent of cs.consequent) { + stack.push(consequent); + } + } + break; + case "TryStatement": + stack.push(node.block); + if (node.handler) { + stack.push(node.handler.body); + } + stack.push(node.finalizer); + break; + case "FunctionDeclaration": + if (includeFunctionDeclarations) { + collectDeclaration(declarations, node.id); + } + break; + case "VariableDeclaration": + if (node.kind === "var") { + for (const decl of node.declarations) { + collectDeclaration(declarations, decl.id); + } + } + break; + } + } + return Array.from(declarations); +}; + +class ConstPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ConstPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = parser => { + parser.hooks.statementIf.tap("ConstPlugin", statement => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(statement.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (statement.test.type !== "Literal") { + const dep = new ConstDependency(`${bool}`, param.range); + dep.loc = statement.loc; + parser.state.current.addDependency(dep); + } + const branchToRemove = bool + ? statement.alternate + : statement.consequent; + if (branchToRemove) { + // Before removing the dead branch, the hoisted declarations + // must be collected. + // + // Given the following code: + // + // if (true) f() else g() + // if (false) { + // function f() {} + // const g = function g() {} + // if (someTest) { + // let a = 1 + // var x, {y, z} = obj + // } + // } else { + // … + // } + // + // the generated code is: + // + // if (true) f() else {} + // if (false) { + // var f, x, y, z; (in loose mode) + // var x, y, z; (in strict mode) + // } else { + // … + // } + // + // NOTE: When code runs in strict mode, `var` declarations + // are hoisted but `function` declarations don't. + // + let declarations; + if (parser.scope.isStrict) { + // If the code runs in strict mode, variable declarations + // using `var` must be hoisted. + declarations = getHoistedDeclarations(branchToRemove, false); + } else { + // Otherwise, collect all hoisted declaration. + declarations = getHoistedDeclarations(branchToRemove, true); + } + let replacement; + if (declarations.length > 0) { + replacement = `{ var ${declarations.join(", ")}; }`; + } else { + replacement = "{}"; + } + const dep = new ConstDependency( + replacement, + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + } + return bool; + } + }); + parser.hooks.expressionConditionalOperator.tap( + "ConstPlugin", + expression => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(expression.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (expression.test.type !== "Literal") { + const dep = new ConstDependency(` ${bool}`, param.range); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // Given the following code: + // + // false ? someExpression() : otherExpression(); + // + // the generated code is: + // + // false ? undefined : otherExpression(); + // + const branchToRemove = bool + ? expression.alternate + : expression.consequent; + const dep = new ConstDependency( + "undefined", + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + return bool; + } + } + ); + parser.hooks.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.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.current.addDependency(dep); + } else { + parser.walkExpression(expression.left); + } + if (!keepRight) { + const dep = new ConstDependency( + "false", + expression.right.range + ); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } + return keepRight; + } + } + } + ); + parser.hooks.evaluateIdentifier + .for("__resourceQuery") + .tap("ConstPlugin", expr => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + getQuery(parser.state.module.resource) + )(expr); + }); + parser.hooks.expression + .for("__resourceQuery") + .tap("ConstPlugin", () => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + parser.state.current.addVariable( + "__resourceQuery", + JSON.stringify(getQuery(parser.state.module.resource)) + ); + return true; + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ConstPlugin", handler); + } + ); + } +} + +module.exports = ConstPlugin; + + +/***/ }), + +/***/ 10706: +/***/ ((module) => { + +"use strict"; + + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ + +class ContextExclusionPlugin { + /** + * @param {RegExp} negativeMatcher Matcher regular expression + */ + constructor(negativeMatcher) { + this.negativeMatcher = negativeMatcher; + } + + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => { + cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => { + return files.filter(filePath => !this.negativeMatcher.test(filePath)); + }); + }); + } +} + +module.exports = ContextExclusionPlugin; + + +/***/ }), + +/***/ 20090: +/***/ ((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__(31669); +const { OriginalSource, RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); +const AsyncDependenciesBlock = __webpack_require__(22814); +const Template = __webpack_require__(96066); +const contextify = __webpack_require__(94658).contextify; + +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ + +/** + * @callback ResolveDependenciesCallback + * @param {Error=} err + * @param {ContextElementDependency[]} dependencies + */ + +/** + * @callback ResolveDependencies + * @param {TODO} fs + * @param {TODO} options + * @param {ResolveDependenciesCallback} callback + */ + +class ContextModule extends Module { + // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once" + // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp, groupOptions?: Object } + // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void + // options: ContextOptions + /** + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {TODO} options options object + */ + constructor(resolveDependencies, options) { + let resource; + let resourceQuery; + const queryIdx = options.resource.indexOf("?"); + if (queryIdx >= 0) { + resource = options.resource.substr(0, queryIdx); + resourceQuery = options.resource.substr(queryIdx); + } else { + resource = options.resource; + resourceQuery = ""; + } + + super("javascript/dynamic", resource); + + // Info from Factory + this.resolveDependencies = resolveDependencies; + this.options = Object.assign({}, options, { + resource: resource, + resourceQuery: resourceQuery + }); + if (options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; + } + + // Info from Build + this._contextDependencies = new Set([this.context]); + + if (typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); + } + + this._identifier = this._createIdentifier(); + } + + updateCacheModule(module) { + this.resolveDependencies = module.resolveDependencies; + this.options = module.options; + this.resolveOptions = module.resolveOptions; + } + + prettyRegExp(regexString) { + // remove the "/" at the front and the beginning + // "/foo/" -> "foo" + return regexString.substring(1, regexString.length - 1); + } + + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${this.options.addon}`; + } + if (this.options.regExp) { + identifier += ` ${this.options.regExp}`; + } + if (this.options.include) { + identifier += ` include: ${this.options.include}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.options.exclude}`; + } + if (this.options.groupOptions) { + identifier += ` groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context); + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${groupOptions[key]}`; + } + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; + } + + libIdent(options) { + let identifier = contextify(options.context, this.context); + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { + identifier += ` ${contextify(options.context, this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } + + return identifier; + } + + needRebuild(fileTimestamps, contextTimestamps) { + const ts = contextTimestamps.get(this.context); + if (!ts) { + return true; + } + + return ts >= this.buildInfo.builtTime; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + builtTime: Date.now(), + contextDependencies: this._contextDependencies + }; + this.resolveDependencies(fs, this.options, (err, dependencies) => { + if (err) return callback(err); + + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } + + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: this.options.chunkName + }), + this + ); + for (const dep of dependencies) { + block.addDependency(dep); + } + this.addBlock(block); + } + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; + } + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } + chunkName = chunkName.replace(/\[index\]/g, index++); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); + } + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: chunkName + }), + dep.module, + dep.loc, + dep.userRequest + ); + block.addDependency(dep); + this.addBlock(block); + } + } else { + callback( + new Error(`Unsupported mode "${this.options.mode}" in context`) + ); + return; + } + callback(); + }); + } + + getUserRequestMap(dependencies) { + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + return dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, dep) => { + map[dep.userRequest] = dep.module.id; + return map; + }, Object.create(null)); + } + + getFakeMap(dependencies) { + if (!this.options.namespaceObject) { + return 9; + } + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + let hasNonHarmony = false; + let hasNamespace = false; + let hasNamed = false; + const fakeMap = dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + return b.module.id - a.module.id; + }) + .reduce((map, dep) => { + const exportsType = + dep.module.buildMeta && dep.module.buildMeta.exportsType; + const id = dep.module.id; + if (!exportsType) { + map[id] = this.options.namespaceObject === "strict" ? 1 : 7; + hasNonHarmony = true; + } else if (exportsType === "namespace") { + map[id] = 9; + hasNamespace = true; + } else if (exportsType === "named") { + map[id] = 3; + hasNamed = true; + } + return map; + }, Object.create(null)); + if (!hasNamespace && hasNonHarmony && !hasNamed) { + return this.options.namespaceObject === "strict" ? 1 : 7; + } + if (hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + if (!hasNamespace && !hasNonHarmony && hasNamed) { + return 3; + } + if (!hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + return fakeMap; + } + + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; + } + + getReturn(type) { + if (type === 9) { + return "__webpack_require__(id)"; + } + return `__webpack_require__.t(id, ${type})`; + } + + getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap)};`; + } + return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; + } + + getSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!__webpack_require__.o(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)};`; + } + + getWeakSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!__webpack_require__.o(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;`; + } + + getAsyncWeakSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(function(id) { + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getEagerSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)} + }` + : "__webpack_require__"; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getLazyOnceSource(block, dependencies, id, runtimeTemplate) { + const promise = runtimeTemplate.blockPromise({ + block, + message: "lazy-once context" + }); + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)}; + }` + : "__webpack_require__"; + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getLazySource(blocks, id) { + let hasMultipleOrNoChunks = false; + let hasNoChunk = true; + const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0])); + const hasFakeMap = typeof fakeMap === "object"; + const map = blocks + .filter(block => block.dependencies[0].module) + .map(block => { + const chunks = block.chunkGroup ? block.chunkGroup.chunks : []; + if (chunks.length > 0) { + hasNoChunk = false; + } + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; + } + return { + dependency: block.dependencies[0], + block: block, + userRequest: block.dependencies[0].userRequest, + chunks + }; + }) + .sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, item) => { + const chunks = item.chunks; + + if (hasNoChunk && !hasFakeMap) { + map[item.userRequest] = item.dependency.module.id; + } else { + const arrayStart = [item.dependency.module.id]; + if (typeof fakeMap === "object") { + arrayStart.push(fakeMap[item.dependency.module.id]); + } + map[item.userRequest] = arrayStart.concat( + chunks.map(chunk => chunk.id) + ); + } + + return map; + }, Object.create(null)); + + const shortMode = hasNoChunk && !hasFakeMap; + const chunksStartPosition = hasFakeMap ? 2 : 1; + const requestPrefix = hasNoChunk + ? "Promise.resolve()" + : hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))` + : `__webpack_require__.e(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + shortMode ? "invalid" : "ids[1]" + ); + + const webpackAsyncContext = + requestPrefix === "Promise.resolve()" + ? `${shortMode ? "" : ""} +function webpackAsyncContext(req) { + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + + ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} + ${returnModuleObject} + }); +}` + : `function webpackAsyncContext(req) { + if(!__webpack_require__.o(map, req)) { + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); + } + + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(function() { + ${returnModuleObject} + }); +}`; + + return `var map = ${JSON.stringify(map, null, "\t")}; +${webpackAsyncContext} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getSourceForEmptyContext(id) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = function() { return []; }; +webpackEmptyContext.resolve = webpackEmptyContext; +module.exports = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)};`; + } + + getSourceForEmptyAsyncContext(id) { + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = function() { return []; }; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +module.exports = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; + } + + getSourceString(asyncMode, runtimeTemplate) { + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource( + block, + block.dependencies, + this.id, + runtimeTemplate + ); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getWeakSyncSource(this.dependencies, this.id); + } + } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, this.id); + } + return this.getSourceForEmptyContext(this.id); + } + + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + return new RawSource(sourceString); + } + + source(dependencyTemplates, runtimeTemplate) { + return this.getSource( + this.getSourceString(this.options.mode, runtimeTemplate) + ); + } + + size() { + // base penalty + const initialSize = 160; + + // if we dont have dependencies we stop here. + return this.dependencies.reduce((size, dependency) => { + const element = /** @type {ContextElementDependency} */ (dependency); + return size + 5 + element.userRequest.length; + }, initialSize); + } +} + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "recursive", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is recursive + */ + function() { + return this.options.recursive; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {boolean} value is recursive + * @returns {void} + */ + function(value) { + this.options.recursive = value; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "regExp", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {RegExp} regular expression + */ + function() { + return this.options.regExp; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {RegExp} value Regular expression + * @returns {void} + */ + function(value) { + this.options.regExp = value; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "addon", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} addon + */ + function() { + return this.options.addon; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value addon + * @returns {void} + */ + function(value) { + this.options.addon = value; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "async", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is async + */ + function() { + return this.options.mode; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {ContextMode} value Context mode + * @returns {void} + */ + function(value) { + this.options.mode = value; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "chunkName", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} chunk name + */ + function() { + return this.options.chunkName; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value chunk name + * @returns {void} + */ + function(value) { + this.options.chunkName = value; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ) +}); + +module.exports = ContextModule; + + +/***/ }), + +/***/ 88239: +/***/ ((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__(36386); +const path = __webpack_require__(85622); + +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook +} = __webpack_require__(92402); +const ContextModule = __webpack_require__(20090); +const ContextElementDependency = __webpack_require__(89079); + +/** @typedef {import("./Module")} Module */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +module.exports = class ContextModuleFactory extends Tapable { + constructor(resolverFactory) { + super(); + this.hooks = { + /** @type {AsyncSeriesWaterfallHook} */ + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {AsyncSeriesWaterfallHook} */ + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {SyncWaterfallHook} */ + contextModuleFiles: new SyncWaterfallHook(["files"]), + /** @type {SyncWaterfallHook} */ + alternatives: new AsyncSeriesWaterfallHook(["modules"]) + }; + this._pluginCompat.tap("ContextModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + case "alternatives": + options.async = true; + break; + } + }); + this.resolverFactory = resolverFactory; + } + + create(data, callback) { + const context = data.context; + const dependencies = data.dependencies; + const resolveOptions = data.resolveOptions; + const dependency = dependencies[0]; + this.hooks.beforeResolve.callAsync( + Object.assign( + { + context: context, + dependencies: dependencies, + resolveOptions + }, + dependency.options + ), + (err, beforeResolveResult) => { + if (err) return callback(err); + + // Ignored + if (!beforeResolveResult) return callback(); + + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; + + let loaders, + resource, + loadersPrefix = ""; + const idx = request.lastIndexOf("!"); + if (idx >= 0) { + let loadersRequest = request.substr(0, idx + 1); + let i; + for ( + i = 0; + i < loadersRequest.length && loadersRequest[i] === "!"; + i++ + ) { + loadersPrefix += "!"; + } + loadersRequest = loadersRequest + .substr(i) + .replace(/!+$/, "") + .replace(/!!+/g, "!"); + if (loadersRequest === "") { + loaders = []; + } else { + loaders = loadersRequest.split("!"); + } + resource = request.substr(idx + 1); + } else { + loaders = []; + resource = request; + } + + const contextResolver = this.resolverFactory.get( + "context", + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + const loaderResolver = this.resolverFactory.get( + "loader", + EMPTY_RESOLVE_OPTIONS + ); + + asyncLib.parallel( + [ + callback => { + contextResolver.resolve( + {}, + context, + resource, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); + } + ); + }, + callback => { + asyncLib.map( + loaders, + (loader, callback) => { + loaderResolver.resolve( + {}, + context, + loader, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); + } + ); + }, + callback + ); + } + ], + (err, result) => { + if (err) return callback(err); + + this.hooks.afterResolve.callAsync( + Object.assign( + { + addon: + loadersPrefix + + result[1].join("!") + + (result[1].length > 0 ? "!" : ""), + resource: result[0], + resolveDependencies: this.resolveDependencies.bind(this) + }, + beforeResolveResult + ), + (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + return callback( + null, + new ContextModule(result.resolveDependencies, result) + ); + } + ); + } + ); + } + ); + } + + resolveDependencies(fs, options, callback) { + const cmf = this; + let resource = options.resource; + let resourceQuery = options.resourceQuery; + let recursive = options.recursive; + let regExp = options.regExp; + let include = options.include; + let exclude = options.exclude; + if (!regExp || !resource) return callback(null, []); + + const addDirectory = (directory, callback) => { + fs.readdir(directory, (err, files) => { + if (err) return callback(err); + files = cmf.hooks.contextModuleFiles.call(files); + if (!files || files.length === 0) return callback(null, []); + asyncLib.map( + files.filter(p => p.indexOf(".") !== 0), + (segment, callback) => { + const subResource = path.join(directory, segment); + + if (!exclude || !subResource.match(exclude)) { + fs.stat(subResource, (err, stat) => { + if (err) { + if (err.code === "ENOENT") { + // ENOENT is ok here because the file may have been deleted between + // the readdir and stat calls. + return callback(); + } else { + return callback(err); + } + } + + if (stat.isDirectory()) { + if (!recursive) return callback(); + addDirectory.call(this, subResource, callback); + } else if ( + stat.isFile() && + (!include || subResource.match(include)) + ) { + const obj = { + context: resource, + request: + "." + + subResource.substr(resource.length).replace(/\\/g, "/") + }; + + this.hooks.alternatives.callAsync( + [obj], + (err, alternatives) => { + if (err) return callback(err); + alternatives = alternatives + .filter(obj => regExp.test(obj.request)) + .map(obj => { + const dep = new ContextElementDependency( + obj.request + resourceQuery, + obj.request + ); + dep.optional = true; + return dep; + }); + callback(null, alternatives); + } + ); + } else { + callback(); + } + }); + } else { + callback(); + } + }, + (err, result) => { + if (err) return callback(err); + + if (!result) return callback(null, []); + + callback( + null, + result.filter(Boolean).reduce((a, i) => a.concat(i), []) + ); + } + ); + }); + }; + + addDirectory(resource, callback); + } +}; + + +/***/ }), + +/***/ 27295: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const ContextElementDependency = __webpack_require__(89079); + +class ContextReplacementPlugin { + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; + + if (typeof newContentResource === "function") { + this.newContentCallback = newContentResource; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "object" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = (fs, callback) => { + callback(null, newContentRecursive); + }; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "function" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = newContentRecursive; + } else { + if (typeof newContentResource !== "string") { + newContentRegExp = newContentRecursive; + newContentRecursive = newContentResource; + newContentResource = undefined; + } + if (typeof newContentRecursive !== "boolean") { + newContentRegExp = newContentRecursive; + newContentRecursive = undefined; + } + this.newContentResource = newContentResource; + this.newContentRecursive = newContentRecursive; + this.newContentRegExp = newContentRegExp; + } + } + + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newContentCallback = this.newContentCallback; + const newContentResource = this.newContentResource; + const newContentRecursive = this.newContentRecursive; + const newContentRegExp = this.newContentRegExp; + const newContentCreateContextMap = this.newContentCreateContextMap; + + compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => { + cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (newContentResource !== undefined) { + result.request = newContentResource; + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCallback === "function") { + newContentCallback(result); + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (newContentResource !== undefined) { + result.resource = path.resolve(result.resource, newContentResource); + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCreateContextMap === "function") { + result.resolveDependencies = createResolveDependenciesFromContextMap( + newContentCreateContextMap + ); + } + if (typeof newContentCallback === "function") { + const origResource = result.resource; + newContentCallback(result); + if (result.resource !== origResource) { + result.resource = path.resolve(origResource, result.resource); + } + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + }); + } +} + +const createResolveDependenciesFromContextMap = createContextMap => { + const resolveDependenciesFromContextMap = (fs, options, callback) => { + createContextMap(fs, (err, map) => { + if (err) return callback(err); + const dependencies = Object.keys(map).map(key => { + return new ContextElementDependency( + map[key] + options.resourceQuery, + key + ); + }); + callback(null, dependencies); + }); + }; + return resolveDependenciesFromContextMap; +}; + +module.exports = ContextReplacementPlugin; + + +/***/ }), + +/***/ 97374: +/***/ ((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__(71101); +const BasicEvaluatedExpression = __webpack_require__(96770); +const ParserHelpers = __webpack_require__(23999); +const NullFactory = __webpack_require__(40438); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ +/** @typedef {CodeValuePrimitive|Record|RuntimeValue} CodeValue */ + +class RuntimeValue { + constructor(fn, fileDependencies) { + this.fn = fn; + this.fileDependencies = fileDependencies || []; + } + + exec(parser) { + if (this.fileDependencies === true) { + parser.state.module.buildInfo.cacheable = false; + } else { + for (const fileDependency of this.fileDependencies) { + parser.state.module.buildInfo.fileDependencies.add(fileDependency); + } + } + + return this.fn({ module: parser.state.module }); + } +} + +const stringifyObj = (obj, parser) => { + return ( + "Object({" + + Object.keys(obj) + .map(key => { + const code = obj[key]; + return JSON.stringify(key) + ":" + toCode(code, parser); + }) + .join(",") + + "})" + ); +}; + +/** + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {Parser} parser Parser + * @returns {string} code converted to string that evaluates + */ +const toCode = (code, parser) => { + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (code instanceof RuntimeValue) { + return toCode(code.exec(parser), parser); + } + if (code instanceof RegExp && code.toString) { + return code.toString(); + } + if (typeof code === "function" && code.toString) { + return "(" + code.toString() + ")"; + } + if (typeof code === "object") { + return stringifyObj(code, parser); + } + return code + ""; +}; + +class DefinePlugin { + /** + * Create a new define plugin + * @param {Record} definitions A map of global object definitions + */ + constructor(definitions) { + this.definitions = definitions; + } + + static runtimeValue(fn, fileDependencies) { + return new RuntimeValue(fn, fileDependencies); + } + + /** + * Apply the plugin + * @param {Compiler} compiler Webpack compiler + * @returns {void} + */ + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "DefinePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + /** + * Handler + * @param {Parser} parser Parser + * @returns {void} + */ + const handler = parser => { + /** + * Walk definitions + * @param {Object} definitions Definitions map + * @param {string} prefix Prefix string + * @returns {void} + */ + const walkDefinitions = (definitions, prefix) => { + Object.keys(definitions).forEach(key => { + const code = definitions[key]; + if ( + code && + typeof code === "object" && + !(code instanceof RuntimeValue) && + !(code instanceof RegExp) + ) { + walkDefinitions(code, prefix + key + "."); + applyObjectDefine(prefix + key, code); + return; + } + applyDefineKey(prefix, key); + applyDefine(prefix + key, code); + }); + }; + + /** + * Apply define key + * @param {string} prefix Prefix + * @param {string} key Key + * @returns {void} + */ + const applyDefineKey = (prefix, key) => { + const splittedKey = key.split("."); + splittedKey.slice(1).forEach((_, i) => { + const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(fullKey) + .tap("DefinePlugin", ParserHelpers.approve); + }); + }; + + /** + * Apply Code + * @param {string} key Key + * @param {CodeValue} code Code + * @returns {void} + */ + const applyDefine = (key, code) => { + const isTypeof = /^typeof\s+/.test(key); + if (isTypeof) key = key.replace(/^typeof\s+/, ""); + let recurse = false; + let recurseTypeof = false; + if (!isTypeof) { + parser.hooks.canRename + .for(key) + .tap("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", expr => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "a": "b", + * "b": "a" + * }); + */ + if (recurse) return; + recurse = true; + const res = parser.evaluate(toCode(code, parser)); + recurse = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = toCode(code, parser); + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency( + parser, + strCode + )(expr); + } + }); + } + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "typeof a": "typeof b", + * "typeof b": "typeof a" + * }); + */ + if (recurseTypeof) return; + recurseTypeof = true; + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + recurseTypeof = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + if (!res.isString()) return; + return ParserHelpers.toConstantDependency( + parser, + JSON.stringify(res.string) + ).bind(parser)(expr); + }); + }; + + /** + * Apply Object + * @param {string} key Key + * @param {Object} obj Object + * @returns {void} + */ + const applyObjectDefine = (key, obj) => { + parser.hooks.canRename + .for(key) + .tap("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", expr => + new BasicEvaluatedExpression().setTruthy().setRange(expr.range) + ); + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.evaluateToString("object")(expr); + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = stringifyObj(obj, parser); + + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency( + parser, + strCode + )(expr); + } + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") + )(expr); + }); + }; + + walkDefinitions(definitions, ""); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("DefinePlugin", handler); + } + ); + } +} +module.exports = DefinePlugin; + + +/***/ }), + +/***/ 42173: +/***/ ((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__(53665); + +const Module = __webpack_require__(75993); +const WebpackMissingModule = __webpack_require__(75386); +const DelegatedSourceDependency = __webpack_require__(25930); +const DelegatedExportsDependency = __webpack_require__(53104); + +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DelegatedModule extends Module { + constructor(sourceRequest, data, type, userRequest, originalRequest) { + super("javascript/dynamic", null); + + // Info from Factory + this.sourceRequest = sourceRequest; + this.request = data.id; + this.type = type; + this.userRequest = userRequest; + this.originalRequest = originalRequest; + this.delegateData = data; + + // Build info + this.delegatedSourceDependency = undefined; + } + + libIdent(options) { + return typeof this.originalRequest === "string" + ? this.originalRequest + : this.originalRequest.libIdent(options); + } + + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; + } + + readableIdentifier() { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; + } + + needRebuild() { + return false; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = Object.assign({}, this.delegateData.buildMeta); + this.buildInfo = {}; + this.delegatedSourceDependency = new DelegatedSourceDependency( + this.sourceRequest + ); + this.addDependency(this.delegatedSourceDependency); + this.addDependency( + new DelegatedExportsDependency(this, this.delegateData.exports || true) + ); + callback(); + } + + source(depTemplates, runtime) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = dep.module; + let str; + + if (!sourceModule) { + str = WebpackMissingModule.moduleCode(this.sourceRequest); + } else { + str = `module.exports = (${runtime.moduleExports({ + module: sourceModule, + request: dep.request + })})`; + + switch (this.type) { + case "require": + str += `(${JSON.stringify(this.request)})`; + break; + case "object": + str += `[${JSON.stringify(this.request)}]`; + break; + } + + str += ";"; + } + + if (this.useSourceMap) { + return new OriginalSource(str, this.identifier()); + } else { + return new RawSource(str); + } + } + + size() { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this.type); + hash.update(JSON.stringify(this.request)); + super.updateHash(hash); + } +} + +module.exports = DelegatedModule; + + +/***/ }), + +/***/ 81002: +/***/ ((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__(42173); + +// options.source +// options.type +// options.context +// options.scope +// options.content +class DelegatedModuleFactoryPlugin { + constructor(options) { + this.options = options; + options.type = options.type || "require"; + options.extensions = options.extensions || [ + "", + ".wasm", + ".mjs", + ".js", + ".json" + ]; + } + + apply(normalModuleFactory) { + const scope = this.options.scope; + if (scope) { + normalModuleFactory.hooks.factory.tap( + "DelegatedModuleFactoryPlugin", + factory => (data, callback) => { + const dependency = data.dependencies[0]; + const request = dependency.request; + if (request && request.indexOf(scope + "/") === 0) { + const innerRequest = "." + request.substr(scope.length); + let resolved; + if (innerRequest in this.options.content) { + resolved = this.options.content[innerRequest]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + this.options.type, + innerRequest, + request + ) + ); + } + for (let i = 0; i < this.options.extensions.length; i++) { + const extension = this.options.extensions[i]; + const requestPlusExt = innerRequest + extension; + if (requestPlusExt in this.options.content) { + resolved = this.options.content[requestPlusExt]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + this.options.type, + requestPlusExt, + request + extension + ) + ); + } + } + } + return factory(data, callback); + } + ); + } else { + normalModuleFactory.hooks.module.tap( + "DelegatedModuleFactoryPlugin", + module => { + if (module.libIdent) { + const request = module.libIdent(this.options); + if (request && request in this.options.content) { + const resolved = this.options.content[request]; + return new DelegatedModule( + this.options.source, + resolved, + this.options.type, + request, + module + ); + } + } + return module; + } + ); + } + } +} +module.exports = DelegatedModuleFactoryPlugin; + + +/***/ }), + +/***/ 16071: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + +const DependenciesBlockVariable = __webpack_require__(82904); + +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DependenciesBlock { + constructor() { + /** @type {Dependency[]} */ + this.dependencies = []; + /** @type {AsyncDependenciesBlock[]} */ + this.blocks = []; + /** @type {DependenciesBlockVariable[]} */ + this.variables = []; + } + + /** + * Adds a DependencyBlock to DependencyBlock relationship. + * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) + * + * @param {AsyncDependenciesBlock} block block being added + * @returns {void} + */ + addBlock(block) { + this.blocks.push(block); + block.parent = this; + } + + /** + * @param {string} name name of dependency + * @param {string} expression expression string for variable + * @param {Dependency[]} dependencies dependency instances tied to variable + * @returns {void} + */ + addVariable(name, expression, dependencies) { + for (let v of this.variables) { + if (v.name === name && v.expression === expression) { + return; + } + } + this.variables.push( + new DependenciesBlockVariable(name, expression, dependencies) + ); + } + + /** + * @param {Dependency} dependency dependency being tied to block. + * This is an "edge" pointing to another "node" on module graph. + * @returns {void} + */ + addDependency(dependency) { + this.dependencies.push(dependency); + } + + /** + * @param {Dependency} dependency dependency being removed + * @returns {void} + */ + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); + } + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + for (const dep of this.dependencies) dep.updateHash(hash); + for (const block of this.blocks) block.updateHash(hash); + for (const variable of this.variables) variable.updateHash(hash); + } + + disconnect() { + for (const dep of this.dependencies) dep.disconnect(); + for (const block of this.blocks) block.disconnect(); + for (const variable of this.variables) variable.disconnect(); + } + + unseal() { + for (const block of this.blocks) block.unseal(); + } + + /** + * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance + * @returns {boolean} returns boolean for filter + */ + hasDependencies(filter) { + if (filter) { + for (const dep of this.dependencies) { + if (filter(dep)) return true; + } + } else { + if (this.dependencies.length > 0) { + return true; + } + } + + for (const block of this.blocks) { + if (block.hasDependencies(filter)) return true; + } + for (const variable of this.variables) { + if (variable.hasDependencies(filter)) return true; + } + return false; + } + + sortItems() { + for (const block of this.blocks) block.sortItems(); + } +} + +module.exports = DependenciesBlock; + + +/***/ }), + +/***/ 82904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { RawSource, ReplaceSource } = __webpack_require__(53665); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {Map} DependencyTemplates */ + +class DependenciesBlockVariable { + /** + * Creates an instance of DependenciesBlockVariable. + * @param {string} name name of DependenciesBlockVariable + * @param {string} expression expression string + * @param {Dependency[]=} dependencies dependencies tied to this varaiable + */ + constructor(name, expression, dependencies) { + this.name = name; + this.expression = expression; + this.dependencies = dependencies || []; + } + + /** + * @param {Hash} hash hash for instance to update + * @returns {void} + */ + updateHash(hash) { + hash.update(this.name); + hash.update(this.expression); + for (const d of this.dependencies) { + d.updateHash(hash); + } + } + + /** + * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map. + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce + * @returns {ReplaceSource} returns constructed source for expression via templates + */ + expressionSource(dependencyTemplates, runtimeTemplate) { + const source = new ReplaceSource(new RawSource(this.expression)); + for (const dep of this.dependencies) { + const template = dependencyTemplates.get(dep.constructor); + if (!template) { + throw new Error(`No template for dependency: ${dep.constructor.name}`); + } + template.apply(dep, source, runtimeTemplate, dependencyTemplates); + } + return source; + } + + disconnect() { + for (const d of this.dependencies) { + d.disconnect(); + } + } + + hasDependencies(filter) { + if (filter) { + return this.dependencies.some(filter); + } + return this.dependencies.length > 0; + } +} + +module.exports = DependenciesBlockVariable; + + +/***/ }), + +/***/ 57282: +/***/ ((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__(31669); +const compareLocations = __webpack_require__(22562); +const DependencyReference = __webpack_require__(71722); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ + +/** + * @typedef {Object} DependencyTemplate + * @property {function(Dependency, Source, RuntimeTemplate, Map): void} apply + */ + +/** @typedef {Object} SourcePosition + * @property {number} line + * @property {number=} column + */ + +/** @typedef {Object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ + +/** @typedef {Object} SynteticDependencyLocation + * @property {string} name + * @property {number=} index + */ + +/** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ + +class Dependency { + constructor() { + /** @type {Module|null} */ + this.module = null; + // TODO remove in webpack 5 + /** @type {boolean} */ + this.weak = false; + /** @type {boolean} */ + this.optional = false; + /** @type {DependencyLocation} */ + this.loc = undefined; + } + + getResourceIdentifier() { + return null; + } + + // Returns the referenced module and export + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, true, this.weak); + } + + // Returns the exported names + getExports() { + return null; + } + + getWarnings() { + return null; + } + + getErrors() { + return null; + } + + updateHash(hash) { + hash.update((this.module && this.module.id) + ""); + } + + disconnect() { + this.module = null; + } +} + +// TODO remove in webpack 5 +Dependency.compare = util.deprecate( + (a, b) => compareLocations(a.loc, b.loc), + "Dependency.compare is deprecated and will be removed in the next major version" +); + +module.exports = Dependency; + + +/***/ }), + +/***/ 6659: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DllEntryDependency = __webpack_require__(66279); +const SingleEntryDependency = __webpack_require__(84828); +const DllModuleFactory = __webpack_require__(62468); + +class DllEntryPlugin { + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DllEntryPlugin", + (compilation, { normalModuleFactory }) => { + const dllModuleFactory = new DllModuleFactory(); + compilation.dependencyFactories.set( + DllEntryDependency, + dllModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => { + compilation.addEntry( + this.context, + new DllEntryDependency( + this.entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + dep.loc = { + name: this.name, + index: idx + }; + return dep; + }), + this.name + ), + this.name, + callback + ); + }); + } +} + +module.exports = DllEntryPlugin; + + +/***/ }), + +/***/ 24803: +/***/ ((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__(53665); +const Module = __webpack_require__(75993); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DllModule extends Module { + constructor(context, dependencies, name, type) { + super("javascript/dynamic", context); + + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this.type = type; + } + + identifier() { + return `dll ${this.name}`; + } + + readableIdentifier() { + return `dll ${this.name}`; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + source() { + return new RawSource("module.exports = __webpack_require__;"); + } + + needRebuild() { + return false; + } + + size() { + return 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("dll module"); + hash.update(this.name || ""); + super.updateHash(hash); + } +} + +module.exports = DllModule; + + +/***/ }), + +/***/ 62468: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { Tapable } = __webpack_require__(92402); +const DllModule = __webpack_require__(24803); + +class DllModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new DllModule( + data.context, + dependency.dependencies, + dependency.name, + dependency.type + ) + ); + } +} + +module.exports = DllModuleFactory; + + +/***/ }), + +/***/ 45255: +/***/ ((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__(6659); +const FlagAllModulesAsUsedPlugin = __webpack_require__(47163); +const LibManifestPlugin = __webpack_require__(30735); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(7303); + +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ + +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options, "Dll Plugin"); + this.options = options; + } + + apply(compiler) { + compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { + const itemToPlugin = (item, name) => { + if (Array.isArray(item)) { + return new DllEntryPlugin(context, item, name); + } + throw new Error("DllPlugin: supply an Array as entry"); + }; + if (typeof entry === "object" && !Array.isArray(entry)) { + Object.keys(entry).forEach(name => { + itemToPlugin(entry[name], name).apply(compiler); + }); + } else { + itemToPlugin(entry, "main").apply(compiler); + } + return true; + }); + new LibManifestPlugin(this.options).apply(compiler); + if (!this.options.entryOnly) { + new FlagAllModulesAsUsedPlugin("DllPlugin").apply(compiler); + } + } +} + +module.exports = DllPlugin; + + +/***/ }), + +/***/ 86231: +/***/ ((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__(48335); +const DelegatedSourceDependency = __webpack_require__(25930); +const DelegatedModuleFactoryPlugin = __webpack_require__(81002); +const ExternalModuleFactoryPlugin = __webpack_require__(67876); +const DelegatedExportsDependency = __webpack_require__(53104); +const NullFactory = __webpack_require__(40438); +const makePathsRelative = __webpack_require__(94658).makePathsRelative; +const WebpackError = __webpack_require__(97391); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(61112); + +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ + +class DllReferencePlugin { + /** + * @param {DllReferencePluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options, "Dll Reference Plugin"); + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + DelegatedExportsDependency, + new NullFactory() + ); + } + ); + + compiler.hooks.beforeCompile.tapAsync( + "DllReferencePlugin", + (params, callback) => { + if ("manifest" in this.options) { + const manifest = this.options.manifest; + if (typeof manifest === "string") { + params.compilationDependencies.add(manifest); + compiler.inputFileSystem.readFile(manifest, (err, result) => { + if (err) return callback(err); + // Catch errors parsing the manifest so that blank + // or malformed manifest files don't kill the process. + try { + params["dll reference " + manifest] = parseJson( + result.toString("utf-8") + ); + } catch (e) { + // Store the error in the params so that it can + // be added as a compilation error later on. + const manifestPath = makePathsRelative( + compiler.options.context, + manifest + ); + params[ + "dll reference parse error " + manifest + ] = new DllManifestError(manifestPath, e.message); + } + return callback(); + }); + 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") { + // If there was an error parsing the manifest + // file, exit now because the error will be added + // as a compilation error in the "compilation" hook. + if (params["dll reference parse error " + manifestParameter]) { + return; + } + manifest = + /** @type {DllReferencePluginOptionsManifest} */ (params[ + "dll reference " + manifestParameter + ]); + } else { + manifest = manifestParameter; + } + if (manifest) { + if (!name) name = manifest.name; + if (!sourceType) sourceType = manifest.type; + if (!content) content = manifest.content; + } + } + 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 + }).apply(normalModuleFactory); + }); + + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, params) => { + if ("manifest" in this.options) { + let manifest = this.options.manifest; + if (typeof manifest === "string") { + // If there was an error parsing the manifest file, add the + // error as a compilation error to make the compilation fail. + let e = params["dll reference parse error " + manifest]; + if (e) { + compilation.errors.push(e); + } + } + } + } + ); + } +} + +class DllManifestError extends WebpackError { + constructor(filename, message) { + super(); + + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = DllReferencePlugin; + + +/***/ }), + +/***/ 49784: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Naoyuki Kanezawa @nkzawa +*/ + + +const MultiEntryDependency = __webpack_require__(7791); +const SingleEntryDependency = __webpack_require__(84828); +const MultiModuleFactory = __webpack_require__(24005); +const MultiEntryPlugin = __webpack_require__(98046); +const SingleEntryPlugin = __webpack_require__(19070); + +/** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */ +/** @typedef {import("../declarations/WebpackOptions").EntryStatic} 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; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "DynamicEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); + + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "DynamicEntryPlugin", + (compilation, callback) => { + /** + * @param {string|string[]} entry entry value or array of entry values + * @param {string} name name of entry + * @returns {Promise} returns the promise resolving the Compilation#addEntry function + */ + const addEntry = (entry, name) => { + const dep = DynamicEntryPlugin.createDependency(entry, name); + return new Promise((resolve, reject) => { + compilation.addEntry(this.context, dep, name, err => { + if (err) return reject(err); + resolve(); + }); + }); + }; + + Promise.resolve(this.entry()).then(entry => { + if (typeof entry === "string" || Array.isArray(entry)) { + addEntry(entry, "main").then(() => callback(), callback); + } else if (typeof entry === "object") { + Promise.all( + Object.keys(entry).map(name => { + return addEntry(entry[name], name); + }) + ).then(() => callback(), callback); + } + }); + } + ); + } +} + +module.exports = DynamicEntryPlugin; +/** + * @param {string|string[]} entry entry value or array of entry paths + * @param {string} name name of entry + * @returns {SingleEntryDependency|MultiEntryDependency} returns dep + */ +DynamicEntryPlugin.createDependency = (entry, name) => { + if (Array.isArray(entry)) { + return MultiEntryPlugin.createDependency(entry, name); + } else { + return SingleEntryPlugin.createDependency(entry, name); + } +}; + + +/***/ }), + +/***/ 99531: +/***/ ((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__(97391); + +class EntryModuleNotFoundError extends WebpackError { + constructor(err) { + super("Entry module not found: " + err); + + this.name = "EntryModuleNotFoundError"; + this.details = err.details; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = EntryModuleNotFoundError; + + +/***/ }), + +/***/ 14604: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const SingleEntryPlugin = __webpack_require__(19070); +const MultiEntryPlugin = __webpack_require__(98046); +const DynamicEntryPlugin = __webpack_require__(49784); + +/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ +/** @typedef {import("./Compiler")} Compiler */ + +/** + * @param {string} context context path + * @param {EntryItem} item entry array or single path + * @param {string} name entry key name + * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin + */ +const itemToPlugin = (context, item, name) => { + if (Array.isArray(item)) { + return new MultiEntryPlugin(context, item, name); + } + return new SingleEntryPlugin(context, item, name); +}; + +module.exports = class EntryOptionPlugin { + /** + * @param {Compiler} compiler the compiler instance one is tapping into + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => { + if (typeof entry === "string" || Array.isArray(entry)) { + itemToPlugin(context, entry, "main").apply(compiler); + } else if (typeof entry === "object") { + for (const name of Object.keys(entry)) { + itemToPlugin(context, entry[name], name).apply(compiler); + } + } else if (typeof entry === "function") { + new DynamicEntryPlugin(context, entry).apply(compiler); + } + return true; + }); + } +}; + + +/***/ }), + +/***/ 71931: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ChunkGroup = __webpack_require__(52911); + +/** @typedef {import("./Chunk")} Chunk */ + +/** + * Entrypoint serves as an encapsulation primitive for chunks that are + * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a + * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects + * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks. + */ +class Entrypoint extends ChunkGroup { + /** + * Creates an instance of Entrypoint. + * @param {string} name the name of the entrypoint + */ + constructor(name) { + super(name); + /** @type {Chunk=} */ + this.runtimeChunk = undefined; + } + + /** + * isInitial will always return true for Entrypoint ChunkGroup. + * @returns {true} returns true as all entrypoints are initial ChunkGroups + */ + isInitial() { + return true; + } + + /** + * Sets the runtimeChunk for an entrypoint. + * @param {Chunk} chunk the chunk being set as the runtime chunk. + * @returns {void} + */ + setRuntimeChunk(chunk) { + this.runtimeChunk = chunk; + } + + /** + * Fetches the chunk reference containing the webpack bootstrap code + * @returns {Chunk} returns the runtime chunk or first chunk in `this.chunks` + */ + getRuntimeChunk() { + return this.runtimeChunk || this.chunks[0]; + } + + /** + * @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; + return super.replaceChunk(oldChunk, newChunk); + } +} + +module.exports = Entrypoint; + + +/***/ }), + +/***/ 6098: +/***/ ((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 +*/ + + + +/** @typedef {import("./Compiler")} Compiler */ + +const WebpackError = __webpack_require__(97391); +const DefinePlugin = __webpack_require__(97374); + +const needsEnvVarFix = + ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 && + process.platform === "win32"; + +class EnvironmentPlugin { + constructor(...keys) { + if (keys.length === 1 && Array.isArray(keys[0])) { + this.keys = keys[0]; + this.defaultValues = {}; + } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { + this.keys = Object.keys(keys[0]); + this.defaultValues = keys[0]; + } else { + this.keys = keys; + this.defaultValues = {}; + } + } + + /** + * @param {Compiler} compiler webpack compiler instance + * @returns {void} + */ + apply(compiler) { + const definitions = this.keys.reduce((defs, key) => { + // TODO remove once the fix has made its way into Node 8. + // Work around https://github.com/nodejs/node/pull/18463, + // affecting Node 8 & 9 by performing an OS-level + // operation that always succeeds before reading + // environment variables: + if (needsEnvVarFix) __webpack_require__(12087).cpus(); + + const value = + process.env[key] !== undefined + ? process.env[key] + : this.defaultValues[key]; + + if (value === undefined) { + compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => { + const error = new WebpackError( + `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + + "You can pass an object with default values to suppress this warning.\n" + + "See https://webpack.js.org/plugins/environment-plugin for example." + ); + + error.name = "EnvVariableNotDefinedError"; + compilation.warnings.push(error); + }); + } + + defs[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); + + return defs; + }, {}); + + new DefinePlugin(definitions).apply(compiler); + } +} + +module.exports = EnvironmentPlugin; + + +/***/ }), + +/***/ 80140: +/***/ ((__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"); + + return stack + .reduce( + (acc, line, idx) => + line.includes(message[idx]) ? acc : acc.concat(line), + [] + ) + .join("\n"); +}; + +exports.cutOffMessage = (stack, message) => { + const nextLine = stack.indexOf("\n"); + if (nextLine === -1) { + return stack === message ? "" : stack; + } else { + const firstLine = stack.substr(0, nextLine); + return firstLine === message ? stack.substr(nextLine + 1) : stack; + } +}; + +exports.cleanUp = (stack, message) => { + stack = exports.cutOffLoaderExecution(stack); + stack = exports.cutOffMessage(stack, message); + return stack; +}; + +exports.cleanUpWebpackOptions = (stack, message) => { + stack = exports.cutOffWebpackOptions(stack); + stack = exports.cutOffMultilineMessage(stack, message); + return stack; +}; + + +/***/ }), + +/***/ 65200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const EvalDevToolModuleTemplatePlugin = __webpack_require__(24157); + +class EvalDevToolModulePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment; + this.moduleFilenameTemplate = options.moduleFilenameTemplate; + this.namespace = options.namespace; + } + + apply(compiler) { + compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { + new EvalDevToolModuleTemplatePlugin({ + sourceUrlComment: this.sourceUrlComment, + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }).apply(compilation.moduleTemplates.javascript); + }); + } +} + +module.exports = EvalDevToolModulePlugin; + + +/***/ }), + +/***/ 24157: +/***/ ((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__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); + +const cache = new WeakMap(); + +class EvalDevToolModuleTemplatePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; + this.namespace = options.namespace || ""; + } + + apply(moduleTemplate) { + moduleTemplate.hooks.module.tap( + "EvalDevToolModuleTemplatePlugin", + (source, module) => { + const cacheEntry = cache.get(source); + if (cacheEntry !== undefined) return cacheEntry; + const content = source.source(); + const str = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + const footer = + "\n" + + this.sourceUrlComment.replace( + /\[url\]/g, + encodeURI(str) + .replace(/%2F/g, "/") + .replace(/%20/g, "_") + .replace(/%5E/g, "^") + .replace(/%5C/g, "\\") + .replace(/^\//, "") + ); + const result = new RawSource( + `eval(${JSON.stringify(content + footer)});` + ); + cache.set(source, result); + return result; + } + ); + moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { + hash.update("EvalDevToolModuleTemplatePlugin"); + hash.update("2"); + }); + } +} + +module.exports = EvalDevToolModuleTemplatePlugin; + + +/***/ }), + +/***/ 51352: +/***/ ((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__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const { absolutify } = __webpack_require__(94658); + +const cache = new WeakMap(); + +class EvalSourceMapDevToolModuleTemplatePlugin { + constructor(compilation, options) { + this.compilation = compilation; + this.sourceMapComment = + options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resource-path]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } + + apply(moduleTemplate) { + const self = this; + const options = this.options; + const matchModule = ModuleFilenameHelpers.matchObject.bind( + ModuleFilenameHelpers, + options + ); + moduleTemplate.hooks.module.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + (source, module) => { + const cachedSource = cache.get(source); + if (cachedSource !== undefined) { + return cachedSource; + } + + if (!matchModule(module.resource)) { + return source; + } + + /** @type {{ [key: string]: TODO; }} */ + let sourceMap; + let content; + if (source.sourceAndMap) { + const sourceAndMap = source.sourceAndMap(options); + sourceMap = sourceAndMap.map; + content = sourceAndMap.source; + } else { + sourceMap = source.map(options); + content = source.source(); + } + if (!sourceMap) { + return source; + } + + // Clone (flat) the sourcemap to ensure that the mutations below do not persist. + sourceMap = Object.keys(sourceMap).reduce((obj, key) => { + obj[key] = sourceMap[key]; + return obj; + }, {}); + const context = this.compilation.compiler.options.context; + const modules = sourceMap.sources.map(source => { + if (source.startsWith("webpack://")) { + source = absolutify(context, source.slice(10)); + } + const module = self.compilation.findModule(source); + return module || source; + }); + let moduleFilenames = modules.map(module => { + return ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: self.moduleFilenameTemplate, + namespace: self.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + }); + moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( + moduleFilenames, + (filename, i, n) => { + for (let j = 0; j < n; j++) filename += "*"; + return filename; + } + ); + sourceMap.sources = moduleFilenames; + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = `${module.id}.js`; + + const footer = + self.sourceMapComment.replace( + /\[url\]/g, + `data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(sourceMap), + "utf8" + ).toString("base64")}` + ) + `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug + + const evalSource = new RawSource( + `eval(${JSON.stringify(content + footer)});` + ); + + cache.set(source, evalSource); + + return evalSource; + } + ); + moduleTemplate.hooks.hash.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + hash => { + hash.update("eval-source-map"); + hash.update("2"); + } + ); + } +} +module.exports = EvalSourceMapDevToolModuleTemplatePlugin; + + +/***/ }), + +/***/ 99994: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const EvalSourceMapDevToolModuleTemplatePlugin = __webpack_require__(51352); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); + +class EvalSourceMapDevToolPlugin { + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" + ); + } + if (typeof options === "string") { + options = { + append: options + }; + } + if (!options) options = {}; + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "EvalSourceMapDevToolPlugin", + compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + new EvalSourceMapDevToolModuleTemplatePlugin( + compilation, + options + ).apply(compilation.moduleTemplates.javascript); + } + ); + } +} + +module.exports = EvalSourceMapDevToolPlugin; + + +/***/ }), + +/***/ 50471: +/***/ ((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__(53665); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +class ExportPropertyMainTemplatePlugin { + /** + * @param {string|string[]} property the name of the property to export + */ + constructor(property) { + this.property = property; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const postfix = `${accessorToObjectAccess([].concat(this.property))}`; + return new ConcatSource(source, postfix); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "ExportPropertyMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { + hash.update("export property"); + hash.update(`${this.property}`); + }); + } +} + +module.exports = ExportPropertyMainTemplatePlugin; + + +/***/ }), + +/***/ 17270: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); +const ConstDependency = __webpack_require__(71101); +const ParserHelpers = __webpack_require__(23999); +const NullFactory = __webpack_require__(40438); + +const REPLACEMENTS = { + // eslint-disable-next-line camelcase + __webpack_hash__: "__webpack_require__.h", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "__webpack_require__.cn" +}; +const REPLACEMENT_TYPES = { + // eslint-disable-next-line camelcase + __webpack_hash__: "string", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "string" +}; + +class ExtendedAPIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ExtendedAPIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const mainTemplate = compilation.mainTemplate; + mainTemplate.hooks.requireExtensions.tap( + "ExtendedAPIPlugin", + (source, chunk, hash) => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`); + buf.push(""); + buf.push("// __webpack_chunkname__"); + buf.push( + `${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};` + ); + return Template.asString(buf); + } + ); + mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true); + + const handler = (parser, parserOptions) => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + parser.hooks.evaluateTypeof + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) + ); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ExtendedAPIPlugin", handler); + } + ); + } +} + +module.exports = ExtendedAPIPlugin; + + +/***/ }), + +/***/ 17204: +/***/ ((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__(53665); +const Module = __webpack_require__(75993); +const WebpackMissingModule = __webpack_require__(75386); +const Template = __webpack_require__(96066); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class ExternalModule extends Module { + constructor(request, type, userRequest) { + super("javascript/dynamic", null); + + // Info from Factory + this.request = request; + this.externalType = type; + this.userRequest = userRequest; + this.external = true; + } + + libIdent() { + return this.userRequest; + } + + chunkCondition(chunk) { + return chunk.hasEntryModule(); + } + + identifier() { + return "external " + JSON.stringify(this.request); + } + + readableIdentifier() { + return "external " + JSON.stringify(this.request); + } + + needRebuild() { + return false; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + callback(); + } + + getSourceForGlobalVariableExternal(variableName, type) { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; + } + + // needed for e.g. window["some"]["thing"] + const objectLookup = variableName + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `(function() { module.exports = ${type}${objectLookup}; }());`; + } + + getSourceForCommonJsExternal(moduleAndSpecifiers) { + if (!Array.isArray(moduleAndSpecifiers)) { + return `module.exports = require(${JSON.stringify( + moduleAndSpecifiers + )});`; + } + + const moduleName = moduleAndSpecifiers[0]; + const objectLookup = moduleAndSpecifiers + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `module.exports = require(${JSON.stringify( + moduleName + )})${objectLookup};`; + } + + checkExternalVariable(variableToCheck, request) { + return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( + request + )}}\n`; + } + + getSourceForAmdOrUmdExternal(id, optional, request) { + const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${id}` + )}__`; + const missingModuleError = optional + ? this.checkExternalVariable(externalVariable, request) + : ""; + return `${missingModuleError}module.exports = ${externalVariable};`; + } + + getSourceForDefaultCase(optional, request) { + if (!Array.isArray(request)) { + // make it an array as the look up works the same basically + request = [request]; + } + + const variableName = request[0]; + const missingModuleError = optional + ? this.checkExternalVariable(variableName, request.join(".")) + : ""; + const objectLookup = request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `${missingModuleError}module.exports = ${variableName}${objectLookup};`; + } + + getSourceString(runtime) { + const request = + typeof this.request === "object" && !Array.isArray(this.request) + ? this.request[this.externalType] + : this.request; + switch (this.externalType) { + case "this": + case "window": + case "self": + return this.getSourceForGlobalVariableExternal( + request, + this.externalType + ); + case "global": + return this.getSourceForGlobalVariableExternal( + request, + runtime.outputOptions.globalObject + ); + case "commonjs": + case "commonjs2": + return this.getSourceForCommonJsExternal(request); + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + return this.getSourceForAmdOrUmdExternal( + this.id, + this.optional, + request + ); + default: + return this.getSourceForDefaultCase(this.optional, request); + } + } + + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + + return new RawSource(sourceString); + } + + source(dependencyTemplates, runtime) { + return this.getSource(this.getSourceString(runtime)); + } + + size() { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this.externalType); + hash.update(JSON.stringify(this.request)); + hash.update(JSON.stringify(Boolean(this.optional))); + super.updateHash(hash); + } +} + +module.exports = ExternalModule; + + +/***/ }), + +/***/ 67876: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ExternalModule = __webpack_require__(17204); + +class ExternalModuleFactoryPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factory.tap( + "ExternalModuleFactoryPlugin", + factory => (data, callback) => { + const context = data.context; + const dependency = data.dependencies[0]; + + const handleExternal = (value, type, callback) => { + if (typeof type === "function") { + callback = type; + type = undefined; + } + if (value === false) return factory(data, callback); + if (value === true) value = dependency.request; + if (type === undefined && /^[a-z0-9]+ /.test(value)) { + const idx = value.indexOf(" "); + type = value.substr(0, idx); + value = value.substr(idx + 1); + } + callback( + null, + new ExternalModule(value, type || globalType, dependency.request) + ); + return true; + }; + + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, callback); + } + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + let asyncFlag; + const handleExternalsAndCallback = (err, module) => { + if (err) return callback(err); + if (!module) { + if (asyncFlag) { + asyncFlag = false; + return; + } + return next(); + } + callback(null, module); + }; + + do { + asyncFlag = true; + if (i >= externals.length) return callback(); + handleExternals(externals[i++], handleExternalsAndCallback); + } while (!asyncFlag); + asyncFlag = false; + }; + + next(); + return; + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { + return handleExternal(dependency.request, callback); + } + } else if (typeof externals === "function") { + externals.call( + null, + context, + dependency.request, + (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); + } + } + ); + return; + } else if ( + typeof externals === "object" && + Object.prototype.hasOwnProperty.call(externals, dependency.request) + ) { + return handleExternal(externals[dependency.request], callback); + } + callback(); + }; + + handleExternals(this.externals, (err, module) => { + if (err) return callback(err); + if (!module) return handleExternal(false, callback); + return callback(null, module); + }); + } + ); + } +} +module.exports = ExternalModuleFactoryPlugin; + + +/***/ }), + +/***/ 75705: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ExternalModuleFactoryPlugin = __webpack_require__(67876); + +class ExternalsPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + apply(compiler) { + compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory + ); + }); + } +} + +module.exports = ExternalsPlugin; + + +/***/ }), + +/***/ 47163: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./Compiler")} Compiler */ + +class FlagAllModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; + } + + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagAllModulesAsUsedPlugin", + compilation => { + compilation.hooks.optimizeDependencies.tap( + "FlagAllModulesAsUsedPlugin", + modules => { + for (const module of modules) { + module.used = true; + module.usedExports = true; + module.addReason(null, null, this.explanation); + } + } + ); + } + ); + } +} + +module.exports = FlagAllModulesAsUsedPlugin; + + +/***/ }), + +/***/ 73599: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Queue = __webpack_require__(38637); + +const addToSet = (a, b) => { + for (const item of b) { + a.add(item); + } +}; + +class FlagDependencyExportsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagDependencyExportsPlugin", + compilation => { + compilation.hooks.finishModules.tap( + "FlagDependencyExportsPlugin", + modules => { + const dependencies = new Map(); + + const queue = new Queue(); + + let module; + let moduleWithExports; + let moduleProvidedExports; + let providedExportsAreTemporary; + + const processDependenciesBlock = depBlock => { + for (const dep of depBlock.dependencies) { + if (processDependency(dep)) return true; + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + if (processDependency(dep)) return true; + } + } + for (const block of depBlock.blocks) { + if (processDependenciesBlock(block)) return true; + } + return false; + }; + + const processDependency = dep => { + const exportDesc = dep.getExports && dep.getExports(); + if (!exportDesc) return; + moduleWithExports = true; + const exports = exportDesc.exports; + // break early if it's only in the worst state + if (module.buildMeta.providedExports === true) { + return true; + } + // break if it should move to the worst state + if (exports === true) { + module.buildMeta.providedExports = true; + return true; + } + // merge in new exports + if (Array.isArray(exports)) { + addToSet(moduleProvidedExports, exports); + } + // store dependencies + const exportDeps = exportDesc.dependencies; + if (exportDeps) { + providedExportsAreTemporary = true; + for (const exportDependency of exportDeps) { + // add dependency for this module + const set = dependencies.get(exportDependency); + if (set === undefined) { + dependencies.set(exportDependency, new Set([module])); + } else { + set.add(module); + } + } + } + return false; + }; + + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; + + const notifyDependenciesIfDifferent = (set, array) => { + const deps = dependencies.get(module); + if (deps !== undefined) { + if (set.size === array.length) { + let i = 0; + let different = false; + for (const item of set) { + if (item !== array[i++]) { + different = true; + break; + } + } + if (!different) return; + } + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; + + // Start with all modules without provided exports + for (const module of modules) { + if (module.buildInfo.temporaryProvidedExports) { + // Clear exports when they are temporary + // and recreate them + module.buildMeta.providedExports = null; + queue.enqueue(module); + } else if (!module.buildMeta.providedExports) { + queue.enqueue(module); + } + } + + while (queue.length > 0) { + module = queue.dequeue(); + + if (module.buildMeta.providedExports !== true) { + moduleWithExports = + module.buildMeta && module.buildMeta.exportsType; + moduleProvidedExports = new Set(); + providedExportsAreTemporary = false; + processDependenciesBlock(module); + module.buildInfo.temporaryProvidedExports = providedExportsAreTemporary; + if (!moduleWithExports) { + notifyDependencies(); + module.buildMeta.providedExports = true; + } else if (module.buildMeta.providedExports === true) { + notifyDependencies(); + } else if (!module.buildMeta.providedExports) { + notifyDependencies(); + module.buildMeta.providedExports = Array.from( + moduleProvidedExports + ); + } else { + notifyDependenciesIfDifferent( + moduleProvidedExports, + module.buildMeta.providedExports + ); + module.buildMeta.providedExports = Array.from( + moduleProvidedExports + ); + } + } + } + } + ); + const providedExportsCache = new WeakMap(); + compilation.hooks.rebuildModule.tap( + "FlagDependencyExportsPlugin", + module => { + providedExportsCache.set(module, module.buildMeta.providedExports); + } + ); + compilation.hooks.finishRebuildingModule.tap( + "FlagDependencyExportsPlugin", + module => { + module.buildMeta.providedExports = providedExportsCache.get(module); + } + ); + } + ); + } +} + +module.exports = FlagDependencyExportsPlugin; + + +/***/ }), + +/***/ 33632: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ + +/** @typedef {false | true | string[]} UsedExports */ + +const addToSet = (a, b) => { + for (const item of b) { + if (!a.includes(item)) a.push(item); + } + return a; +}; + +const isSubset = (biggerSet, subset) => { + if (biggerSet === true) return true; + if (subset === true) return false; + return subset.every(item => biggerSet.indexOf(item) >= 0); +}; + +class FlagDependencyUsagePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { + compilation.hooks.optimizeDependencies.tap( + "FlagDependencyUsagePlugin", + modules => { + const processModule = (module, usedExports) => { + module.used = true; + if (module.usedExports === true) return; + if (usedExports === true) { + module.usedExports = true; + } else if (Array.isArray(usedExports)) { + const old = module.usedExports ? module.usedExports.length : -1; + module.usedExports = addToSet( + module.usedExports || [], + usedExports + ); + if (module.usedExports.length === old) { + return; + } + } else if (Array.isArray(module.usedExports)) { + return; + } else { + module.usedExports = false; + } + + // for a module without side effects we stop tracking usage here when no export is used + // This module won't be evaluated in this case + if (module.factoryMeta.sideEffectFree) { + if (module.usedExports === false) return; + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) + return; + } + + queue.push([module, module, module.usedExports]); + }; + + const processDependenciesBlock = (module, depBlock, usedExports) => { + for (const dep of depBlock.dependencies) { + processDependency(module, dep); + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + processDependency(module, dep); + } + } + for (const block of depBlock.blocks) { + queue.push([module, block, usedExports]); + } + }; + + const processDependency = (module, dep) => { + const reference = compilation.getDependencyReference(module, dep); + if (!reference) return; + const referenceModule = reference.module; + const importedNames = reference.importedNames; + const oldUsed = referenceModule.used; + const oldUsedExports = referenceModule.usedExports; + if ( + !oldUsed || + (importedNames && + (!oldUsedExports || !isSubset(oldUsedExports, importedNames))) + ) { + processModule(referenceModule, importedNames); + } + }; + + for (const module of modules) { + if (!module.used) module.used = false; + } + + /** @type {[Module, DependenciesBlock, UsedExports][]} */ + const queue = []; + for (const preparedEntrypoint of compilation._preparedEntrypoints) { + if (preparedEntrypoint.module) { + processModule(preparedEntrypoint.module, true); + } + } + + while (queue.length) { + const queueItem = queue.pop(); + processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); + } + } + ); + }); + } +} +module.exports = FlagDependencyUsagePlugin; + + +/***/ }), + +/***/ 31221: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const FunctionModuleTemplatePlugin = __webpack_require__(18864); + +class FunctionModulePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { + new FunctionModuleTemplatePlugin().apply( + compilation.moduleTemplates.javascript + ); + }); + } +} + +module.exports = FunctionModulePlugin; + + +/***/ }), + +/***/ 18864: +/***/ ((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__(53665); +const Template = __webpack_require__(96066); + +class FunctionModuleTemplatePlugin { + apply(moduleTemplate) { + moduleTemplate.hooks.render.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + const source = new ConcatSource(); + const args = [module.moduleArgument]; + // TODO remove HACK checking type for javascript + if (module.type && module.type.startsWith("javascript")) { + args.push(module.exportsArgument); + if (module.hasDependencies(d => d.requireWebpackRequire !== false)) { + args.push("__webpack_require__"); + } + } else if (module.type && module.type.startsWith("json")) { + // no additional arguments needed + } else { + args.push(module.exportsArgument, "__webpack_require__"); + } + source.add("/***/ (function(" + args.join(", ") + ") {\n\n"); + if (module.buildInfo.strict) source.add('"use strict";\n'); + source.add(moduleSource); + source.add("\n\n/***/ })"); + return source; + } + ); + + moduleTemplate.hooks.package.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + if (moduleTemplate.runtimeTemplate.outputOptions.pathinfo) { + const source = new ConcatSource(); + const req = module.readableIdentifier( + moduleTemplate.runtimeTemplate.requestShortener + ); + const reqStr = req.replace(/\*\//g, "*_/"); + const reqStrStar = "*".repeat(reqStr.length); + source.add("/*!****" + reqStrStar + "****!*\\\n"); + source.add(" !*** " + reqStr + " ***!\n"); + source.add(" \\****" + reqStrStar + "****/\n"); + if ( + Array.isArray(module.buildMeta.providedExports) && + module.buildMeta.providedExports.length === 0 + ) { + source.add(Template.toComment("no exports provided") + "\n"); + } else if (Array.isArray(module.buildMeta.providedExports)) { + source.add( + Template.toComment( + "exports provided: " + + module.buildMeta.providedExports.join(", ") + ) + "\n" + ); + } else if (module.buildMeta.providedExports) { + source.add(Template.toComment("no static exports found") + "\n"); + } + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + source.add(Template.toComment("no exports used") + "\n"); + } else if (Array.isArray(module.usedExports)) { + source.add( + Template.toComment( + "exports used: " + module.usedExports.join(", ") + ) + "\n" + ); + } else if (module.usedExports) { + source.add(Template.toComment("all exports used") + "\n"); + } + if (module.optimizationBailout) { + for (const text of module.optimizationBailout) { + let code; + if (typeof text === "function") { + code = text(moduleTemplate.runtimeTemplate.requestShortener); + } else { + code = text; + } + source.add(Template.toComment(`${code}`) + "\n"); + } + } + source.add(moduleSource); + return source; + } + return moduleSource; + } + ); + + moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { + hash.update("FunctionModuleTemplatePlugin"); + hash.update("2"); + }); + } +} +module.exports = FunctionModuleTemplatePlugin; + + +/***/ }), + +/***/ 39172: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ + +/** + * + */ +class Generator { + static byType(map) { + return new ByTypeGenerator(map); + } + + /** + * @abstract + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + throw new Error("Generator.generate: must be overridden"); + } +} + +class ByTypeGenerator extends Generator { + constructor(map) { + super(); + this.map = map; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + const generator = this.map[type]; + if (!generator) { + throw new Error(`Generator.byType: no generator specified for ${type}`); + } + return generator.generate( + module, + dependencyTemplates, + runtimeTemplate, + type + ); + } +} + +module.exports = Generator; + + +/***/ }), + +/***/ 32973: +/***/ ((__unused_webpack_module, exports) => { + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ + +/** + * @param {ChunkGroup} chunkGroup the ChunkGroup to connect + * @param {Chunk} chunk chunk to tie to ChunkGroup + * @returns {void} + */ +const connectChunkGroupAndChunk = (chunkGroup, chunk) => { + if (chunkGroup.pushChunk(chunk)) { + chunk.addGroup(chunkGroup); + } +}; + +/** + * @param {ChunkGroup} parent parent ChunkGroup to connect + * @param {ChunkGroup} child child ChunkGroup to connect + * @returns {void} + */ +const connectChunkGroupParentAndChild = (parent, child) => { + if (parent.addChild(child)) { + child.addParent(parent); + } +}; + +/** + * @param {Chunk} chunk Chunk to connect to Module + * @param {Module} module Module to connect to Chunk + * @returns {void} + */ +const connectChunkAndModule = (chunk, module) => { + if (module.addChunk(chunk)) { + chunk.addModule(module); + } +}; + +/** + * @param {Chunk} chunk Chunk being disconnected + * @param {Module} module Module being disconnected + * @returns {void} + */ +const disconnectChunkAndModule = (chunk, module) => { + chunk.removeModule(module); + module.removeChunk(chunk); +}; + +/** + * @param {AsyncDependenciesBlock} depBlock DepBlock being tied to ChunkGroup + * @param {ChunkGroup} chunkGroup ChunkGroup being tied to DepBlock + * @returns {void} + */ +const connectDependenciesBlockAndChunkGroup = (depBlock, chunkGroup) => { + if (chunkGroup.addBlock(depBlock)) { + depBlock.chunkGroup = chunkGroup; + } +}; + +exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; +exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; +exports.connectChunkAndModule = connectChunkAndModule; +exports.disconnectChunkAndModule = disconnectChunkAndModule; +exports.connectDependenciesBlockAndChunkGroup = connectDependenciesBlockAndChunkGroup; + + +/***/ }), + +/***/ 30327: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + +const WebpackError = __webpack_require__(97391); + +module.exports = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 50268: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const createHash = __webpack_require__(15660); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(45843); + +/** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ + +class HashedModuleIdsPlugin { + /** + * @param {HashedModuleIdsPluginOptions=} options options object + */ + constructor(options) { + if (!options) options = {}; + + validateOptions(schema, options, "Hashed Module Ids Plugin"); + + /** @type {HashedModuleIdsPluginOptions} */ + this.options = Object.assign( + { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4 + }, + options + ); + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { + const usedIds = new Set(); + compilation.hooks.beforeModuleIds.tap( + "HashedModuleIdsPlugin", + modules => { + for (const module of modules) { + if (module.id === null && module.libIdent) { + const id = module.libIdent({ + context: this.options.context || compiler.options.context + }); + const hash = createHash(options.hashFunction); + hash.update(id); + const hashId = /** @type {string} */ (hash.digest( + options.hashDigest + )); + let len = options.hashDigestLength; + while (usedIds.has(hashId.substr(0, len))) len++; + module.id = hashId.substr(0, len); + usedIds.add(module.id); + } + } + } + ); + }); + } +} + +module.exports = HashedModuleIdsPlugin; + + +/***/ }), + +/***/ 65217: +/***/ ((module) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable no-unused-vars +var $hash$ = undefined; +var $requestTimeout$ = undefined; +var installedModules = undefined; +var $require$ = undefined; +var hotDownloadManifest = undefined; +var hotDownloadUpdateChunk = undefined; +var hotDisposeChunk = undefined; +var modules = undefined; +var chunkId = undefined; + +module.exports = function() { + var hotApplyOnUpdate = true; + // eslint-disable-next-line no-unused-vars + var hotCurrentHash = $hash$; + var hotRequestTimeout = $requestTimeout$; + var hotCurrentModuleData = {}; + var hotCurrentChildModule; + // eslint-disable-next-line no-unused-vars + var hotCurrentParents = []; + // eslint-disable-next-line no-unused-vars + var hotCurrentParentsTemp = []; + + // eslint-disable-next-line no-unused-vars + function hotCreateRequire(moduleId) { + var me = installedModules[moduleId]; + if (!me) return $require$; + var fn = function(request) { + if (me.hot.active) { + if (installedModules[request]) { + if (installedModules[request].parents.indexOf(moduleId) === -1) { + installedModules[request].parents.push(moduleId); + } + } else { + hotCurrentParents = [moduleId]; + hotCurrentChildModule = request; + } + if (me.children.indexOf(request) === -1) { + me.children.push(request); + } + } else { + console.warn( + "[HMR] unexpected require(" + + request + + ") from disposed module " + + moduleId + ); + hotCurrentParents = []; + } + return $require$(request); + }; + var ObjectFactory = function ObjectFactory(name) { + return { + configurable: true, + enumerable: true, + get: function() { + return $require$[name]; + }, + set: function(value) { + $require$[name] = value; + } + }; + }; + for (var name in $require$) { + if ( + Object.prototype.hasOwnProperty.call($require$, name) && + name !== "e" && + name !== "t" + ) { + Object.defineProperty(fn, name, ObjectFactory(name)); + } + } + fn.e = function(chunkId) { + if (hotStatus === "ready") hotSetStatus("prepare"); + hotChunksLoading++; + return $require$.e(chunkId).then(finishChunkLoading, function(err) { + finishChunkLoading(); + throw err; + }); + + function finishChunkLoading() { + hotChunksLoading--; + if (hotStatus === "prepare") { + if (!hotWaitingFilesMap[chunkId]) { + hotEnsureUpdateChunk(chunkId); + } + if (hotChunksLoading === 0 && hotWaitingFiles === 0) { + hotUpdateDownloaded(); + } + } + } + }; + fn.t = function(value, mode) { + if (mode & 1) value = fn(value); + return $require$.t(value, mode & ~1); + }; + return fn; + } + + // eslint-disable-next-line no-unused-vars + function hotCreateModule(moduleId) { + var hot = { + // private stuff + _acceptedDependencies: {}, + _declinedDependencies: {}, + _selfAccepted: false, + _selfDeclined: false, + _selfInvalidated: false, + _disposeHandlers: [], + _main: hotCurrentChildModule !== moduleId, + + // Module API + active: true, + accept: function(dep, callback) { + if (dep === undefined) hot._selfAccepted = true; + else if (typeof dep === "function") hot._selfAccepted = dep; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._acceptedDependencies[dep[i]] = callback || function() {}; + else hot._acceptedDependencies[dep] = callback || function() {}; + }, + decline: function(dep) { + if (dep === undefined) hot._selfDeclined = true; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._declinedDependencies[dep[i]] = true; + else hot._declinedDependencies[dep] = true; + }, + dispose: function(callback) { + hot._disposeHandlers.push(callback); + }, + addDisposeHandler: function(callback) { + hot._disposeHandlers.push(callback); + }, + removeDisposeHandler: function(callback) { + var idx = hot._disposeHandlers.indexOf(callback); + if (idx >= 0) hot._disposeHandlers.splice(idx, 1); + }, + invalidate: function() { + this._selfInvalidated = true; + switch (hotStatus) { + case "idle": + hotUpdate = {}; + hotUpdate[moduleId] = modules[moduleId]; + hotSetStatus("ready"); + break; + case "ready": + hotApplyInvalidatedModule(moduleId); + break; + case "prepare": + case "check": + case "dispose": + case "apply": + (hotQueuedInvalidatedModules = + hotQueuedInvalidatedModules || []).push(moduleId); + break; + default: + // ignore requests in error states + break; + } + }, + + // Management API + check: hotCheck, + apply: hotApply, + status: function(l) { + if (!l) return hotStatus; + hotStatusHandlers.push(l); + }, + addStatusHandler: function(l) { + hotStatusHandlers.push(l); + }, + removeStatusHandler: function(l) { + var idx = hotStatusHandlers.indexOf(l); + if (idx >= 0) hotStatusHandlers.splice(idx, 1); + }, + + //inherit from previous dispose call + data: hotCurrentModuleData[moduleId] + }; + hotCurrentChildModule = undefined; + return hot; + } + + var hotStatusHandlers = []; + var hotStatus = "idle"; + + function hotSetStatus(newStatus) { + hotStatus = newStatus; + for (var i = 0; i < hotStatusHandlers.length; i++) + hotStatusHandlers[i].call(null, newStatus); + } + + // while downloading + var hotWaitingFiles = 0; + var hotChunksLoading = 0; + var hotWaitingFilesMap = {}; + var hotRequestedFilesMap = {}; + var hotAvailableFilesMap = {}; + var hotDeferred; + + // The update info + var hotUpdate, hotUpdateNewHash, hotQueuedInvalidatedModules; + + function toModuleId(id) { + var isNumber = +id + "" === id; + return isNumber ? +id : id; + } + + function hotCheck(apply) { + if (hotStatus !== "idle") { + throw new Error("check() is only allowed in idle status"); + } + hotApplyOnUpdate = apply; + hotSetStatus("check"); + return hotDownloadManifest(hotRequestTimeout).then(function(update) { + if (!update) { + hotSetStatus(hotApplyInvalidatedModules() ? "ready" : "idle"); + return null; + } + hotRequestedFilesMap = {}; + hotWaitingFilesMap = {}; + hotAvailableFilesMap = update.c; + hotUpdateNewHash = update.h; + + hotSetStatus("prepare"); + var promise = new Promise(function(resolve, reject) { + hotDeferred = { + resolve: resolve, + reject: reject + }; + }); + hotUpdate = {}; + /*foreachInstalledChunks*/ + // eslint-disable-next-line no-lone-blocks + { + hotEnsureUpdateChunk(chunkId); + } + if ( + hotStatus === "prepare" && + hotChunksLoading === 0 && + hotWaitingFiles === 0 + ) { + hotUpdateDownloaded(); + } + return promise; + }); + } + + // eslint-disable-next-line no-unused-vars + function hotAddUpdateChunk(chunkId, moreModules) { + if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) + return; + hotRequestedFilesMap[chunkId] = false; + for (var moduleId in moreModules) { + if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { + hotUpdate[moduleId] = moreModules[moduleId]; + } + } + if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { + hotUpdateDownloaded(); + } + } + + function hotEnsureUpdateChunk(chunkId) { + if (!hotAvailableFilesMap[chunkId]) { + hotWaitingFilesMap[chunkId] = true; + } else { + hotRequestedFilesMap[chunkId] = true; + hotWaitingFiles++; + hotDownloadUpdateChunk(chunkId); + } + } + + function hotUpdateDownloaded() { + hotSetStatus("ready"); + var deferred = hotDeferred; + hotDeferred = null; + if (!deferred) return; + if (hotApplyOnUpdate) { + // Wrap deferred object in Promise to mark it as a well-handled Promise to + // avoid triggering uncaught exception warning in Chrome. + // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 + Promise.resolve() + .then(function() { + return hotApply(hotApplyOnUpdate); + }) + .then( + function(result) { + deferred.resolve(result); + }, + function(err) { + deferred.reject(err); + } + ); + } else { + var outdatedModules = []; + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + outdatedModules.push(toModuleId(id)); + } + } + deferred.resolve(outdatedModules); + } + } + + function hotApply(options) { + if (hotStatus !== "ready") + throw new Error("apply() is only allowed in ready status"); + options = options || {}; + return hotApplyInternal(options); + } + + function hotApplyInternal(options) { + hotApplyInvalidatedModules(); + + var cb; + var i; + var j; + var module; + var moduleId; + + function getAffectedStuff(updateModuleId) { + var outdatedModules = [updateModuleId]; + var outdatedDependencies = {}; + + var queue = outdatedModules.map(function(id) { + return { + chain: [id], + id: id + }; + }); + while (queue.length > 0) { + var queueItem = queue.pop(); + var moduleId = queueItem.id; + var chain = queueItem.chain; + module = installedModules[moduleId]; + if ( + !module || + (module.hot._selfAccepted && !module.hot._selfInvalidated) + ) + continue; + if (module.hot._selfDeclined) { + return { + type: "self-declined", + chain: chain, + moduleId: moduleId + }; + } + if (module.hot._main) { + return { + type: "unaccepted", + chain: chain, + moduleId: moduleId + }; + } + for (var i = 0; i < module.parents.length; i++) { + var parentId = module.parents[i]; + var parent = installedModules[parentId]; + if (!parent) continue; + if (parent.hot._declinedDependencies[moduleId]) { + return { + type: "declined", + chain: chain.concat([parentId]), + moduleId: moduleId, + parentId: parentId + }; + } + if (outdatedModules.indexOf(parentId) !== -1) continue; + if (parent.hot._acceptedDependencies[moduleId]) { + if (!outdatedDependencies[parentId]) + outdatedDependencies[parentId] = []; + addAllToSet(outdatedDependencies[parentId], [moduleId]); + continue; + } + delete outdatedDependencies[parentId]; + outdatedModules.push(parentId); + queue.push({ + chain: chain.concat([parentId]), + id: parentId + }); + } + } + + return { + type: "accepted", + moduleId: updateModuleId, + outdatedModules: outdatedModules, + outdatedDependencies: outdatedDependencies + }; + } + + function addAllToSet(a, b) { + for (var i = 0; i < b.length; i++) { + var item = b[i]; + if (a.indexOf(item) === -1) a.push(item); + } + } + + // at begin all updates modules are outdated + // the "outdated" status can propagate to parents if they don't accept the children + var outdatedDependencies = {}; + var outdatedModules = []; + var appliedUpdate = {}; + + var warnUnexpectedRequire = function warnUnexpectedRequire() { + console.warn( + "[HMR] unexpected require(" + result.moduleId + ") to disposed module" + ); + }; + + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + moduleId = toModuleId(id); + /** @type {TODO} */ + var result; + if (hotUpdate[id]) { + result = getAffectedStuff(moduleId); + } else { + result = { + type: "disposed", + moduleId: id + }; + } + /** @type {Error|false} */ + var abortError = false; + var doApply = false; + var doDispose = false; + var chainInfo = ""; + if (result.chain) { + chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); + } + switch (result.type) { + case "self-declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of self decline: " + + result.moduleId + + chainInfo + ); + break; + case "declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of declined dependency: " + + result.moduleId + + " in " + + result.parentId + + chainInfo + ); + break; + case "unaccepted": + if (options.onUnaccepted) options.onUnaccepted(result); + if (!options.ignoreUnaccepted) + abortError = new Error( + "Aborted because " + moduleId + " is not accepted" + chainInfo + ); + break; + case "accepted": + if (options.onAccepted) options.onAccepted(result); + doApply = true; + break; + case "disposed": + if (options.onDisposed) options.onDisposed(result); + doDispose = true; + break; + default: + throw new Error("Unexception type " + result.type); + } + if (abortError) { + hotSetStatus("abort"); + return Promise.reject(abortError); + } + if (doApply) { + appliedUpdate[moduleId] = hotUpdate[moduleId]; + addAllToSet(outdatedModules, result.outdatedModules); + for (moduleId in result.outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call( + result.outdatedDependencies, + moduleId + ) + ) { + if (!outdatedDependencies[moduleId]) + outdatedDependencies[moduleId] = []; + addAllToSet( + outdatedDependencies[moduleId], + result.outdatedDependencies[moduleId] + ); + } + } + } + if (doDispose) { + addAllToSet(outdatedModules, [result.moduleId]); + appliedUpdate[moduleId] = warnUnexpectedRequire; + } + } + } + + // Store self accepted outdated modules to require them later by the module system + var outdatedSelfAcceptedModules = []; + for (i = 0; i < outdatedModules.length; i++) { + moduleId = outdatedModules[i]; + if ( + installedModules[moduleId] && + installedModules[moduleId].hot._selfAccepted && + // removed self-accepted modules should not be required + appliedUpdate[moduleId] !== warnUnexpectedRequire && + // when called invalidate self-accepting is not possible + !installedModules[moduleId].hot._selfInvalidated + ) { + outdatedSelfAcceptedModules.push({ + module: moduleId, + parents: installedModules[moduleId].parents.slice(), + errorHandler: installedModules[moduleId].hot._selfAccepted + }); + } + } + + // Now in "dispose" phase + hotSetStatus("dispose"); + Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { + if (hotAvailableFilesMap[chunkId] === false) { + hotDisposeChunk(chunkId); + } + }); + + var idx; + var queue = outdatedModules.slice(); + while (queue.length > 0) { + moduleId = queue.pop(); + module = installedModules[moduleId]; + if (!module) continue; + + var data = {}; + + // Call dispose handlers + var disposeHandlers = module.hot._disposeHandlers; + for (j = 0; j < disposeHandlers.length; j++) { + cb = disposeHandlers[j]; + cb(data); + } + hotCurrentModuleData[moduleId] = data; + + // disable module (this disables requires from this module) + module.hot.active = false; + + // remove module from cache + delete installedModules[moduleId]; + + // when disposing there is no need to call dispose handler + delete outdatedDependencies[moduleId]; + + // remove "parents" references from all children + for (j = 0; j < module.children.length; j++) { + var child = installedModules[module.children[j]]; + if (!child) continue; + idx = child.parents.indexOf(moduleId); + if (idx >= 0) { + child.parents.splice(idx, 1); + } + } + } + + // remove outdated dependency from module children + var dependency; + var moduleOutdatedDependencies; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + for (j = 0; j < moduleOutdatedDependencies.length; j++) { + dependency = moduleOutdatedDependencies[j]; + idx = module.children.indexOf(dependency); + if (idx >= 0) module.children.splice(idx, 1); + } + } + } + } + + // Now in "apply" phase + hotSetStatus("apply"); + + if (hotUpdateNewHash !== undefined) { + hotCurrentHash = hotUpdateNewHash; + hotUpdateNewHash = undefined; + } + hotUpdate = undefined; + + // insert new code + for (moduleId in appliedUpdate) { + if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { + modules[moduleId] = appliedUpdate[moduleId]; + } + } + + // call accept handlers + var error = null; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + var callbacks = []; + for (i = 0; i < moduleOutdatedDependencies.length; i++) { + dependency = moduleOutdatedDependencies[i]; + cb = module.hot._acceptedDependencies[dependency]; + if (cb) { + if (callbacks.indexOf(cb) !== -1) continue; + callbacks.push(cb); + } + } + for (i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + try { + cb(moduleOutdatedDependencies); + } catch (err) { + if (options.onErrored) { + options.onErrored({ + type: "accept-errored", + moduleId: moduleId, + dependencyId: moduleOutdatedDependencies[i], + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } + } + } + } + } + + // Load self accepted modules + for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { + var item = outdatedSelfAcceptedModules[i]; + moduleId = item.module; + hotCurrentParents = item.parents; + hotCurrentChildModule = moduleId; + try { + $require$(moduleId); + } catch (err) { + if (typeof item.errorHandler === "function") { + try { + item.errorHandler(err); + } catch (err2) { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-error-handler-errored", + moduleId: moduleId, + error: err2, + originalError: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err2; + } + if (!error) error = err; + } + } else { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-errored", + moduleId: moduleId, + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } + } + } + + // handle errors in accept handlers and self accepted module load + if (error) { + hotSetStatus("fail"); + return Promise.reject(error); + } + + if (hotQueuedInvalidatedModules) { + return hotApplyInternal(options).then(function(list) { + outdatedModules.forEach(function(moduleId) { + if (list.indexOf(moduleId) < 0) list.push(moduleId); + }); + return list; + }); + } + + hotSetStatus("idle"); + return new Promise(function(resolve) { + resolve(outdatedModules); + }); + } + + function hotApplyInvalidatedModules() { + if (hotQueuedInvalidatedModules) { + if (!hotUpdate) hotUpdate = {}; + hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); + hotQueuedInvalidatedModules = undefined; + return true; + } + } + + function hotApplyInvalidatedModule(moduleId) { + if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) + hotUpdate[moduleId] = modules[moduleId]; + } +}; + + +/***/ }), + +/***/ 69575: +/***/ ((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__(92402); +const { RawSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); +const ModuleHotAcceptDependency = __webpack_require__(29018); +const ModuleHotDeclineDependency = __webpack_require__(60482); +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); +const ParserHelpers = __webpack_require__(23999); + +module.exports = class HotModuleReplacementPlugin { + constructor(options) { + this.options = options || {}; + this.multiStep = this.options.multiStep; + this.fullBuildTimeout = this.options.fullBuildTimeout || 200; + this.requestTimeout = this.options.requestTimeout || 10000; + } + + apply(compiler) { + const multiStep = this.multiStep; + const fullBuildTimeout = this.fullBuildTimeout; + const requestTimeout = this.requestTimeout; + const hotUpdateChunkFilename = + compiler.options.output.hotUpdateChunkFilename; + const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; + compiler.hooks.additionalPass.tapAsync( + "HotModuleReplacementPlugin", + callback => { + if (multiStep) return setTimeout(callback, fullBuildTimeout); + return callback(); + } + ); + + const addParserPlugins = (parser, parserOptions) => { + parser.hooks.expression + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.h()" + ) + ); + parser.hooks.evaluateTypeof + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.evaluateToString("string") + ); + parser.hooks.evaluateIdentifier.for("module.hot").tap( + { + name: "HotModuleReplacementPlugin", + before: "NodeStuffPlugin" + }, + expr => { + return ParserHelpers.evaluateToIdentifier( + "module.hot", + !!parser.state.compilation.hotUpdateChunkTemplate + )(expr); + } + ); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.call + .for("module.hot.accept") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length >= 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + let requests = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); + } + if (params.length > 0) { + params.forEach((param, idx) => { + const request = param.string; + const dep = new ModuleHotAcceptDependency(request, param.range); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + requests.push(request); + }); + if (expr.arguments.length > 1) { + parser.hooks.hotAcceptCallback.call( + expr.arguments[1], + requests + ); + parser.walkExpression(expr.arguments[1]); // other args are ignored + return true; + } else { + parser.hooks.hotAcceptWithoutCallback.call(expr, requests); + return true; + } + } + } + }); + parser.hooks.call + .for("module.hot.decline") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length === 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); + } + params.forEach((param, idx) => { + const dep = new ModuleHotDeclineDependency( + param.string, + param.range + ); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + }); + } + }); + parser.hooks.expression + .for("module.hot") + .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); + }; + + compiler.hooks.compilation.tap( + "HotModuleReplacementPlugin", + (compilation, { normalModuleFactory }) => { + // This applies the HMR plugin only to the targeted compiler + // It should not affect child compilations + if (compilation.compiler !== compiler) return; + + const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; + if (!hotUpdateChunkTemplate) return; + + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotAcceptDependency, + new ModuleHotAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleHotDeclineDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotDeclineDependency, + new ModuleHotDeclineDependency.Template() + ); + + compilation.hooks.record.tap( + "HotModuleReplacementPlugin", + (compilation, records) => { + if (records.hash === compilation.hash) return; + records.hash = compilation.hash; + records.moduleHashs = {}; + for (const module of compilation.modules) { + const identifier = module.identifier(); + records.moduleHashs[identifier] = module.hash; + } + records.chunkHashs = {}; + for (const chunk of compilation.chunks) { + records.chunkHashs[chunk.id] = chunk.hash; + } + records.chunkModuleIds = {}; + for (const chunk of compilation.chunks) { + records.chunkModuleIds[chunk.id] = Array.from( + chunk.modulesIterable, + m => m.id + ); + } + } + ); + let initialPass = false; + let recompilation = false; + compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { + let records = compilation.records; + if (!records) { + initialPass = true; + return; + } + if (!records.hash) initialPass = true; + const preHash = records.preHash || "x"; + const prepreHash = records.prepreHash || "x"; + if (preHash === compilation.hash) { + recompilation = true; + compilation.modifyHash(prepreHash); + return; + } + records.prepreHash = records.hash || "x"; + records.preHash = compilation.hash; + compilation.modifyHash(records.prepreHash); + }); + compilation.hooks.shouldGenerateChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return false; + } + ); + compilation.hooks.needAdditionalPass.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return true; + } + ); + compilation.hooks.additionalChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + const records = compilation.records; + if (records.hash === compilation.hash) return; + if ( + !records.moduleHashs || + !records.chunkHashs || + !records.chunkModuleIds + ) + return; + for (const module of compilation.modules) { + const identifier = module.identifier(); + let hash = module.hash; + module.hotUpdate = records.moduleHashs[identifier] !== hash; + } + const hotUpdateMainContent = { + h: compilation.hash, + c: {} + }; + for (const key of Object.keys(records.chunkHashs)) { + const chunkId = isNaN(+key) ? key : +key; + const currentChunk = compilation.chunks.find( + chunk => `${chunk.id}` === key + ); + if (currentChunk) { + const newModules = currentChunk + .getModules() + .filter(module => module.hotUpdate); + const allModules = new Set(); + for (const module of currentChunk.modulesIterable) { + allModules.add(module.id); + } + const removedModules = records.chunkModuleIds[chunkId].filter( + id => !allModules.has(id) + ); + if (newModules.length > 0 || removedModules.length > 0) { + const source = hotUpdateChunkTemplate.render( + chunkId, + newModules, + removedModules, + compilation.hash, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + const { + path: filename, + info: assetInfo + } = compilation.getPathWithInfo(hotUpdateChunkFilename, { + hash: records.hash, + chunk: currentChunk + }); + compilation.additionalChunkAssets.push(filename); + compilation.emitAsset( + filename, + source, + Object.assign({ hotModuleReplacement: true }, assetInfo) + ); + hotUpdateMainContent.c[chunkId] = true; + currentChunk.files.push(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } else { + hotUpdateMainContent.c[chunkId] = false; + } + } + const source = new RawSource(JSON.stringify(hotUpdateMainContent)); + const { + path: filename, + info: assetInfo + } = compilation.getPathWithInfo(hotUpdateMainFilename, { + hash: records.hash + }); + compilation.emitAsset( + filename, + source, + Object.assign({ hotModuleReplacement: true }, assetInfo) + ); + } + ); + + const mainTemplate = compilation.mainTemplate; + + mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => { + hash.update("HotMainTemplateDecorator"); + }); + + mainTemplate.hooks.moduleRequire.tap( + "HotModuleReplacementPlugin", + (_, chunk, hash, varModuleId) => { + return `hotCreateRequire(${varModuleId})`; + } + ); + + mainTemplate.hooks.requireExtensions.tap( + "HotModuleReplacementPlugin", + source => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push( + mainTemplate.requireFn + + ".h = function() { return hotCurrentHash; };" + ); + return Template.asString(buf); + } + ); + + const needChunkLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + + mainTemplate.hooks.bootstrap.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash) => { + source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash); + return Template.asString([ + source, + "", + hotInitCode + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hash\$/g, JSON.stringify(hash)) + .replace(/\$requestTimeout\$/g, requestTimeout) + .replace( + /\/\*foreachInstalledChunks\*\//g, + needChunkLoadingCode(chunk) + ? "for(var chunkId in installedChunks)" + : `var chunkId = ${JSON.stringify(chunk.id)};` + ) + ]); + } + ); + + mainTemplate.hooks.globalHash.tap( + "HotModuleReplacementPlugin", + () => true + ); + + mainTemplate.hooks.currentHash.tap( + "HotModuleReplacementPlugin", + (_, length) => { + if (isFinite(length)) { + return `hotCurrentHash.substr(0, ${length})`; + } else { + return "hotCurrentHash"; + } + } + ); + + mainTemplate.hooks.moduleObj.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash, varModuleId) => { + return Template.asString([ + `${source},`, + `hot: hotCreateModule(${varModuleId}),`, + "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", + "children: []" + ]); + } + ); + + // TODO add HMR support for javascript/esm + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HotModuleReplacementPlugin", addParserPlugins); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("HotModuleReplacementPlugin", addParserPlugins); + + compilation.hooks.normalModuleLoader.tap( + "HotModuleReplacementPlugin", + context => { + context.hot = true; + } + ); + } + ); + } +}; + +const hotInitCode = Template.getFunctionContent( + __webpack_require__(65217) +); + + +/***/ }), + +/***/ 26782: +/***/ ((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__(2919); + +class HotUpdateChunk extends Chunk { + constructor() { + super(); + /** @type {(string|number)[]} */ + this.removedModules = undefined; + } +} + +module.exports = HotUpdateChunk; + + +/***/ }), + +/***/ 66062: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); +const HotUpdateChunk = __webpack_require__(26782); +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(92402); + +module.exports = class HotUpdateChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + modules: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "hash", + "id", + "moduleTemplate", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; + } + + render( + id, + modules, + removedModules, + hash, + moduleTemplate, + dependencyTemplates + ) { + const hotUpdateChunk = new HotUpdateChunk(); + hotUpdateChunk.id = id; + hotUpdateChunk.setModules(modules); + hotUpdateChunk.removedModules = removedModules; + const modulesSource = Template.renderChunkModules( + hotUpdateChunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates + ); + const core = this.hooks.modules.call( + modulesSource, + modules, + removedModules, + moduleTemplate, + dependencyTemplates + ); + const source = this.hooks.render.call( + core, + modules, + removedModules, + hash, + id, + moduleTemplate, + dependencyTemplates + ); + return source; + } + + updateHash(hash) { + hash.update("HotUpdateChunkTemplate"); + hash.update("1"); + this.hooks.hash.call(hash); + } +}; + + +/***/ }), + +/***/ 41364: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(69667); + +/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ + +class IgnorePlugin { + /** + * @param {IgnorePluginOptions} options IgnorePlugin options + */ + constructor(options) { + // TODO webpack 5 remove this compat-layer + if (arguments.length > 1 || options instanceof RegExp) { + options = { + resourceRegExp: arguments[0], + contextRegExp: arguments[1] + }; + } + + validateOptions(schema, options, "IgnorePlugin"); + this.options = options; + + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); + } + + /** + * Note that if "contextRegExp" is given, both the "resourceRegExp" + * and "contextRegExp" have to match. + * + * @param {TODO} result result + * @returns {TODO|null} returns result or null if result should be ignored + */ + checkIgnore(result) { + if (!result) return result; + + if ( + "checkResource" in this.options && + this.options.checkResource && + this.options.checkResource(result.request, result.context) + ) { + // TODO webpack 5 remove checkContext, as checkResource already gets context + if ("checkContext" in this.options && this.options.checkContext) { + if (this.options.checkContext(result.context)) { + return null; + } + } else { + return null; + } + } + + if ( + "resourceRegExp" in this.options && + this.options.resourceRegExp && + this.options.resourceRegExp.test(result.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(result.context)) { + return null; + } + } else { + return null; + } + } + + return result; + } + + /** + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => { + nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); + }); + compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => { + cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); + }); + } +} + +module.exports = IgnorePlugin; + + +/***/ }), + +/***/ 98509: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { RawSource, ReplaceSource } = __webpack_require__(53665); + +// TODO: clean up this file +// replace with newer constructs + +// TODO: remove DependencyVariables and replace them with something better + +class JavascriptGenerator { + generate(module, dependencyTemplates, runtimeTemplate) { + const originalSource = module.originalSource(); + if (!originalSource) { + return new RawSource("throw new Error('No source available');"); + } + + const source = new ReplaceSource(originalSource); + + this.sourceBlock( + module, + module, + [], + dependencyTemplates, + source, + runtimeTemplate + ); + + return source; + } + + sourceBlock( + module, + block, + availableVars, + dependencyTemplates, + source, + runtimeTemplate + ) { + for (const dependency of block.dependencies) { + this.sourceDependency( + dependency, + dependencyTemplates, + source, + runtimeTemplate + ); + } + + /** + * Get the variables of all blocks that we need to inject. + * These will contain the variable name and its expression. + * The name will be added as a parameter in a IIFE the expression as its value. + */ + const vars = block.variables.reduce((result, value) => { + const variable = this.sourceVariables( + value, + availableVars, + dependencyTemplates, + runtimeTemplate + ); + + if (variable) { + result.push(variable); + } + + return result; + }, []); + + /** + * if we actually have variables + * this is important as how #splitVariablesInUniqueNamedChunks works + * it will always return an array in an array which would lead to a IIFE wrapper around + * a module if we do this with an empty vars array. + */ + if (vars.length > 0) { + /** + * Split all variables up into chunks of unique names. + * e.g. imagine you have the following variable names that need to be injected: + * [foo, bar, baz, foo, some, more] + * we can not inject "foo" twice, therefore we just make two IIFEs like so: + * (function(foo, bar, baz){ + * (function(foo, some, more){ + * … + * }(…)); + * }(…)); + * + * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this: + * [[foo, bar, baz], [foo, some, more]] + */ + const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks( + vars + ); + + // create all the beginnings of IIFEs + const functionWrapperStarts = injectionVariableChunks.map( + variableChunk => { + return this.variableInjectionFunctionWrapperStartCode( + variableChunk.map(variable => variable.name) + ); + } + ); + + // and all the ends + const functionWrapperEnds = injectionVariableChunks.map(variableChunk => { + return this.variableInjectionFunctionWrapperEndCode( + module, + variableChunk.map(variable => variable.expression), + block + ); + }); + + // join them to one big string + const varStartCode = functionWrapperStarts.join(""); + + // reverse the ends first before joining them, as the last added must be the inner most + const varEndCode = functionWrapperEnds.reverse().join(""); + + // if we have anything, add it to the source + if (varStartCode && varEndCode) { + const start = block.range ? block.range[0] : -10; + const end = block.range + ? block.range[1] + : module.originalSource().size() + 1; + source.insert(start + 0.5, varStartCode); + source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); + } + } + + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + availableVars.concat(vars), + dependencyTemplates, + source, + runtimeTemplate + ); + } + } + + sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { + const template = dependencyTemplates.get(dependency.constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } + template.apply(dependency, source, runtimeTemplate, dependencyTemplates); + } + + sourceVariables( + variable, + availableVars, + dependencyTemplates, + runtimeTemplate + ) { + const name = variable.name; + const expr = variable.expressionSource( + dependencyTemplates, + runtimeTemplate + ); + + if ( + availableVars.some( + v => v.name === name && v.expression.source() === expr.source() + ) + ) { + return; + } + return { + name: name, + expression: expr + }; + } + + /* + * creates the start part of a IIFE around the module to inject a variable name + * (function(…){ <- this part + * }.call(…)) + */ + variableInjectionFunctionWrapperStartCode(varNames) { + const args = varNames.join(", "); + return `/* WEBPACK VAR INJECTION */(function(${args}) {`; + } + + contextArgument(module, block) { + if (this === block) { + return module.exportsArgument; + } + return "this"; + } + + /* + * creates the end part of a IIFE around the module to inject a variable name + * (function(…){ + * }.call(…)) <- this part + */ + variableInjectionFunctionWrapperEndCode(module, varExpressions, block) { + const firstParam = this.contextArgument(module, block); + const furtherParams = varExpressions.map(e => e.source()).join(", "); + return `}.call(${firstParam}, ${furtherParams}))`; + } + + splitVariablesInUniqueNamedChunks(vars) { + const startState = [[]]; + return vars.reduce((chunks, variable) => { + const current = chunks[chunks.length - 1]; + // check if variable with same name exists already + // if so create a new chunk of variables. + const variableNameAlreadyExists = current.some( + v => v.name === variable.name + ); + + if (variableNameAlreadyExists) { + // start new chunk with current variable + chunks.push([variable]); + } else { + // else add it to current chunk + current.push(variable); + } + return chunks; + }, startState); + } +} + +module.exports = JavascriptGenerator; + + +/***/ }), + +/***/ 10339: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Parser = __webpack_require__(70558); +const Template = __webpack_require__(96066); +const { ConcatSource } = __webpack_require__(53665); +const JavascriptGenerator = __webpack_require__(98509); +const createHash = __webpack_require__(15660); + +class JavascriptModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "JavascriptModulesPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("javascript/auto") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "auto"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "script"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/esm") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "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.mainTemplate.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const hash = options.hash; + const fullHash = options.fullHash; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; + + const filenameTemplate = + chunk.filenameTemplate || outputOptions.filename; + + const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); + + result.push({ + render: () => + compilation.mainTemplate.render( + hash, + chunk, + moduleTemplates.javascript, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + noChunkHash: !useChunkHash, + contentHashType: "javascript", + chunk + }, + identifier: `chunk${chunk.id}`, + hash: useChunkHash ? chunk.hash : fullHash + }); + return result; + } + ); + compilation.mainTemplate.hooks.modules.tap( + "JavascriptModulesPlugin", + (source, chunk, hash, moduleTemplate, dependencyTemplates) => { + return Template.renderChunkModules( + chunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates, + "/******/ " + ); + } + ); + compilation.chunkTemplate.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; + const filenameTemplate = + chunk.filenameTemplate || outputOptions.chunkFilename; + + result.push({ + render: () => + this.renderJavascript( + compilation.chunkTemplate, + chunk, + moduleTemplates.javascript, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + chunk, + contentHashType: "javascript" + }, + identifier: `chunk${chunk.id}`, + hash: chunk.hash + }); + + return result; + } + ); + compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { + const outputOptions = compilation.outputOptions; + const { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } = outputOptions; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + const template = chunk.hasRuntime() + ? compilation.mainTemplate + : compilation.chunkTemplate; + hash.update(`${chunk.id} `); + hash.update(chunk.ids ? chunk.ids.join(",") : ""); + template.updateHashForChunk( + hash, + chunk, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + for (const m of chunk.modulesIterable) { + if (typeof m.source === "function") { + hash.update(m.hash); + } + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.javascript = digest.substr(0, hashDigestLength); + }); + } + ); + } + + renderJavascript(chunkTemplate, chunk, moduleTemplate, dependencyTemplates) { + const moduleSources = Template.renderChunkModules( + chunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates + ); + const core = chunkTemplate.hooks.modules.call( + moduleSources, + chunk, + moduleTemplate, + dependencyTemplates + ); + let source = chunkTemplate.hooks.render.call( + core, + chunk, + moduleTemplate, + dependencyTemplates + ); + if (chunk.hasEntryModule()) { + source = chunkTemplate.hooks.renderWithEntry.call(source, chunk); + } + chunk.rendered = true; + return new ConcatSource(source, ";"); + } +} + +module.exports = JavascriptModulesPlugin; + + +/***/ }), + +/***/ 72806: +/***/ ((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 } = __webpack_require__(53665); + +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 +}; + +class JsonGenerator { + generate(module, dependencyTemplates, runtimeTemplate) { + const source = new ConcatSource(); + const data = module.buildInfo.jsonData; + if (data === undefined) { + return new RawSource( + runtimeTemplate.missingModuleStatement({ + request: module.rawRequest + }) + ); + } + let finalJson; + if ( + Array.isArray(module.buildMeta.providedExports) && + !module.isUsed("default") + ) { + // Only some exports are used: We can optimize here, by only generating a part of the JSON + const reducedJson = {}; + for (const exportName of module.buildMeta.providedExports) { + if (exportName === "default") continue; + const used = module.isUsed(exportName); + if (used) { + reducedJson[used] = data[exportName]; + } + } + finalJson = reducedJson; + } else { + finalJson = data; + } + // Use JSON because JSON.parse() is much faster than JavaScript evaluation + const jsonSource = JSON.stringify(stringifySafe(finalJson)); + const jsonExpr = `JSON.parse(${jsonSource})`; + source.add(`${module.moduleArgument}.exports = ${jsonExpr};`); + return source; + } +} + +module.exports = JsonGenerator; + + +/***/ }), + +/***/ 2859: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const JsonParser = __webpack_require__(5807); +const JsonGenerator = __webpack_require__(72806); + +class JsonModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "JsonModulesPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonParser(); + }); + normalModuleFactory.hooks.createGenerator + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonGenerator(); + }); + } + ); + } +} + +module.exports = JsonModulesPlugin; + + +/***/ }), + +/***/ 5807: +/***/ ((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__(48335); +const JsonExportsDependency = __webpack_require__(54396); + +class JsonParser { + constructor(options) { + this.options = options; + } + + parse(source, state) { + const data = parseJson(source[0] === "\ufeff" ? source.slice(1) : source); + state.module.buildInfo.jsonData = data; + state.module.buildMeta.exportsType = "named"; + if (typeof data === "object" && data) { + state.module.addDependency(new JsonExportsDependency(Object.keys(data))); + } + state.module.addDependency(new JsonExportsDependency(["default"])); + return state; + } +} + +module.exports = JsonParser; + + +/***/ }), + +/***/ 30735: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const asyncLib = __webpack_require__(36386); +const SingleEntryDependency = __webpack_require__(84828); + +class LibManifestPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.emit.tapAsync( + "LibManifestPlugin", + (compilation, callback) => { + asyncLib.forEach( + compilation.chunks, + (chunk, callback) => { + if (!chunk.isOnlyInitial()) { + callback(); + return; + } + const targetPath = compilation.getPath(this.options.path, { + hash: compilation.hash, + chunk + }); + const name = + this.options.name && + compilation.getPath(this.options.name, { + hash: compilation.hash, + chunk + }); + const manifest = { + name, + type: this.options.type, + content: Array.from(chunk.modulesIterable, module => { + if ( + this.options.entryOnly && + !module.reasons.some( + r => r.dependency instanceof SingleEntryDependency + ) + ) { + return; + } + if (module.libIdent) { + const ident = module.libIdent({ + context: this.options.context || compiler.options.context + }); + if (ident) { + return { + ident, + data: { + id: module.id, + buildMeta: module.buildMeta + } + }; + } + } + }) + .filter(Boolean) + .reduce((obj, item) => { + obj[item.ident] = item.data; + return obj; + }, Object.create(null)) + }; + // Apply formatting to content if format flag is true; + const manifestContent = this.options.format + ? JSON.stringify(manifest, null, 2) + : JSON.stringify(manifest); + const content = Buffer.from(manifestContent, "utf8"); + compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { + if (err) return callback(err); + compiler.outputFileSystem.writeFile( + targetPath, + content, + callback + ); + }); + }, + callback + ); + } + ); + } +} +module.exports = LibManifestPlugin; + + +/***/ }), + +/***/ 65237: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const SetVarMainTemplatePlugin = __webpack_require__(37098); + +/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("./Compiler")} Compiler */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +/** + * @param {string=} base the path prefix + * @param {string|string[]|LibraryCustomUmdObject} accessor the accessor + * @param {"amd" | "commonjs" | "root"} umdProperty property used when a custom umd object is provided + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, umdProperty, joinWith = "; ") => { + const normalizedAccessor = + typeof accessor === "object" && !Array.isArray(accessor) + ? accessor[umdProperty] + : accessor; + const accessors = Array.isArray(normalizedAccessor) + ? normalizedAccessor + : [normalizedAccessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) { + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + } + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +class LibraryTemplatePlugin { + /** + * @param {string|string[]|LibraryCustomUmdObject} name name of library + * @param {string} target type of library + * @param {boolean} umdNamedDefine setting this to true will name the UMD module + * @param {string|TODO} auxiliaryComment comment in the UMD wrapper + * @param {string|string[]} exportProperty which export should be exposed as library + */ + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.name = name; + this.target = target; + this.umdNamedDefine = umdNamedDefine; + this.auxiliaryComment = auxiliaryComment; + this.exportProperty = exportProperty; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { + if (this.exportProperty) { + const ExportPropertyMainTemplatePlugin = __webpack_require__(50471); + new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( + compilation + ); + } + switch (this.target) { + case "var": + if ( + !this.name || + (typeof this.name === "object" && !Array.isArray(this.name)) + ) { + throw new Error( + "library name must be set and not an UMD custom object for non-UMD target" + ); + } + new SetVarMainTemplatePlugin( + `var ${accessorAccess(undefined, this.name, "root")}`, + false + ).apply(compilation); + break; + case "assign": + new SetVarMainTemplatePlugin( + accessorAccess(undefined, this.name, "root"), + false + ).apply(compilation); + break; + case "this": + case "self": + case "window": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess(this.target, this.name, "root"), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin(this.target, true).apply(compilation); + } + break; + case "global": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess( + compilation.runtimeTemplate.outputOptions.globalObject, + this.name, + "root" + ), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin( + compilation.runtimeTemplate.outputOptions.globalObject, + true + ).apply(compilation); + } + break; + case "commonjs": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess("exports", this.name, "commonjs"), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin("exports", true).apply(compilation); + } + break; + case "commonjs2": + case "commonjs-module": + new SetVarMainTemplatePlugin("module.exports", false).apply( + compilation + ); + break; + case "amd": + case "amd-require": { + const AmdMainTemplatePlugin = __webpack_require__(9701); + if (this.name && typeof this.name !== "string") { + throw new Error("library name must be a string for amd target"); + } + new AmdMainTemplatePlugin({ + name: this.name, + requireAsWrapper: this.target === "amd-require" + }).apply(compilation); + break; + } + case "umd": + case "umd2": { + const UmdMainTemplatePlugin = __webpack_require__(75374); + new UmdMainTemplatePlugin(this.name, { + optionalAmdExternalAsGlobal: this.target === "umd2", + namedDefine: this.umdNamedDefine, + auxiliaryComment: this.auxiliaryComment + }).apply(compilation); + break; + } + case "jsonp": { + const JsonpExportMainTemplatePlugin = __webpack_require__(13732); + if (typeof this.name !== "string") + throw new Error("library name must be a string for jsonp target"); + new JsonpExportMainTemplatePlugin(this.name).apply(compilation); + break; + } + case "system": { + const SystemMainTemplatePlugin = __webpack_require__(97365); + new SystemMainTemplatePlugin({ + name: this.name + }).apply(compilation); + break; + } + default: + throw new Error(`${this.target} is not a valid Library target`); + } + }); + } +} + +module.exports = LibraryTemplatePlugin; + + +/***/ }), + +/***/ 48775: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ModuleFilenameHelpers = __webpack_require__(71474); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(4994); + +/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ + +class LoaderOptionsPlugin { + /** + * @param {LoaderOptionsPluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options || {}, "Loader Options Plugin"); + + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; + } + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderOptionsPlugin", + (context, module) => { + const resource = module.resource; + if (!resource) return; + const i = resource.indexOf("?"); + if ( + ModuleFilenameHelpers.matchObject( + options, + i < 0 ? resource : resource.substr(0, i) + ) + ) { + for (const key of Object.keys(options)) { + if (key === "include" || key === "exclude" || key === "test") { + continue; + } + context[key] = options[key]; + } + } + } + ); + }); + } +} + +module.exports = LoaderOptionsPlugin; + + +/***/ }), + +/***/ 95154: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class LoaderTargetPlugin { + constructor(target) { + this.target = target; + } + + apply(compiler) { + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; + } + ); + }); + } +} + +module.exports = LoaderTargetPlugin; + + +/***/ }), + +/***/ 43626: +/***/ ((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, + PrefixSource, + RawSource +} = __webpack_require__(53665); +const { + Tapable, + SyncWaterfallHook, + SyncHook, + SyncBailHook +} = __webpack_require__(92402); +const Template = __webpack_require__(96066); + +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map} dependencyTemplates + */ + +// require function shortcuts: +// __webpack_require__.s = the module id of the entry point +// __webpack_require__.c = the module cache +// __webpack_require__.m = the module functions +// __webpack_require__.p = the bundle public path +// __webpack_require__.i = the identity function used for harmony imports +// __webpack_require__.e = the chunk ensure function +// __webpack_require__.d = the exported property define getter function +// __webpack_require__.o = Object.prototype.hasOwnProperty.call +// __webpack_require__.r = define compatibility on export +// __webpack_require__.t = create a fake namespace object +// __webpack_require__.n = compatibility get default export +// __webpack_require__.h = the webpack hash +// __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id +// __webpack_require__.oe = the uncaught error handler for the webpack runtime +// __webpack_require__.nc = the script nonce + +module.exports = class MainTemplate extends Tapable { + /** + * + * @param {TODO=} outputOptions output options for the MainTemplate + */ + constructor(outputOptions) { + super(); + /** @type {TODO?} */ + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "modules", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + moduleObj: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + requireEnsure: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "chunkIdExpression" + ]), + bootstrap: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), + require: new SyncWaterfallHook(["source", "chunk", "hash"]), + requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + beforeStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + startup: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + afterStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk", "hash"]), + moduleRequire: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + addModule: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression", + "moduleExpression" + ]), + currentHash: new SyncWaterfallHook(["source", "requestedLength"]), + assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]), + globalHashPaths: new SyncWaterfallHook(["paths"]), + globalHash: new SyncBailHook(["chunk", "paths"]), + + // TODO this should be moved somewhere else + // It's weird here + hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) + }; + this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => { + /** @type {string[]} */ + const buf = []; + if (chunk.entryModule) { + buf.push("// Load entry module and return exports"); + buf.push( + `return ${this.renderRequireFunctionForModule( + hash, + chunk, + JSON.stringify(chunk.entryModule.id) + )}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});` + ); + } + return Template.asString(buf); + }); + this.hooks.render.tap( + "MainTemplate", + (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { + const source = new ConcatSource(); + source.add("/******/ (function(modules) { // webpackBootstrap\n"); + source.add(new PrefixSource("/******/", bootstrapSource)); + source.add("/******/ })\n"); + source.add( + "/************************************************************************/\n" + ); + source.add("/******/ ("); + source.add( + this.hooks.modules.call( + new RawSource(""), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + source.add(")"); + return source; + } + ); + this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// The module cache", + "var installedModules = {};" + ]); + }); + this.hooks.require.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// Check if module is in cache", + "if(installedModules[moduleId]) {", + Template.indent("return installedModules[moduleId].exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = installedModules[moduleId] = {", + Template.indent(this.hooks.moduleObj.call("", chunk, hash, "moduleId")), + "};", + "", + Template.asString( + outputOptions.strictModuleExceptionHandling + ? [ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([ + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});`, + "threw = false;" + ]), + "} finally {", + Template.indent([ + "if(threw) delete installedModules[moduleId];" + ]), + "}" + ] + : [ + "// Execute the module function", + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});` + ] + ), + "", + "// Flag the module as loaded", + "module.l = true;", + "", + "// Return the exports of the module", + "return module.exports;" + ]); + }); + this.hooks.moduleObj.tap( + "MainTemplate", + (source, chunk, hash, varModuleId) => { + return Template.asString(["i: moduleId,", "l: false,", "exports: {}"]); + } + ); + this.hooks.requireExtensions.tap("MainTemplate", (source, chunk, hash) => { + const buf = []; + const chunkMaps = chunk.getChunkMaps(); + // Check if there are non initial chunks which need to be imported using require-ensure + if (Object.keys(chunkMaps.hash).length) { + buf.push("// This file contains only the entry chunk."); + buf.push("// The chunk loading function for additional chunks"); + buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`); + buf.push(Template.indent("var promises = [];")); + buf.push( + Template.indent( + this.hooks.requireEnsure.call("", chunk, hash, "chunkId") + ) + ); + buf.push(Template.indent("return Promise.all(promises);")); + buf.push("};"); + } else if ( + chunk.hasModuleInGraph(m => + m.blocks.some(b => b.chunkGroup && b.chunkGroup.chunks.length > 0) + ) + ) { + // There async blocks in the graph, so we need to add an empty requireEnsure + // function anyway. This can happen with multiple entrypoints. + buf.push("// The chunk loading function for additional chunks"); + buf.push("// Since all referenced chunks are already included"); + buf.push("// in this file, this function is empty here."); + buf.push(`${this.requireFn}.e = function requireEnsure() {`); + buf.push(Template.indent("return Promise.resolve();")); + buf.push("};"); + } + buf.push(""); + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${this.requireFn}.m = modules;`); + + buf.push(""); + buf.push("// expose the module cache"); + buf.push(`${this.requireFn}.c = installedModules;`); + + buf.push(""); + buf.push("// define getter function for harmony exports"); + buf.push(`${this.requireFn}.d = function(exports, name, getter) {`); + buf.push( + Template.indent([ + `if(!${this.requireFn}.o(exports, name)) {`, + Template.indent([ + "Object.defineProperty(exports, name, { enumerable: true, get: getter });" + ]), + "}" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// define __esModule on exports"); + buf.push(`${this.requireFn}.r = function(exports) {`); + buf.push( + Template.indent([ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// create a fake namespace object"); + buf.push("// mode & 1: value is a module id, require it"); + buf.push("// mode & 2: merge all properties of value into the ns"); + buf.push("// mode & 4: return value when already ns object"); + buf.push("// mode & 8|1: behave like require"); + buf.push(`${this.requireFn}.t = function(value, mode) {`); + buf.push( + Template.indent([ + `if(mode & 1) value = ${this.requireFn}(value);`, + `if(mode & 8) return value;`, + "if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;", + "var ns = Object.create(null);", + `${this.requireFn}.r(ns);`, + "Object.defineProperty(ns, 'default', { enumerable: true, value: value });", + "if(mode & 2 && typeof value != 'string') for(var key in value) " + + `${this.requireFn}.d(ns, key, function(key) { ` + + "return value[key]; " + + "}.bind(null, key));", + "return ns;" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push( + "// getDefaultExport function for compatibility with non-harmony modules" + ); + buf.push(this.requireFn + ".n = function(module) {"); + buf.push( + Template.indent([ + "var getter = module && module.__esModule ?", + Template.indent([ + "function getDefault() { return module['default']; } :", + "function getModuleExports() { return module; };" + ]), + `${this.requireFn}.d(getter, 'a', getter);`, + "return getter;" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// Object.prototype.hasOwnProperty.call"); + buf.push( + `${this.requireFn}.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` + ); + + const publicPath = this.getPublicPath({ + hash: hash + }); + buf.push(""); + buf.push("// __webpack_public_path__"); + buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`); + return Template.asString(buf); + }); + + this.requireFn = "__webpack_require__"; + } + + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + + this.hooks.renderManifest.call(result, options); + + return result; + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {string[]} the generated source of the bootstrap code + */ + renderBootstrap(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = []; + buf.push( + this.hooks.bootstrap.call( + "", + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + buf.push(this.hooks.localVars.call("", chunk, hash)); + buf.push(""); + buf.push("// The require function"); + buf.push(`function ${this.requireFn}(moduleId) {`); + buf.push(Template.indent(this.hooks.require.call("", chunk, hash))); + buf.push("}"); + buf.push(""); + buf.push( + Template.asString(this.hooks.requireExtensions.call("", chunk, hash)) + ); + buf.push(""); + buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); + const afterStartupCode = Template.asString( + this.hooks.afterStartup.call("", chunk, hash) + ); + if (afterStartupCode) { + // TODO webpack 5: this is a bit hacky to avoid a breaking change + // change it to a better way + buf.push("var startupResult = (function() {"); + } + buf.push(Template.asString(this.hooks.startup.call("", chunk, hash))); + if (afterStartupCode) { + buf.push("})();"); + buf.push(afterStartupCode); + buf.push("return startupResult;"); + } + return buf; + } + + /** + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {ConcatSource} the newly generated source from rendering + */ + render(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = this.renderBootstrap( + hash, + chunk, + moduleTemplate, + dependencyTemplates + ); + let source = this.hooks.render.call( + new OriginalSource( + Template.prefix(buf, " \t") + "\n", + "webpack/bootstrap" + ), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ); + if (chunk.hasEntryModule()) { + source = this.hooks.renderWithEntry.call(source, chunk, hash); + } + if (!source) { + throw new Error( + "Compiler error: MainTemplate plugin 'render' should return something" + ); + } + chunk.rendered = true; + return new ConcatSource(source, ";"); + } + + /** + * + * @param {string} hash hash for render fn + * @param {Chunk} chunk Chunk instance for require + * @param {(number|string)=} varModuleId module id + * @returns {TODO} the moduleRequire hook call return signature + */ + renderRequireFunctionForModule(hash, chunk, varModuleId) { + return this.hooks.moduleRequire.call( + this.requireFn, + chunk, + hash, + varModuleId + ); + } + + /** + * + * @param {string} hash hash for render add fn + * @param {Chunk} chunk Chunk instance for require add fn + * @param {(string|number)=} varModuleId module id + * @param {Module} varModule Module instance + * @returns {TODO} renderAddModule call + */ + renderAddModule(hash, chunk, varModuleId, varModule) { + return this.hooks.addModule.call( + `modules[${varModuleId}] = ${varModule};`, + chunk, + hash, + varModuleId, + varModule + ); + } + + /** + * + * @param {string} hash string hash + * @param {number=} length length + * @returns {string} call hook return + */ + renderCurrentHashCode(hash, length) { + length = length || Infinity; + return this.hooks.currentHash.call( + JSON.stringify(hash.substr(0, length)), + length + ); + } + + /** + * + * @param {object} options get public path options + * @returns {string} hook call + */ + getPublicPath(options) { + return this.hooks.assetPath.call( + this.outputOptions.publicPath || "", + options + ); + } + + getAssetPath(path, options) { + return this.hooks.assetPath.call(path, options); + } + + getAssetPathWithInfo(path, options) { + const assetInfo = {}; + // TODO webpack 5: refactor assetPath hook to receive { path, info } object + const newPath = this.hooks.assetPath.call(path, options, assetInfo); + return { path: newPath, info: assetInfo }; + } + + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("maintemplate"); + hash.update("3"); + this.hooks.hash.call(hash); + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + for (const line of this.renderBootstrap( + "0000", + chunk, + moduleTemplate, + dependencyTemplates + )) { + hash.update(line); + } + } + + useChunkHash(chunk) { + const paths = this.hooks.globalHashPaths.call([]); + return !this.hooks.globalHash.call(chunk, paths); + } +}; + + +/***/ }), + +/***/ 50332: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +module.exports = __webpack_require__(32327); + + +/***/ }), + +/***/ 75993: +/***/ ((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__(31669); + +const DependenciesBlock = __webpack_require__(16071); +const ModuleReason = __webpack_require__(44576); +const SortableSet = __webpack_require__(50071); +const Template = __webpack_require__(96066); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const sortById = (a, b) => { + return a.id - b.id; +}; + +const sortByDebugId = (a, b) => { + return a.debugId - b.debugId; +}; + +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + +class Module extends DependenciesBlock { + constructor(type, context = null) { + super(); + /** @type {string} */ + this.type = type; + /** @type {string} */ + this.context = context; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Hash + /** @type {string} */ + this.hash = undefined; + /** @type {string} */ + this.renderedHash = undefined; + + // Info from Factory + /** @type {TODO} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {object} */ + this.factoryMeta = {}; + + // Info from Build + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {object} */ + this.buildMeta = undefined; + /** @type {object} */ + this.buildInfo = undefined; + + // Graph (per Compilation) + /** @type {ModuleReason[]} */ + this.reasons = []; + /** @type {SortableSet} */ + this._chunks = new SortableSet(undefined, sortById); + + // Info from Compilation (per Compilation) + /** @type {number|string} */ + this.id = null; + /** @type {number} */ + this.index = null; + /** @type {number} */ + this.index2 = null; + /** @type {number} */ + this.depth = null; + /** @type {Module} */ + this.issuer = null; + /** @type {undefined | object} */ + this.profile = undefined; + /** @type {boolean} */ + this.prefetched = false; + /** @type {boolean} */ + this.built = false; + + // Info from Optimization (per Compilation) + /** @type {null | boolean} */ + this.used = null; + /** @type {false | true | string[]} */ + this.usedExports = null; + /** @type {(string | OptimizationBailoutFunction)[]} */ + this.optimizationBailout = []; + + // delayed operations + /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ + this._rewriteChunkInReasons = undefined; + + /** @type {boolean} */ + this.useSourceMap = false; + + // info from build + this._source = null; + } + + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; + } + + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; + } + + disconnect() { + this.hash = undefined; + this.renderedHash = undefined; + + this.reasons.length = 0; + this._rewriteChunkInReasons = undefined; + this._chunks.clear(); + + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this.issuer = null; + this.profile = undefined; + this.prefetched = false; + this.built = false; + + this.used = null; + this.usedExports = null; + this.optimizationBailout.length = 0; + super.disconnect(); + } + + unseal() { + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this._chunks.clear(); + super.unseal(); + } + + setChunks(chunks) { + this._chunks = new SortableSet(chunks, sortById); + } + + addChunk(chunk) { + if (this._chunks.has(chunk)) return false; + this._chunks.add(chunk); + return true; + } + + removeChunk(chunk) { + if (this._chunks.delete(chunk)) { + chunk.removeModule(this); + return true; + } + return false; + } + + isInChunk(chunk) { + return this._chunks.has(chunk); + } + + isEntryModule() { + for (const chunk of this._chunks) { + if (chunk.entryModule === this) return true; + } + return false; + } + + get optional() { + return ( + this.reasons.length > 0 && + this.reasons.every(r => r.dependency && r.dependency.optional) + ); + } + + /** + * @returns {Chunk[]} all chunks which contain the module + */ + getChunks() { + return Array.from(this._chunks); + } + + getNumberOfChunks() { + return this._chunks.size; + } + + get chunksIterable() { + return this._chunks; + } + + hasEqualsChunks(otherModule) { + if (this._chunks.size !== otherModule._chunks.size) return false; + this._chunks.sortWith(sortByDebugId); + otherModule._chunks.sortWith(sortByDebugId); + const a = this._chunks[Symbol.iterator](); + const b = otherModule._chunks[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done) return true; + if (aItem.value !== bItem.value) return false; + } + } + + addReason(module, dependency, explanation) { + this.reasons.push(new ModuleReason(module, dependency, explanation)); + } + + removeReason(module, dependency) { + for (let i = 0; i < this.reasons.length; i++) { + let r = this.reasons[i]; + if (r.module === module && r.dependency === dependency) { + this.reasons.splice(i, 1); + return true; + } + } + return false; + } + + hasReasonForChunk(chunk) { + if (this._rewriteChunkInReasons) { + for (const operation of this._rewriteChunkInReasons) { + this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + } + this._rewriteChunkInReasons = undefined; + } + for (let i = 0; i < this.reasons.length; i++) { + if (this.reasons[i].hasChunk(chunk)) return true; + } + return false; + } + + hasReasons() { + return this.reasons.length > 0; + } + + rewriteChunkInReasons(oldChunk, newChunks) { + // This is expensive. Delay operation until we really need the data + if (this._rewriteChunkInReasons === undefined) { + this._rewriteChunkInReasons = []; + } + this._rewriteChunkInReasons.push({ + oldChunk, + newChunks + }); + } + + _doRewriteChunkInReasons(oldChunk, newChunks) { + for (let i = 0; i < this.reasons.length; i++) { + this.reasons[i].rewriteChunks(oldChunk, newChunks); + } + } + + /** + * @param {string=} exportName the name of the export + * @returns {boolean|string} false if the export isn't used, true if no exportName is provided and the module is used, or the name to access it if the export is used + */ + isUsed(exportName) { + if (!exportName) return this.used !== false; + if (this.used === null || this.usedExports === null) return exportName; + if (!this.used) return false; + if (!this.usedExports) return false; + if (this.usedExports === true) return exportName; + let idx = this.usedExports.indexOf(exportName); + if (idx < 0) return false; + + // Mangle export name if possible + if (this.isProvided(exportName)) { + if (this.buildMeta.exportsType === "namespace") { + return Template.numberToIdentifer(idx); + } + if ( + this.buildMeta.exportsType === "named" && + !this.usedExports.includes("default") + ) { + return Template.numberToIdentifer(idx); + } + } + return exportName; + } + + isProvided(exportName) { + if (!Array.isArray(this.buildMeta.providedExports)) return null; + return this.buildMeta.providedExports.includes(exportName); + } + + toString() { + return `Module[${this.id || this.debugId}]`; + } + + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(`${this.id}`); + hash.update(JSON.stringify(this.usedExports)); + super.updateHash(hash); + } + + sortItems(sortChunks) { + super.sortItems(); + if (sortChunks) this._chunks.sort(); + this.reasons.sort((a, b) => { + if (a.module === b.module) return 0; + if (!a.module) return -1; + if (!b.module) return 1; + return sortById(a.module, b.module); + }); + if (Array.isArray(this.usedExports)) { + this.usedExports.sort(); + } + } + + unbuild() { + this.dependencies.length = 0; + this.blocks.length = 0; + this.variables.length = 0; + this.buildMeta = undefined; + this.buildInfo = undefined; + this.disconnect(); + } + + get arguments() { + throw new Error("Module.arguments was removed, there is no replacement."); + } + + set arguments(value) { + throw new Error("Module.arguments was removed, there is no replacement."); + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "forEachChunk", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any, Set): void} fn callback function + * @returns {void} + * @this {Module} + */ + function(fn) { + this._chunks.forEach(fn); + }, + "Module.forEachChunk: Use for(const chunk of module.chunksIterable) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "mapChunks", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any): void} fn Mapper function + * @returns {Array} Array of chunks mapped + * @this {Module} + */ + function(fn) { + return Array.from(this._chunks, fn); + }, + "Module.mapChunks: Use Array.from(module.chunksIterable, fn) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "entry", { + configurable: false, + get() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); + }, + set() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "meta", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @returns {void} + * @this {Module} + */ + function() { + return this.buildMeta; + }, + "Module.meta was renamed to Module.buildMeta" + ), + set: util.deprecate( + /** + * @deprecated + * @param {TODO} value Value + * @returns {void} + * @this {Module} + */ + function(value) { + this.buildMeta = value; + }, + "Module.meta was renamed to Module.buildMeta" + ) +}); + +/** @type {function(): string} */ +Module.prototype.identifier = null; + +/** @type {function(RequestShortener): string} */ +Module.prototype.readableIdentifier = null; + +Module.prototype.build = null; +Module.prototype.source = null; +Module.prototype.size = null; +Module.prototype.nameForCondition = null; +/** @type {null | function(Chunk): boolean} */ +Module.prototype.chunkCondition = null; +Module.prototype.updateCacheModule = null; + +module.exports = Module; + + +/***/ }), + +/***/ 12072: +/***/ ((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__(97391); +const { cutOffLoaderExecution } = __webpack_require__(80140); + +class ModuleBuildError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module build failed"; + let details = undefined; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = cutOffLoaderExecution(err.stack); + if (!err.hideStack) { + message += stack; + } else { + details = stack; + if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } else { + message = err; + } + + super(message); + + this.name = "ModuleBuildError"; + this.details = details; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleBuildError; + + +/***/ }), + +/***/ 14953: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ + +class ModuleDependencyError extends WebpackError { + /** + * Creates an instance of ModuleDependencyError. + * @param {Module} module module tied to dependency + * @param {Error} err error thrown + * @param {TODO} loc location of dependency + */ + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyError"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleDependencyError; + + +/***/ }), + +/***/ 59136: +/***/ ((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__(97391); + +module.exports = class ModuleDependencyWarning extends WebpackError { + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyWarning"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 82528: +/***/ ((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__(97391); +const { cleanUp } = __webpack_require__(80140); + +class ModuleError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module Error"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (err && typeof err === "object" && err.message) { + message += err.message; + } else if (err) { + message += err; + } + super(message); + this.name = "ModuleError"; + this.module = module; + this.error = err; + this.details = + err && typeof err === "object" && err.stack + ? cleanUp(err.stack, this.message) + : undefined; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleError; + + +/***/ }), + +/***/ 71474: +/***/ ((__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__(15660); + +const ModuleFilenameHelpers = exports; + +ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi; +ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]"; +ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi; +ModuleFilenameHelpers.RESOURCE = "[resource]"; +ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi; +ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]"; +ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi; +ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]"; +ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi; +ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi; +ModuleFilenameHelpers.LOADERS = "[loaders]"; +ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi; +ModuleFilenameHelpers.QUERY = "[query]"; +ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi; +ModuleFilenameHelpers.ID = "[id]"; +ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi; +ModuleFilenameHelpers.HASH = "[hash]"; +ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi; +ModuleFilenameHelpers.NAMESPACE = "[namespace]"; +ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi; + +const getAfter = (str, token) => { + const idx = str.indexOf(token); + return idx < 0 ? "" : str.substr(idx); +}; + +const getBefore = (str, token) => { + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.substr(0, idx); +}; + +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + 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; +}; + +ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { + const opts = Object.assign( + { + namespace: "", + moduleFilenameTemplate: "" + }, + typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + } + ); + + let absoluteResourcePath; + let hash; + let identifier; + let moduleId; + let shortIdentifier; + if (module === undefined) module = ""; + if (typeof module === "string") { + shortIdentifier = requestShortener.shorten(module); + identifier = shortIdentifier; + moduleId = ""; + absoluteResourcePath = module.split("!").pop(); + hash = getHash(identifier); + } else { + shortIdentifier = module.readableIdentifier(requestShortener); + identifier = requestShortener.shorten(module.identifier()); + moduleId = module.id; + absoluteResourcePath = module + .identifier() + .split("!") + .pop(); + hash = getHash(identifier); + } + const resource = shortIdentifier.split("!").pop(); + const loaders = getBefore(shortIdentifier, "!"); + const allLoaders = getBefore(identifier, "!"); + const query = getAfter(resource, "?"); + const resourcePath = resource.substr(0, resource.length - query.length); + if (typeof opts.moduleFilenameTemplate === "function") { + return opts.moduleFilenameTemplate({ + identifier: identifier, + shortIdentifier: shortIdentifier, + resource: resource, + resourcePath: resourcePath, + absoluteResourcePath: absoluteResourcePath, + allLoaders: allLoaders, + query: query, + moduleId: moduleId, + hash: hash, + namespace: opts.namespace + }); + } + return opts.moduleFilenameTemplate + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) + .replace( + ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, + absoluteResourcePath + ) + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) + .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) + .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) + .replace(ModuleFilenameHelpers.REGEXP_HASH, hash) + .replace(ModuleFilenameHelpers.REGEXP_NAMESPACE, opts.namespace); +}; + +ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { + const countMap = Object.create(null); + const posMap = Object.create(null); + array.forEach((item, idx) => { + countMap[item] = countMap[item] || []; + countMap[item].push(idx); + posMap[item] = 0; + }); + if (comparator) { + Object.keys(countMap).forEach(item => { + countMap[item].sort(comparator); + }); + } + return array.map((item, i) => { + if (countMap[item].length > 1) { + if (comparator && countMap[item][0] === i) return item; + return fn(item, i, posMap[item]++); + } else { + return item; + } + }); +}; + +ModuleFilenameHelpers.matchPart = (str, test) => { + if (!test) return true; + test = asRegExp(test); + if (Array.isArray(test)) { + return test.map(asRegExp).some(regExp => regExp.test(str)); + } else { + return test.test(str); + } +}; + +ModuleFilenameHelpers.matchObject = (obj, str) => { + if (obj.test) { + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; + } + } + if (obj.include) { + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } + } + if (obj.exclude) { + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; + } + } + return true; +}; + + +/***/ }), + +/***/ 71638: +/***/ ((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__(97391); + +class ModuleNotFoundError extends WebpackError { + constructor(module, err) { + super("Module not found: " + err); + + this.name = "ModuleNotFoundError"; + this.details = err.details; + this.missing = err.missing; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleNotFoundError; + + +/***/ }), + +/***/ 62500: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ + +class ModuleParseError extends WebpackError { + /** + * @param {Module} module the errored module + * @param {string} source source code + * @param {Error&any} err the parse error + * @param {string[]} loaders the loaders used + */ + constructor(module, source, err, loaders) { + let message = "Module parse failed: " + err.message; + let loc = undefined; + 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.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + var lineNumber = err.loc.line; + if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { + // binary file + message += "\n(Source code omitted for this binary file)"; + } else { + const sourceLines = source.split(/\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 = err.loc; + } else { + message += "\n" + err.stack; + } + + super(message); + + this.name = "ModuleParseError"; + this.module = module; + this.loc = loc; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleParseError; + + +/***/ }), + +/***/ 44576: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency")} Dependency */ + +class ModuleReason { + /** + * @param {Module} module the referencing module + * @param {Dependency} dependency the referencing dependency + * @param {string=} explanation some extra detail + */ + constructor(module, dependency, explanation) { + this.module = module; + this.dependency = dependency; + this.explanation = explanation; + this._chunks = null; + } + + hasChunk(chunk) { + if (this._chunks) { + if (this._chunks.has(chunk)) return true; + } else if (this.module && this.module._chunks.has(chunk)) return true; + return false; + } + + rewriteChunks(oldChunk, newChunks) { + if (!this._chunks) { + if (this.module) { + if (!this.module._chunks.has(oldChunk)) return; + this._chunks = new Set(this.module._chunks); + } else { + this._chunks = new Set(); + } + } + if (this._chunks.has(oldChunk)) { + this._chunks.delete(oldChunk); + for (let i = 0; i < newChunks.length; i++) { + this._chunks.add(newChunks[i]); + } + } + } +} + +module.exports = ModuleReason; + + +/***/ }), + +/***/ 75100: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(92402); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ + +module.exports = class ModuleTemplate extends Tapable { + constructor(runtimeTemplate, type) { + super(); + this.runtimeTemplate = runtimeTemplate; + this.type = type; + this.hooks = { + content: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + module: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + package: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; + } + + /** + * @param {Module} module the module + * @param {TODO} dependencyTemplates templates for dependencies + * @param {TODO} options render options + * @returns {Source} the source + */ + render(module, dependencyTemplates, options) { + try { + const moduleSource = module.source( + dependencyTemplates, + this.runtimeTemplate, + this.type + ); + const moduleSourcePostContent = this.hooks.content.call( + moduleSource, + module, + options, + dependencyTemplates + ); + const moduleSourcePostModule = this.hooks.module.call( + moduleSourcePostContent, + module, + options, + dependencyTemplates + ); + const moduleSourcePostRender = this.hooks.render.call( + moduleSourcePostModule, + module, + options, + dependencyTemplates + ); + return this.hooks.package.call( + moduleSourcePostRender, + module, + options, + dependencyTemplates + ); + } catch (e) { + e.message = `${module.identifier()}\n${e.message}`; + throw e; + } + } + + updateHash(hash) { + hash.update("1"); + this.hooks.hash.call(hash); + } +}; + + +/***/ }), + +/***/ 6372: +/***/ ((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__(97391); +const { cleanUp } = __webpack_require__(80140); + +class ModuleWarning extends WebpackError { + constructor(module, warning, { from = null } = {}) { + let message = "Module Warning"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (warning && typeof warning === "object" && warning.message) { + message += warning.message; + } else if (warning) { + message += warning; + } + super(message); + this.name = "ModuleWarning"; + this.module = module; + this.warning = warning; + this.details = + warning && typeof warning === "object" && warning.stack + ? cleanUp(warning.stack, this.message) + : undefined; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleWarning; + + +/***/ }), + +/***/ 10238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { Tapable, SyncHook, MultiHook } = __webpack_require__(92402); +const asyncLib = __webpack_require__(36386); +const MultiWatching = __webpack_require__(66624); +const MultiStats = __webpack_require__(55144); +const ConcurrentCompilationError = __webpack_require__(18933); + +module.exports = class MultiCompiler extends Tapable { + constructor(compilers) { + super(); + this.hooks = { + done: new SyncHook(["stats"]), + invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), + run: new MultiHook(compilers.map(c => c.hooks.run)), + watchClose: new SyncHook([]), + watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), + infrastructureLog: new MultiHook( + compilers.map(c => c.hooks.infrastructureLog) + ) + }; + if (!Array.isArray(compilers)) { + compilers = Object.keys(compilers).map(name => { + compilers[name].name = name; + return compilers[name]; + }); + } + this.compilers = compilers; + let doneCompilers = 0; + let compilerStats = []; + let index = 0; + for (const compiler of this.compilers) { + let compilerDone = false; + const compilerIndex = index++; + // eslint-disable-next-line no-loop-func + compiler.hooks.done.tap("MultiCompiler", stats => { + if (!compilerDone) { + compilerDone = true; + doneCompilers++; + } + compilerStats[compilerIndex] = stats; + if (doneCompilers === this.compilers.length) { + this.hooks.done.call(new MultiStats(compilerStats)); + } + }); + // eslint-disable-next-line no-loop-func + compiler.hooks.invalid.tap("MultiCompiler", () => { + if (compilerDone) { + compilerDone = false; + doneCompilers--; + } + }); + } + this.running = false; + } + + get outputPath() { + let commonPath = this.compilers[0].outputPath; + for (const compiler of this.compilers) { + while ( + compiler.outputPath.indexOf(commonPath) !== 0 && + /[/\\]/.test(commonPath) + ) { + commonPath = commonPath.replace(/[/\\][^/\\]*$/, ""); + } + } + + if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; + return commonPath; + } + + get inputFileSystem() { + throw new Error("Cannot read inputFileSystem of a MultiCompiler"); + } + + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } + + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } + } + + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } + } + + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); + } + + validateDependencies(callback) { + const edges = new Set(); + const missing = []; + const targetFound = compiler => { + for (const edge of edges) { + if (edge.target === compiler) { + return true; + } + } + return false; + }; + const sortEdges = (e1, e2) => { + return ( + e1.source.name.localeCompare(e2.source.name) || + e1.target.name.localeCompare(e2.target.name) + ); + }; + for (const source of this.compilers) { + if (source.dependencies) { + for (const dep of source.dependencies) { + const target = this.compilers.find(c => c.name === dep); + if (!target) { + missing.push(dep); + } else { + edges.add({ + source, + target + }); + } + } + } + } + const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`); + const stack = this.compilers.filter(c => !targetFound(c)); + while (stack.length > 0) { + const current = stack.pop(); + for (const edge of edges) { + if (edge.source === current) { + edges.delete(edge); + const target = edge.target; + if (!targetFound(target)) { + stack.push(target); + } + } + } + } + if (edges.size > 0) { + const lines = Array.from(edges) + .sort(sortEdges) + .map(edge => `${edge.source.name} -> ${edge.target.name}`); + lines.unshift("Circular dependency found in compiler dependencies."); + errors.unshift(lines.join("\n")); + } + if (errors.length > 0) { + const message = errors.join("\n"); + callback(new Error(message)); + return false; + } + return true; + } + + runWithDependencies(compilers, fn, callback) { + const fulfilledNames = new Set(); + let remainingCompilers = compilers; + const isDependencyFulfilled = d => fulfilledNames.has(d); + const getReadyCompilers = () => { + let readyCompilers = []; + let list = remainingCompilers; + remainingCompilers = []; + for (const c of list) { + const ready = + !c.dependencies || c.dependencies.every(isDependencyFulfilled); + if (ready) { + readyCompilers.push(c); + } else { + remainingCompilers.push(c); + } + } + return readyCompilers; + }; + const runCompilers = callback => { + if (remainingCompilers.length === 0) return callback(); + asyncLib.map( + getReadyCompilers(), + (compiler, callback) => { + fn(compiler, err => { + if (err) return callback(err); + fulfilledNames.add(compiler.name); + runCompilers(callback); + }); + }, + callback + ); + }; + runCompilers(callback); + } + + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); + + let watchings = []; + let allStats = this.compilers.map(() => null); + let compilerStatus = this.compilers.map(() => false); + if (this.validateDependencies(handler)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + let firstRun = true; + let watching = compiler.watch( + Array.isArray(watchOptions) + ? watchOptions[compilerIdx] + : watchOptions, + (err, stats) => { + if (err) handler(err); + if (stats) { + allStats[compilerIdx] = stats; + compilerStatus[compilerIdx] = "new"; + if (compilerStatus.every(Boolean)) { + const freshStats = allStats.filter((s, idx) => { + return compilerStatus[idx] === "new"; + }); + compilerStatus.fill(true); + const multiStats = new MultiStats(freshStats); + handler(null, multiStats); + } + } + if (firstRun && !err) { + firstRun = false; + callback(); + } + } + ); + watchings.push(watching); + }, + () => { + // ignore + } + ); + } + + return new MultiWatching(watchings, this); + } + + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + + const finalCallback = (err, stats) => { + this.running = false; + + if (callback !== undefined) { + return callback(err, stats); + } + }; + + const allStats = this.compilers.map(() => null); + if (this.validateDependencies(callback)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + compiler.run((err, stats) => { + if (err) { + return callback(err); + } + allStats[compilerIdx] = stats; + callback(); + }); + }, + err => { + if (err) { + return finalCallback(err); + } + finalCallback(null, new MultiStats(allStats)); + } + ); + } + } + + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); + } + } + } +}; + + +/***/ }), + +/***/ 98046: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const MultiEntryDependency = __webpack_require__(7791); +const SingleEntryDependency = __webpack_require__(84828); +const MultiModuleFactory = __webpack_require__(24005); + +/** @typedef {import("./Compiler")} Compiler */ + +class MultiEntryPlugin { + /** + * The MultiEntryPlugin is invoked whenever this.options.entry value is an array of paths + * @param {string} context context path + * @param {string[]} entries array of entry paths + * @param {string} name entry key name + */ + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MultiEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); + + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "MultiEntryPlugin", + (compilation, callback) => { + const { context, entries, name } = this; + + const dep = MultiEntryPlugin.createDependency(entries, name); + compilation.addEntry(context, dep, name, callback); + } + ); + } + + /** + * @param {string[]} entries each entry path string + * @param {string} name name of the entry + * @returns {MultiEntryDependency} returns a constructed Dependency + */ + static createDependency(entries, name) { + return new MultiEntryDependency( + entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + // Because entrypoints are not dependencies found in an + // existing module, we give it a synthetic id + dep.loc = { + name, + index: idx + }; + return dep; + }), + name + ); + } +} + +module.exports = MultiEntryPlugin; + + +/***/ }), + +/***/ 4198: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Module = __webpack_require__(75993); +const Template = __webpack_require__(96066); +const { RawSource } = __webpack_require__(53665); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class MultiModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); + + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this._identifier = `multi ${this.dependencies + .map(d => d.request) + .join(" ")}`; + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + return `multi ${this.dependencies + .map(d => requestShortener.shorten(d.request)) + .join(" ")}`; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + needRebuild() { + return false; + } + + size() { + return 16 + this.dependencies.length * 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("multi module"); + hash.update(this.name || ""); + super.updateHash(hash); + } + + source(dependencyTemplates, runtimeTemplate) { + const str = []; + let idx = 0; + for (const dep of this.dependencies) { + if (dep.module) { + if (idx === this.dependencies.length - 1) { + str.push("module.exports = "); + } + str.push("__webpack_require__("); + if (runtimeTemplate.outputOptions.pathinfo) { + str.push(Template.toComment(dep.request)); + } + str.push(`${JSON.stringify(dep.module.id)}`); + str.push(")"); + } else { + const content = __webpack_require__(75386).module( + dep.request + ); + str.push(content); + } + str.push(";\n"); + idx++; + } + return new RawSource(str.join("")); + } +} + +module.exports = MultiModule; + + +/***/ }), + +/***/ 24005: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { Tapable } = __webpack_require__(92402); +const MultiModule = __webpack_require__(4198); + +module.exports = class MultiModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } + + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new MultiModule(data.context, dependency.dependencies, dependency.name) + ); + } +}; + + +/***/ }), + +/***/ 55144: +/***/ ((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__(99977); + +const optionOrFallback = (optionValue, fallbackValue) => + optionValue !== undefined ? optionValue : fallbackValue; + +class MultiStats { + constructor(stats) { + this.stats = stats; + this.hash = stats.map(stat => stat.hash).join(""); + } + + hasErrors() { + return this.stats + .map(stat => stat.hasErrors()) + .reduce((a, b) => a || b, false); + } + + hasWarnings() { + return this.stats + .map(stat => stat.hasWarnings()) + .reduce((a, b) => a || b, false); + } + + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + const jsons = this.stats.map((stat, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = stat.toJson(childOptions, forToString); + obj.name = stat.compilation && stat.compilation.name; + return obj; + }); + const showVersion = + options.version === undefined + ? jsons.every(j => j.version) + : options.version !== false; + const showHash = + options.hash === undefined + ? jsons.every(j => j.hash) + : options.hash !== false; + if (showVersion) { + for (const j of jsons) { + delete j.version; + } + } + const obj = { + errors: jsons.reduce((arr, j) => { + return arr.concat( + j.errors.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []), + warnings: jsons.reduce((arr, j) => { + return arr.concat( + j.warnings.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []) + }; + if (showVersion) obj.version = __webpack_require__(71618)/* .version */ .i8; + if (showHash) obj.hash = this.hash; + if (options.children !== false) obj.children = jsons; + return obj; + } + + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const useColors = optionOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } +} + +module.exports = MultiStats; + + +/***/ }), + +/***/ 66624: +/***/ ((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__(36386); + +class MultiWatching { + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; + } + + invalidate() { + for (const watching of this.watchings) { + watching.invalidate(); + } + } + + suspend() { + for (const watching of this.watchings) { + watching.suspend(); + } + } + + resume() { + for (const watching of this.watchings) { + watching.resume(); + } + } + + close(callback) { + asyncLib.forEach( + this.watchings, + (watching, finishedCallback) => { + watching.close(finishedCallback); + }, + err => { + this.compiler.hooks.watchClose.call(); + if (typeof callback === "function") { + this.compiler.running = false; + callback(err); + } + } + ); + } +} + +module.exports = MultiWatching; + + +/***/ }), + +/***/ 70419: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class NamedChunksPlugin { + static defaultNameResolver(chunk) { + return chunk.name || null; + } + + constructor(nameResolver) { + this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; + } + + apply(compiler) { + compiler.hooks.compilation.tap("NamedChunksPlugin", compilation => { + compilation.hooks.beforeChunkIds.tap("NamedChunksPlugin", chunks => { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = this.nameResolver(chunk); + } + } + }); + }); + } +} + +module.exports = NamedChunksPlugin; + + +/***/ }), + +/***/ 86707: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const createHash = __webpack_require__(15660); +const RequestShortener = __webpack_require__(54254); + +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); +}; + +class NamedModulesPlugin { + constructor(options) { + this.options = options || {}; + } + + apply(compiler) { + compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => { + compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => { + const namedModules = new Map(); + const context = this.options.context || compiler.options.context; + + for (const module of modules) { + if (module.id === null && module.libIdent) { + module.id = module.libIdent({ context }); + } + + if (module.id !== null) { + const namedModule = namedModules.get(module.id); + if (namedModule !== undefined) { + namedModule.push(module); + } else { + namedModules.set(module.id, [module]); + } + } + } + + for (const namedModule of namedModules.values()) { + if (namedModule.length > 1) { + for (const module of namedModule) { + const requestShortener = new RequestShortener(context); + module.id = `${module.id}?${getHash( + requestShortener.shorten(module.identifier()) + )}`; + } + } + } + }); + }); + } +} + +module.exports = NamedModulesPlugin; + + +/***/ }), + +/***/ 22615: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class NoEmitOnErrorsPlugin { + apply(compiler) { + compiler.hooks.shouldEmit.tap("NoEmitOnErrorsPlugin", compilation => { + if (compilation.getStats().hasErrors()) return false; + }); + compiler.hooks.compilation.tap("NoEmitOnErrorsPlugin", compilation => { + compilation.hooks.shouldRecord.tap("NoEmitOnErrorsPlugin", () => { + if (compilation.getStats().hasErrors()) return false; + }); + }); + } +} + +module.exports = NoEmitOnErrorsPlugin; + + +/***/ }), + +/***/ 45759: +/***/ ((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__(97391); + +module.exports = class NoModeWarning extends WebpackError { + constructor(modules) { + super(); + + this.name = "NoModeWarning"; + this.message = + "configuration\n" + + "The 'mode' option has not been set, webpack will fallback to 'production' for this value. " + + "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + + "You can also set it to 'none' to disable any default behavior. " + + "Learn more: https://webpack.js.org/configuration/mode/"; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 28386: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); + +const NullFactory = __webpack_require__(40438); + +class NodeStuffPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "NodeStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; + + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } + + const setConstant = (expressionName, value) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(value) + ); + return true; + }); + }; + + const setModuleConstant = (expressionName, fn) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(fn(parser.state.module)) + ); + return true; + }); + }; + const context = compiler.context; + if (localOptions.__filename) { + if (localOptions.__filename === "mock") { + setConstant("__filename", "/index.js"); + } else { + setModuleConstant("__filename", module => + path.relative(context, module.resource) + ); + } + parser.hooks.evaluateIdentifier + .for("__filename") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + const resource = parser.state.module.resource; + const i = resource.indexOf("?"); + return ParserHelpers.evaluateToString( + i < 0 ? resource : resource.substr(0, i) + )(expr); + }); + } + if (localOptions.__dirname) { + if (localOptions.__dirname === "mock") { + setConstant("__dirname", "/"); + } else { + setModuleConstant("__dirname", module => + path.relative(context, module.context) + ); + } + parser.hooks.evaluateIdentifier + .for("__dirname") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + parser.state.module.context + )(expr); + }); + } + parser.hooks.expression + .for("require.extensions") + .tap( + "NodeStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.extensions is not supported by webpack. Use a loader instead." + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeStuffPlugin", handler); + } + ); + } +} +module.exports = NodeStuffPlugin; + + +/***/ }), + +/***/ 25963: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const NativeModule = __webpack_require__(32282); + +const { + CachedSource, + LineToLineMappedSource, + OriginalSource, + RawSource, + SourceMapSource +} = __webpack_require__(53665); +const { getContext, runLoaders } = __webpack_require__(73278); + +const WebpackError = __webpack_require__(97391); +const Module = __webpack_require__(75993); +const ModuleParseError = __webpack_require__(62500); +const ModuleBuildError = __webpack_require__(12072); +const ModuleError = __webpack_require__(82528); +const ModuleWarning = __webpack_require__(6372); +const createHash = __webpack_require__(15660); +const contextify = __webpack_require__(94658).contextify; + +/** @typedef {import("./util/createHash").Hash} Hash */ + +const asString = buf => { + if (Buffer.isBuffer(buf)) { + return buf.toString("utf-8"); + } + return buf; +}; + +const asBuffer = str => { + if (!Buffer.isBuffer(str)) { + return Buffer.from(str, "utf-8"); + } + return str; +}; + +class NonErrorEmittedError extends WebpackError { + constructor(error) { + super(); + + this.name = "NonErrorEmittedError"; + this.message = "(Emitted value instead of an instance of Error) " + error; + + Error.captureStackTrace(this, this.constructor); + } +} + +/** + * @typedef {Object} CachedSourceEntry + * @property {TODO} source the generated source + * @property {string} hash the hash value + */ + +class NormalModule extends Module { + constructor({ + type, + request, + userRequest, + rawRequest, + loaders, + resource, + matchResource, + parser, + generator, + resolveOptions + }) { + super(type, getContext(resource)); + + // Info from Factory + this.request = request; + this.userRequest = userRequest; + this.rawRequest = rawRequest; + this.binary = type.startsWith("webassembly"); + this.parser = parser; + this.generator = generator; + this.resource = resource; + this.matchResource = matchResource; + this.loaders = loaders; + if (resolveOptions !== undefined) this.resolveOptions = resolveOptions; + + // Info from Build + this.error = null; + this._source = null; + this._sourceSize = null; + this._buildHash = ""; + this.buildTimestamp = undefined; + /** @private @type {Map} */ + this._cachedSources = new Map(); + + // Options for the NormalModule set by plugins + // TODO refactor this -> options object filled from Factory + this.useSourceMap = false; + this.lineToLine = false; + + // Cache + this._lastSuccessfulBuildMeta = {}; + } + + identifier() { + return this.request; + } + + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); + } + + libIdent(options) { + return contextify(options.context, this.userRequest); + } + + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; + } + + updateCacheModule(module) { + this.type = module.type; + this.request = module.request; + this.userRequest = module.userRequest; + this.rawRequest = module.rawRequest; + this.parser = module.parser; + this.generator = module.generator; + this.resource = module.resource; + this.matchResource = module.matchResource; + this.loaders = module.loaders; + this.resolveOptions = module.resolveOptions; + } + + createSourceForAsset(name, content, sourceMap) { + if (!sourceMap) { + return new RawSource(content); + } + + if (typeof sourceMap === "string") { + return new OriginalSource(content, sourceMap); + } + + return new SourceMapSource(content, name, sourceMap); + } + + createLoaderContext(resolver, options, compilation, fs) { + const requestShortener = compilation.runtimeTemplate.requestShortener; + const getCurrentLoaderName = () => { + const currentLoader = this.getCurrentLoader(loaderContext); + if (!currentLoader) return "(not in loader scope)"; + return requestShortener.shorten(currentLoader.loader); + }; + const loaderContext = { + version: 2, + emitWarning: warning => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + this.warnings.push( + new ModuleWarning(this, warning, { + from: getCurrentLoaderName() + }) + ); + }, + emitError: error => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + this.errors.push( + new ModuleError(this, error, { + from: getCurrentLoaderName() + }) + ); + }, + getLogger: name => { + const currentLoader = this.getCurrentLoader(loaderContext); + return compilation.getLogger(() => + [currentLoader && currentLoader.loader, name, this.identifier()] + .filter(Boolean) + .join("|") + ); + }, + // TODO remove in webpack 5 + exec: (code, filename) => { + // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'. + const module = new NativeModule(filename, this); + // @ts-ignore _nodeModulePaths is deprecated and undocumented Node.js API + module.paths = NativeModule._nodeModulePaths(this.context); + module.filename = filename; + module._compile(code, filename); + return module.exports; + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, {}, callback); + }, + getResolve(options) { + const child = options ? resolver.withOptions(options) : resolver; + return (context, request, callback) => { + if (callback) { + child.resolve({}, context, request, {}, callback); + } else { + return new Promise((resolve, reject) => { + child.resolve({}, context, request, {}, (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( + name, + content, + sourceMap + ); + this.buildInfo.assetsInfo.set(name, assetInfo); + }, + rootContext: options.context, + webpack: true, + sourceMap: !!this.useSourceMap, + mode: options.mode || "production", + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs: fs + }; + + compilation.hooks.normalModuleLoader.call(loaderContext, this); + if (options.loader) { + Object.assign(loaderContext, options.loader); + } + + return loaderContext; + } + + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } + + createSource(source, resourceBuffer, sourceMap) { + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(source); + } + + // from here on we assume we have an identifier + const identifier = this.identifier(); + + if (this.lineToLine && resourceBuffer) { + return new LineToLineMappedSource( + source, + identifier, + asString(resourceBuffer) + ); + } + + if (this.useSourceMap && sourceMap) { + return new SourceMapSource(source, identifier, sourceMap); + } + + if (Buffer.isBuffer(source)) { + // @ts-ignore + // TODO We need to fix @types/webpack-sources to allow RawSource to take a Buffer | string + return new RawSource(source); + } + + return new OriginalSource(source, identifier); + } + + doBuild(options, compilation, resolver, fs, callback) { + const loaderContext = this.createLoaderContext( + resolver, + options, + compilation, + fs + ); + + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + readResource: fs.readFile.bind(fs) + }, + (err, result) => { + if (result) { + this.buildInfo.cacheable = result.cacheable; + this.buildInfo.fileDependencies = new Set(result.fileDependencies); + this.buildInfo.contextDependencies = new Set( + result.contextDependencies + ); + } + + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); + } + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(this, err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + }); + return callback(error); + } + + const resourceBuffer = result.resourceBuffer; + const source = result.result[0]; + const sourceMap = result.result.length >= 1 ? result.result[1] : null; + const extraInfo = result.result.length >= 2 ? result.result[2] : null; + + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` + ); + const error = new ModuleBuildError(this, err); + return callback(error); + } + + this._source = this.createSource( + this.binary ? asBuffer(source) : asString(source), + resourceBuffer, + sourceMap + ); + this._sourceSize = null; + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); + } + ); + } + + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); + this.error = error; + this.errors.push(this.error); + this._source = new RawSource( + "throw new Error(" + JSON.stringify(this.error.message) + ");" + ); + this._sourceSize = null; + this._ast = null; + } + + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.indexOf(rule) === 0; + } + + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); + } + + // check if module should not be parsed + // returns "true" if the module should !not! be parsed + // returns "false" if the module !must! be parsed + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } + + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); + } + + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; + } + } + // no match found, so this module !should! be parsed + return false; + } + + _initBuildHash(compilation) { + const hash = createHash(compilation.outputOptions.hashFunction); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); + } + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + this._buildHash = /** @type {string} */ (hash.digest("hex")); + } + + build(options, compilation, resolver, fs, callback) { + this.buildTimestamp = Date.now(); + this.built = true; + this._source = null; + this._sourceSize = null; + this._ast = null; + this._buildHash = ""; + this.error = null; + this.errors.length = 0; + this.warnings.length = 0; + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + fileDependencies: new Set(), + contextDependencies: new Set(), + assets: undefined, + assetsInfo: undefined + }; + + return this.doBuild(options, compilation, resolver, fs, err => { + this._cachedSources.clear(); + + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } + + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + this._initBuildHash(compilation); + return callback(); + } + + const handleParseError = e => { + const source = this._source.source(); + const loaders = this.loaders.map(item => + contextify(options.context, item.loader) + ); + const error = new ModuleParseError(this, source, e, loaders); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + + const handleParseResult = result => { + this._lastSuccessfulBuildMeta = this.buildMeta; + this._initBuildHash(compilation); + return callback(); + }; + + try { + const result = this.parser.parse( + this._ast || this._source.source(), + { + current: this, + module: this, + compilation: compilation, + options: options + }, + (err, result) => { + if (err) { + handleParseError(err); + } else { + handleParseResult(result); + } + } + ); + if (result !== undefined) { + // parse is sync + handleParseResult(result); + } + } catch (e) { + handleParseError(e); + } + }); + } + + getHashDigest(dependencyTemplates) { + // TODO webpack 5 refactor + let dtHash = dependencyTemplates.get("hash"); + return `${this.hash}-${dtHash}`; + } + + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + const hashDigest = this.getHashDigest(dependencyTemplates); + const cacheEntry = this._cachedSources.get(type); + if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) { + // We can reuse the cached source + return cacheEntry.source; + } + + const source = this.generator.generate( + this, + dependencyTemplates, + runtimeTemplate, + type + ); + + const cachedSource = new CachedSource(source); + this._cachedSources.set(type, { + source: cachedSource, + hash: hashDigest + }); + return cachedSource; + } + + originalSource() { + return this._source; + } + + needRebuild(fileTimestamps, contextTimestamps) { + // always try to rebuild in case of an error + if (this.error) return true; + + // always rebuild when module is not cacheable + if (!this.buildInfo.cacheable) return true; + + // Check timestamps of all dependencies + // Missing timestamp -> need rebuild + // Timestamp bigger than buildTimestamp -> need rebuild + for (const file of this.buildInfo.fileDependencies) { + const timestamp = fileTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + for (const file of this.buildInfo.contextDependencies) { + const timestamp = contextTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + // elsewise -> no rebuild needed + return false; + } + + size() { + if (this._sourceSize === null) { + this._sourceSize = this._source ? this._source.size() : -1; + } + return this._sourceSize; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this._buildHash); + super.updateHash(hash); + } +} + +module.exports = NormalModule; + + +/***/ }), + +/***/ 22298: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + +const path = __webpack_require__(85622); +const asyncLib = __webpack_require__(36386); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = __webpack_require__(92402); +const NormalModule = __webpack_require__(25963); +const RawModule = __webpack_require__(82353); +const RuleSet = __webpack_require__(84247); +const { cachedCleverMerge } = __webpack_require__(67916); + +const EMPTY_RESOLVE_OPTIONS = {}; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; + +const loaderToIdent = data => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return data.loader + "??" + data.ident; + } + return data.loader + "?" + JSON.stringify(data.options); +}; + +const identToLoaderRequest = resultString => { + const idx = resultString.indexOf("?"); + if (idx >= 0) { + const loader = resultString.substr(0, idx); + const options = resultString.substr(idx + 1); + return { + loader, + options + }; + } else { + return { + loader: resultString, + options: undefined + }; + } +}; + +const dependencyCache = new WeakMap(); + +class NormalModuleFactory extends Tapable { + constructor(context, resolverFactory, options) { + super(); + this.hooks = { + resolver: new SyncWaterfallHook(["resolver"]), + factory: new SyncWaterfallHook(["factory"]), + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + createModule: new SyncBailHook(["data"]), + module: new SyncWaterfallHook(["module", "data"]), + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ) + }; + this._pluginCompat.tap("NormalModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + options.async = true; + break; + case "parser": + this.hooks.parser + .for("javascript/auto") + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + let match; + match = /^parser (.+)$/.exec(options.name); + if (match) { + this.hooks.parser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + match = /^create-parser (.+)$/.exec(options.name); + if (match) { + this.hooks.createParser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + }); + this.resolverFactory = resolverFactory; + this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); + this.cachePredicate = + typeof options.unsafeCache === "function" + ? options.unsafeCache + : Boolean.bind(null, options.unsafeCache); + this.context = context || ""; + this.parserCache = Object.create(null); + this.generatorCache = Object.create(null); + this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { + let resolver = this.hooks.resolver.call(null); + + // Ignored + if (!resolver) return callback(); + + resolver(result, (err, data) => { + if (err) return callback(err); + + // Ignored + if (!data) return callback(); + + // direct module + if (typeof data.source === "function") return callback(null, data); + + this.hooks.afterResolve.callAsync(data, (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + let createdModule = this.hooks.createModule.call(result); + if (!createdModule) { + if (!result.request) { + return callback(new Error("Empty dependency (no request)")); + } + + createdModule = new NormalModule(result); + } + + createdModule = this.hooks.module.call(createdModule, result); + + return callback(null, createdModule); + }); + }); + }); + this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { + const contextInfo = data.contextInfo; + const context = data.context; + const request = data.request; + + const loaderResolver = this.getResolver("loader"); + const normalResolver = this.getResolver("normal", data.resolveOptions); + + let matchResource = undefined; + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + matchResource = matchResourceMatch[1]; + if (/^\.\.?\//.test(matchResource)) { + matchResource = path.join(context, matchResource); + } + requestWithoutMatchResource = request.substr( + matchResourceMatch[0].length + ); + } + + const noPreAutoLoaders = requestWithoutMatchResource.startsWith("-!"); + const noAutoLoaders = + noPreAutoLoaders || requestWithoutMatchResource.startsWith("!"); + const noPrePostAutoLoaders = requestWithoutMatchResource.startsWith("!!"); + let elements = requestWithoutMatchResource + .replace(/^-?!+/, "") + .replace(/!!+/g, "!") + .split("!"); + let resource = elements.pop(); + elements = elements.map(identToLoaderRequest); + + asyncLib.parallel( + [ + callback => + this.resolveRequestArray( + contextInfo, + context, + elements, + loaderResolver, + callback + ), + callback => { + if (resource === "" || resource[0] === "?") { + return callback(null, { + resource + }); + } + + normalResolver.resolve( + contextInfo, + context, + resource, + {}, + (err, resource, resourceResolveData) => { + if (err) return callback(err); + callback(null, { + resourceResolveData, + resource + }); + } + ); + } + ], + (err, results) => { + if (err) return callback(err); + let loaders = results[0]; + const resourceResolveData = results[1].resourceResolveData; + resource = results[1].resource; + + // translate option idents + try { + for (const item of loaders) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.substr(1); + item.options = this.ruleSet.findOptionsByIdent(ident); + item.ident = ident; + } + } + } catch (e) { + return callback(e); + } + + if (resource === false) { + // ignored + return callback( + null, + new RawModule( + "/* (ignored) */", + `ignored ${context} ${request}`, + `${request} (ignored)` + ) + ); + } + + const userRequest = + (matchResource !== undefined ? `${matchResource}!=!` : "") + + loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"); + + let resourcePath = + matchResource !== undefined ? matchResource : resource; + let resourceQuery = ""; + const queryIndex = resourcePath.indexOf("?"); + if (queryIndex >= 0) { + resourceQuery = resourcePath.substr(queryIndex); + resourcePath = resourcePath.substr(0, queryIndex); + } + + const result = this.ruleSet.exec({ + resource: resourcePath, + realResource: + matchResource !== undefined + ? resource.replace(/\?.*/, "") + : resourcePath, + resourceQuery, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler + }); + const settings = {}; + const useLoadersPost = []; + const useLoaders = []; + const useLoadersPre = []; + for (const r of result) { + if (r.type === "use") { + if (r.enforce === "post" && !noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } else if ( + r.enforce === "pre" && + !noPreAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoadersPre.push(r.value); + } else if ( + !r.enforce && + !noAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoaders.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[r.type] === "object" && + settings[r.type] !== null + ) { + settings[r.type] = cachedCleverMerge(settings[r.type], r.value); + } else { + settings[r.type] = r.value; + } + } + asyncLib.parallel( + [ + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPost, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoaders, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPre, + loaderResolver + ) + ], + (err, results) => { + if (err) return callback(err); + if (matchResource === undefined) { + loaders = results[0].concat(loaders, results[1], results[2]); + } else { + loaders = results[0].concat(results[1], loaders, results[2]); + } + process.nextTick(() => { + const type = settings.type; + const resolveOptions = settings.resolve; + callback(null, { + context: context, + request: loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"), + dependencies: data.dependencies, + userRequest, + rawRequest: request, + loaders, + resource, + matchResource, + resourceResolveData, + settings, + type, + parser: this.getParser(type, settings.parser), + generator: this.getGenerator(type, settings.generator), + resolveOptions + }); + }); + } + ); + } + ); + }); + } + + create(data, callback) { + const dependencies = data.dependencies; + const cacheEntry = dependencyCache.get(dependencies[0]); + if (cacheEntry) return callback(null, cacheEntry); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const request = dependencies[0].request; + const contextInfo = data.contextInfo || {}; + this.hooks.beforeResolve.callAsync( + { + contextInfo, + resolveOptions, + context, + request, + dependencies + }, + (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + const factory = this.hooks.factory.call(null); + + // Ignored + if (!factory) return callback(); + + factory(result, (err, module) => { + if (err) return callback(err); + + if (module && this.cachePredicate(module)) { + for (const d of dependencies) { + dependencyCache.set(d, module); + } + } + + callback(null, module); + }); + } + ); + } + + resolveRequestArray(contextInfo, context, array, resolver, callback) { + if (array.length === 0) return callback(null, []); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + {}, + (err, result) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !/-loader$/.test(item.loader) + ) { + return resolver.resolve( + contextInfo, + context, + item.loader + "-loader", + {}, + err2 => { + if (!err2) { + err.message = + err.message + + "\n" + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); + + const optionsOnly = item.options + ? { + options: item.options + } + : undefined; + return callback( + null, + Object.assign({}, item, identToLoaderRequest(result), optionsOnly) + ); + } + ); + }, + callback + ); + } + + getParser(type, parserOptions) { + let ident = type; + if (parserOptions) { + if (parserOptions.ident) { + ident = `${type}|${parserOptions.ident}`; + } else { + ident = JSON.stringify([type, parserOptions]); + } + } + if (ident in this.parserCache) { + return this.parserCache[ident]; + } + return (this.parserCache[ident] = this.createParser(type, parserOptions)); + } + + createParser(type, parserOptions = {}) { + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); + } + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; + } + + getGenerator(type, generatorOptions) { + let ident = type; + if (generatorOptions) { + if (generatorOptions.ident) { + ident = `${type}|${generatorOptions.ident}`; + } else { + ident = JSON.stringify([type, generatorOptions]); + } + } + if (ident in this.generatorCache) { + return this.generatorCache[ident]; + } + return (this.generatorCache[ident] = this.createGenerator( + type, + generatorOptions + )); + } + + createGenerator(type, generatorOptions = {}) { + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); + } + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; + } + + getResolver(type, resolveOptions) { + return this.resolverFactory.get( + type, + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + } +} + +module.exports = NormalModuleFactory; + + +/***/ }), + +/***/ 73253: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); + +class NormalModuleReplacementPlugin { + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } + + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap( + "NormalModuleReplacementPlugin", + nmf => { + nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + return result; + }); + nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.resource = path.resolve( + path.dirname(result.resource), + newResource + ); + } + } + return result; + }); + } + ); + } +} + +module.exports = NormalModuleReplacementPlugin; + + +/***/ }), + +/***/ 40438: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class NullFactory { + create(data, callback) { + return callback(); + } +} +module.exports = NullFactory; + + +/***/ }), + +/***/ 4428: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class OptionsApply { + process(options, compiler) {} +} +module.exports = OptionsApply; + + +/***/ }), + +/***/ 3414: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** + * Gets the value at path of object + * @param {object} obj object to query + * @param {string} path query path + * @returns {any} - if {@param path} requests element from array, then `undefined` will be returned + */ +const getProperty = (obj, path) => { + let name = path.split("."); + for (let i = 0; i < name.length - 1; i++) { + obj = obj[name[i]]; + if (typeof obj !== "object" || !obj || Array.isArray(obj)) return; + } + return obj[name.pop()]; +}; + +/** + * Sets the value at path of object. Stops execution, if {@param path} requests element from array to be set + * @param {object} obj object to query + * @param {string} path query path + * @param {any} value value to be set + * @returns {void} + */ +const setProperty = (obj, path, value) => { + let name = path.split("."); + for (let i = 0; i < name.length - 1; i++) { + if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return; + if (Array.isArray(obj[name[i]])) return; + if (!obj[name[i]]) obj[name[i]] = {}; + obj = obj[name[i]]; + } + obj[name.pop()] = value; +}; + +/** + * @typedef {'call' | 'make' | 'append'} ConfigType + */ +/** + * @typedef {(options: object) => any} MakeConfigHandler + */ +/** + * @typedef {(value: any, options: object) => any} CallConfigHandler + */ +/** + * @typedef {any[]} AppendConfigValues + */ + +class OptionsDefaulter { + constructor() { + /** + * Stores default options settings or functions for computing them + */ + this.defaults = {}; + /** + * Stores configuration for options + * @type {{[key: string]: ConfigType}} + */ + this.config = {}; + } + + /** + * Enhancing {@param options} with default values + * @param {object} options provided options + * @returns {object} - enhanced options + * @throws {Error} - will throw error, if configuration value is other then `undefined` or {@link ConfigType} + */ + process(options) { + options = Object.assign({}, options); + for (let name in this.defaults) { + switch (this.config[name]) { + /** + * If {@link ConfigType} doesn't specified and current value is `undefined`, then default value will be assigned + */ + case undefined: + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name]); + } + break; + /** + * Assign result of {@link CallConfigHandler} + */ + case "call": + setProperty( + options, + name, + this.defaults[name].call(this, getProperty(options, name), options) + ); + break; + /** + * Assign result of {@link MakeConfigHandler}, if current value is `undefined` + */ + case "make": + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name].call(this, options)); + } + break; + /** + * Adding {@link AppendConfigValues} at the end of the current array + */ + case "append": { + let oldValue = getProperty(options, name); + if (!Array.isArray(oldValue)) { + oldValue = []; + } + oldValue.push(...this.defaults[name]); + setProperty(options, name, oldValue); + break; + } + default: + throw new Error( + "OptionsDefaulter cannot process " + this.config[name] + ); + } + } + return options; + } + + /** + * Builds up default values + * @param {string} name option path + * @param {ConfigType | any} config if {@param def} is provided, then only {@link ConfigType} is allowed + * @param {MakeConfigHandler | CallConfigHandler | AppendConfigValues} [def] defaults + * @returns {void} + */ + set(name, config, def) { + if (def !== undefined) { + this.defaults[name] = def; + this.config[name] = config; + } else { + this.defaults[name] = config; + delete this.config[name]; + } + } +} + +module.exports = OptionsDefaulter; + + +/***/ }), + +/***/ 70558: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API + +const acorn = __webpack_require__(77087); +const { Tapable, SyncBailHook, HookMap } = __webpack_require__(92402); +const util = __webpack_require__(31669); +const vm = __webpack_require__(92184); +const BasicEvaluatedExpression = __webpack_require__(96770); +const StackedSetMap = __webpack_require__(92251); + +const acornParser = acorn.Parser; + +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; +}; + +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: 11, + sourceType: "module", + 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 Parser extends Tapable { + constructor(options, sourceType = "auto") { + super(); + this.hooks = { + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + statement: new SyncBailHook(["statement"]), + statementIf: new SyncBailHook(["statement"]), + label: new HookMap(() => new SyncBailHook(["statement"])), + import: new SyncBailHook(["statement", "source"]), + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + export: new SyncBailHook(["statement"]), + exportImport: new SyncBailHook(["statement", "source"]), + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + exportExpression: new SyncBailHook(["statement", "declaration"]), + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + assigned: new HookMap(() => new SyncBailHook(["expression"])), + assign: new HookMap(() => new SyncBailHook(["expression"])), + typeof: new HookMap(() => new SyncBailHook(["expression"])), + importCall: new SyncBailHook(["expression"]), + call: new HookMap(() => new SyncBailHook(["expression"])), + callAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + new: new HookMap(() => new SyncBailHook(["expression"])), + expression: new HookMap(() => new SyncBailHook(["expression"])), + expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + expressionConditionalOperator: new SyncBailHook(["expression"]), + expressionLogicalOperator: new SyncBailHook(["expression"]), + program: new SyncBailHook(["ast", "comments"]) + }; + const HOOK_MAP_COMPAT_CONFIG = { + evaluateTypeof: /^evaluate typeof (.+)$/, + evaluateIdentifier: /^evaluate Identifier (.+)$/, + evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/, + evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/, + evaluate: /^evaluate (.+)$/, + label: /^label (.+)$/, + varDeclarationLet: /^var-let (.+)$/, + varDeclarationConst: /^var-const (.+)$/, + varDeclarationVar: /^var-var (.+)$/, + varDeclaration: /^var (.+)$/, + canRename: /^can-rename (.+)$/, + rename: /^rename (.+)$/, + typeof: /^typeof (.+)$/, + assigned: /^assigned (.+)$/, + assign: /^assign (.+)$/, + callAnyMember: /^call (.+)\.\*$/, + call: /^call (.+)$/, + new: /^new (.+)$/, + expressionConditionalOperator: /^expression \?:$/, + expressionAnyMember: /^expression (.+)\.\*$/, + expression: /^expression (.+)$/ + }; + this._pluginCompat.tap("Parser", options => { + for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) { + const regexp = HOOK_MAP_COMPAT_CONFIG[name]; + const match = regexp.exec(options.name); + if (match) { + if (match[1]) { + this.hooks[name].tap( + match[1], + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } else { + this.hooks[name].tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } + return true; + } + } + }); + this.options = options; + this.sourceType = sourceType; + this.scope = undefined; + this.state = undefined; + this.comments = undefined; + this.initializeEvaluating(); + } + + initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap("Parser", expr => { + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(expr.range); + } + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); + } + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { + let left; + let leftAsBool; + let right; + if (expr.operator === "&&") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === false) return left.setRange(expr.range); + if (leftAsBool !== true) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); + } else if (expr.operator === "||") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === true) return left.setRange(expr.range); + if (leftAsBool !== false) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); + } + }); + this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => { + let left; + let right; + let res; + if (expr.operator === "+") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString(left.string + right.string); + } else if (right.isNumber()) { + res.setString(left.string + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() + ) { + // "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.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; + } + } + res.setRange(expr.range); + return res; + } else if (expr.operator === "-") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number - right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "*") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number * right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "/") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number / right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "**") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(Math.pow(left.number, right.number)); + res.setRange(expr.range); + return res; + } else if (expr.operator === "==" || expr.operator === "===") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string === right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number === right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool === right.bool); + } + } else if (expr.operator === "!=" || expr.operator === "!==") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string !== right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number !== right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool !== right.bool); + } + } else if (expr.operator === "&") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number & right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "|") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number | right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "^") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number ^ right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >>> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "<<") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number << right.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => { + if (expr.operator === "typeof") { + let res; + let name; + if (expr.argument.type === "Identifier") { + name = + this.scope.renames.get(expr.argument.name) || expr.argument.name; + if (!this.scope.definitions.has(name)) { + const hook = this.hooks.evaluateTypeof.get(name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "MemberExpression") { + const exprName = this.getNameForExpression(expr.argument); + if (exprName && exprName.free) { + const hook = this.hooks.evaluateTypeof.get(exprName.name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "FunctionExpression") { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(expr.range); + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isString() || arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(expr.range); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(expr.range); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(expr.range); + } + if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(expr.range); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (argument.isBoolean()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.bool) + .setRange(expr.range); + } + if (argument.isTruthy()) { + return new BasicEvaluatedExpression() + .setBoolean(false) + .setRange(expr.range); + } + if (argument.isFalsy()) { + return new BasicEvaluatedExpression() + .setBoolean(true) + .setRange(expr.range); + } + if (argument.isString()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.string) + .setRange(expr.range); + } + if (argument.isNumber()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.number) + .setRange(expr.range); + } + } else if (expr.operator === "~") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (!argument.isNumber()) return; + const res = new BasicEvaluatedExpression(); + res.setNumber(~argument.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + }); + this.hooks.evaluate.for("Identifier").tap("Parser", expr => { + const name = this.scope.renames.get(expr.name) || expr.name; + if (!this.scope.definitions.has(expr.name)) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expr); + } + } + }); + this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => { + const name = this.scope.renames.get("this"); + if (name) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => { + let exprName = this.getNameForExpression(expression); + if (exprName) { + if (exprName.free) { + const hook = this.hooks.evaluateIdentifier.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(exprName.name) + .setRange(expression.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name); + if (hook !== undefined) { + return hook.call(expression); + } + } + } + }); + this.hooks.evaluate.for("CallExpression").tap("Parser", expr => { + if (expr.callee.type !== "MemberExpression") return; + if ( + expr.callee.property.type !== + (expr.callee.computed ? "Literal" : "Identifier") + ) + return; + const param = this.evaluateExpression(expr.callee.object); + if (!param) return; + const property = expr.callee.property.name || expr.callee.property.value; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); + } + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + let arg1 = this.evaluateExpression(expr.arguments[0]); + let arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + arg1 = arg1.regExp || arg1.string; + if (!arg2.isString()) return; + arg2 = arg2.string; + return new BasicEvaluatedExpression() + .setString(param.string.replace(arg1, arg2)) + .setRange(expr.range); + }); + ["substr", "substring"].forEach(fn => { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + let arg1; + let result, + str = param.string; + switch (expr.arguments.length) { + case 1: + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: { + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setRange(expr.range); + }); + }); + + /** + * @param {string} kind "cooked" | "raw" + * @param {TODO} templateLiteralExpr TemplateLiteral expr + * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template + */ + const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { + const quasis = []; + 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") { + // 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 + }; + }; + + this.hooks.evaluate.for("TemplateLiteral").tap("Parser", 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("Parser", node => { + if (this.evaluateExpression(node.tag).identifier !== "String.raw") return; + const { quasis, parts } = getSimplifiedTemplateResult("raw", node.quasi); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "raw") + .setRange(node.range); + }); + + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap("Parser", (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; + + let stringSuffix = null; + let hasUnknownParams = false; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const argExpr = this.evaluateExpression(expr.arguments[i]); + if (!argExpr.isString() && !argExpr.isNumber()) { + hasUnknownParams = true; + break; + } + + const value = argExpr.isString() + ? argExpr.string + : "" + argExpr.number; + + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setRange(newRange); + } + + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix) + .setRange(expr.range); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix) + .setRange(expr.range); + } else { + const newString = + param.string + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setRange(expr.range); + } + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = param.string.split(arg.string); + } else if (arg.isRegExp()) { + result = param.string.split(arg.regExp); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setRange(expr.range); + }); + this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => { + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + if (!consequent || !alternate) return; + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + } + res.setRange(expr.range); + return res; + }); + this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => { + const items = expr.elements.map(element => { + return element !== null && this.evaluateExpression(element); + }); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(items) + .setRange(expr.range); + }); + } + + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result && result.isIdentifier()) { + return result.identifier; + } + } + + walkClass(classy) { + if (classy.superClass) this.walkExpression(classy.superClass); + if (classy.body && classy.body.type === "ClassBody") { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + for (const methodDefinition of classy.body.body) { + if (methodDefinition.type === "MethodDefinition") { + this.walkMethodDefinition(methodDefinition); + } + } + this.scope.topLevelScope = wasTopLevel; + } + } + + walkMethodDefinition(methodDefinition) { + if (methodDefinition.computed && methodDefinition.key) { + this.walkExpression(methodDefinition.key); + } + if (methodDefinition.value) { + this.walkExpression(methodDefinition.value); + } + } + + // Prewalking iterates the scope for variable declarations + prewalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.prewalkStatement(statement); + } + } + + // Block-Prewalking 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) { + switch (statement.type) { + case "BlockStatement": + this.prewalkBlockStatement(statement); + break; + case "DoWhileStatement": + this.prewalkDoWhileStatement(statement); + break; + case "ExportAllDeclaration": + this.prewalkExportAllDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.prewalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.prewalkExportNamedDeclaration(statement); + break; + case "ForInStatement": + this.prewalkForInStatement(statement); + break; + case "ForOfStatement": + this.prewalkForOfStatement(statement); + break; + case "ForStatement": + this.prewalkForStatement(statement); + break; + case "FunctionDeclaration": + this.prewalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.prewalkIfStatement(statement); + break; + case "ImportDeclaration": + this.prewalkImportDeclaration(statement); + break; + case "LabeledStatement": + this.prewalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.prewalkSwitchStatement(statement); + break; + case "TryStatement": + this.prewalkTryStatement(statement); + break; + case "VariableDeclaration": + this.prewalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.prewalkWhileStatement(statement); + break; + case "WithStatement": + this.prewalkWithStatement(statement); + break; + } + } + + blockPrewalkStatement(statement) { + switch (statement.type) { + case "VariableDeclaration": + this.blockPrewalkVariableDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.blockPrewalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.blockPrewalkExportNamedDeclaration(statement); + break; + case "ClassDeclaration": + this.blockPrewalkClassDeclaration(statement); + break; + } + } + + walkStatement(statement) { + if (this.hooks.statement.call(statement) !== undefined) return; + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + } + + // Real Statements + prewalkBlockStatement(statement) { + this.prewalkStatements(statement.body); + } + + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + this.blockPrewalkStatements(body); + this.walkStatements(body); + }); + } + + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } + + prewalkIfStatement(statement) { + this.prewalkStatement(statement.consequent); + if (statement.alternate) { + this.prewalkStatement(statement.alternate); + } + } + + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkStatement(statement.consequent); + if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } else { + if (result) { + this.walkStatement(statement.consequent); + } else if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } + } + + prewalkLabeledStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.walkStatement(statement.body); + } + + prewalkWithStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkStatement(statement.body); + } + + prewalkSwitchStatement(statement) { + this.prewalkSwitchCases(statement.cases); + } + + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); + } + + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); + } + + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } + + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } + + prewalkTryStatement(statement) { + this.prewalkStatement(statement.block); + } + + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); + } else { + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; + } + if (statement.handler) this.walkCatchClause(statement.handler); + if (statement.finalizer) this.walkStatement(statement.finalizer); + } + + prewalkWhileStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkStatement(statement.body); + } + + prewalkDoWhileStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkDoWhileStatement(statement) { + this.walkStatement(statement.body); + this.walkExpression(statement.test); + } + + prewalkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.prewalkStatement(statement.init); + } + } + this.prewalkStatement(statement.body); + } + + walkForStatement(statement) { + this.inBlockScope(() => { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.blockPrewalkVariableDeclaration(statement.init); + 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 + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(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 + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(body); + } + }); + } + + prewalkForOfStatement(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); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(body); + } + }); + } + + // Declarations + prewalkFunctionDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); + } + } + + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inFunctionScope(true, statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + if (statement.body.type === "BlockStatement") { + this.detectMode(statement.body.body); + this.prewalkStatement(statement.body); + this.walkStatement(statement.body); + } else { + this.walkExpression(statement.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + prewalkImportDeclaration(statement) { + const source = statement.source.value; + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + this.scope.renames.set(name, null); + this.scope.definitions.add(name); + switch (specifier.type) { + case "ImportDefaultSpecifier": + this.hooks.importSpecifier.call(statement, source, "default", name); + break; + case "ImportSpecifier": + this.hooks.importSpecifier.call( + statement, + source, + specifier.imported.name, + name + ); + break; + case "ImportNamespaceSpecifier": + this.hooks.importSpecifier.call(statement, source, null, name); + break; + } + } + } + + 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; + } + } + + blockPrewalkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.blockPrewalkStatement(statement.declaration); + } + } + + prewalkExportNamedDeclaration(statement) { + let source; + if (statement.source) { + source = statement.source.value; + this.hooks.exportImport.call(statement, source); + } else { + this.hooks.export.call(statement); + } + if (statement.declaration) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.prewalkStatement(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; + } + } + } + } + } + + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } + } + + blockPrewalkExportDefaultDeclaration(statement) { + if (statement.declaration.type === "ClassDeclaration") { + this.blockPrewalkClassDeclaration(statement.declaration); + } + } + + prewalkExportDefaultDeclaration(statement) { + this.prewalkStatement(statement.declaration); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration.id.name, + "default" + ); + } + } + + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.walkStatement(statement.declaration); + } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if (statement.declaration.type === "FunctionDeclaration") { + this.walkFunctionDeclaration(statement.declaration); + } else if (statement.declaration.type === "ClassDeclaration") { + this.walkClassDeclaration(statement.declaration); + } else { + this.walkExpression(statement.declaration); + } + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration, + "default" + ); + } + } + } + + prewalkExportAllDeclaration(statement) { + const source = statement.source.value; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); + } + + prewalkVariableDeclaration(statement) { + 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": { + this.enterPattern(declarator.id, (name, decl) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(decl)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(decl)) { + this.scope.renames.set(name, null); + this.scope.definitions.add(name); + } + } + }); + break; + } + } + } + } + + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(declarator.init)) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(declarator.init)) { + this.scope.renames.set( + declarator.id.name, + this.scope.renames.get(renameIdentifier) || renameIdentifier + ); + this.scope.definitions.delete(declarator.id.name); + } + break; + } + } + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); + break; + } + } + } + } + + blockPrewalkClassDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); + } + } + + walkClassDeclaration(statement) { + this.walkClass(statement); + } + + prewalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.prewalkStatements(switchCase.consequent); + } + } + + walkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + this.walkStatements(switchCase.consequent); + } + } + + walkCatchClause(catchClause) { + this.inBlockScope(() => { + // Error binding is optional in catch clause since ECMAScript 2019 + if (catchClause.param !== null) { + this.enterPattern(catchClause.param, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); + this.walkPattern(catchClause.param); + } + this.prewalkStatement(catchClause.body); + this.walkStatement(catchClause.body); + }); + } + + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } + } + + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } + + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); + } + } + } + + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } + } + + walkRestElement(pattern) { + this.walkPattern(pattern.argument); + } + + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } + + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } + } + + walkAwaitExpression(expression) { + this.walkExpression(expression.argument); + } + + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } + } + + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + continue; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand) { + this.scope.inShorthand = true; + } + this.walkExpression(prop.value); + if (prop.shorthand) { + this.scope.inShorthand = false; + } + } + } + + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + 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); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + walkArrowFunctionExpression(expression) { + this.inFunctionScope(false, expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + } + + walkSequenceExpression(expression) { + if (expression.expressions) this.walkExpressions(expression.expressions); + } + + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } + + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const exprName = this.getNameForExpression(expression.argument); + if (exprName && exprName.free) { + const hook = this.hooks.typeof.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; + } + } + } + this.walkExpression(expression.argument); + } + + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); + } + + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); + } + + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else { + if (result) { + this.walkExpression(expression.right); + } + } + } + + walkAssignmentExpression(expression) { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if (expression.left.type === "Identifier" && renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(expression.right)) { + // renaming "a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(expression.right)) { + this.scope.renames.set(expression.left.name, renameIdentifier); + this.scope.definitions.delete(expression.left.name); + } + return; + } + } + if (expression.left.type === "Identifier") { + const assignedHook = this.hooks.assigned.get(expression.left.name); + if (assignedHook === undefined || !assignedHook.call(expression)) { + this.walkExpression(expression.right); + } + this.scope.renames.set(expression.left.name, null); + const assignHook = this.hooks.assign.get(expression.left.name); + if (assignHook === undefined || !assignHook.call(expression)) { + this.walkExpression(expression.left); + } + return; + } + this.walkExpression(expression.right); + this.walkPattern(expression.left); + this.enterPattern(expression.left, (name, decl) => { + this.scope.renames.set(name, null); + }); + } + + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + } + + walkNewExpression(expression) { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const hook = this.hooks.new.get(callee.identifier); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) { + return; + } + } + } + + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } + + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } + + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } + + walkClassExpression(expression) { + this.walkClass(expression); + } + + _walkIIFE(functionExpression, options, currentThis) { + const renameArgOrThis = argOrThis => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if (renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(argOrThis)) { + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(argOrThis)) { + return renameIdentifier; + } + } + } + this.walkExpression(argOrThis); + }; + const params = functionExpression.params; + const renameThis = currentThis ? renameArgOrThis(currentThis) : null; + const args = options.map(renameArgOrThis); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = params.filter((identifier, idx) => !args[idx]); + + // Add function name in scope for recursive calls + if (functionExpression.id) { + scopeParams.push(functionExpression.id.name); + } + + this.inFunctionScope(true, scopeParams, () => { + if (renameThis) { + this.scope.renames.set("this", renameThis); + } + for (let i = 0; i < args.length; i++) { + const param = args[i]; + if (!param) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.scope.renames.set(params[i].name, param); + } + if (functionExpression.body.type === "BlockStatement") { + this.detectMode(functionExpression.body.body); + this.prewalkStatement(functionExpression.body); + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + walkCallExpression(expression) { + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type === "FunctionExpression" && + !expression.callee.computed && + (expression.callee.property.name === "call" || + expression.callee.property.name === "bind") && + expression.arguments.length > 0 + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + expression.callee.object, + expression.arguments.slice(1), + expression.arguments[0] + ); + } else if (expression.callee.type === "FunctionExpression") { + // (function(…) { }(…)) + this._walkIIFE(expression.callee, expression.arguments, null); + } else if (expression.callee.type === "Import") { + let result = this.hooks.importCall.call(expression); + if (result === true) return; + + if (expression.arguments) this.walkExpressions(expression.arguments); + } else { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const callHook = this.hooks.call.get(callee.identifier); + if (callHook !== undefined) { + let result = callHook.call(expression); + if (result === true) return; + } + let identifier = callee.identifier.replace(/\.[^.]+$/, ""); + if (identifier !== callee.identifier) { + const callAnyHook = this.hooks.callAnyMember.get(identifier); + if (callAnyHook !== undefined) { + let result = callAnyHook.call(expression); + if (result === true) return; + } + } + } + + if (expression.callee) this.walkExpression(expression.callee); + if (expression.arguments) this.walkExpressions(expression.arguments); + } + } + + walkMemberExpression(expression) { + const exprName = this.getNameForExpression(expression); + if (exprName && exprName.free) { + const expressionHook = this.hooks.expression.get(exprName.name); + if (expressionHook !== undefined) { + const result = expressionHook.call(expression); + if (result === true) return; + } + const expressionAnyMemberHook = this.hooks.expressionAnyMember.get( + exprName.nameGeneral + ); + if (expressionAnyMemberHook !== undefined) { + const result = expressionAnyMemberHook.call(expression); + if (result === true) return; + } + } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); + } + + walkThisExpression(expression) { + const expressionHook = this.hooks.expression.get("this"); + if (expressionHook !== undefined) { + expressionHook.call(expression); + } + } + + walkIdentifier(expression) { + if (!this.scope.definitions.has(expression.name)) { + const hook = this.hooks.expression.get( + this.scope.renames.get(expression.name) || expression.name + ); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; + } + } + } + + /** + * @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(), + renames: oldScope.renames.createChild() + }; + + this.scope.renames.set("this", null); + + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); + + 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(), + renames: oldScope.renames.createChild() + }; + + if (hasThis) { + this.scope.renames.set("this", null); + } + + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); + + fn(); + + this.scope = oldScope; + } + + 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(), + renames: oldScope.renames.createChild() + }; + + fn(); + + this.scope = oldScope; + } + + // TODO webpack 5: remove this methods + // only for backward-compat + detectStrictMode(statements) { + this.detectMode(statements); + } + + 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; + } + } + + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); + } + } + } + + 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": + this.enterPattern(pattern.value, onIdent); + break; + } + } + + enterIdentifier(pattern, onIdent) { + onIdent(pattern.name, pattern); + } + + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } + } + + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + this.enterPattern(element, onIdent); + } + } + + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); + } + + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } + + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined) { + if (result) { + result.setExpression(expression); + } + return result; + } + } + } catch (e) { + console.warn(e); + // ignore error + } + return new BasicEvaluatedExpression() + .setRange(expression.range) + .setExpression(expression); + } + + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(expression.left) + + this.parseString(expression.right) + ); + } + break; + case "Literal": + return expression.value + ""; + } + throw new Error( + expression.type + " is not supported as parameter for require" + ); + } + + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString(expression.left); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + left.range[0], + right.range ? right.range[1] : left.range[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value, + code: false, + conditional: false + }; + } + } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; + } + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; + } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; + } + + parse(source, initialState) { + let ast; + let comments; + if (typeof source === "object" && source !== null) { + ast = source; + comments = source.comments; + } else { + comments = []; + ast = Parser.parse(source, { + sourceType: this.sourceType, + onComment: comments + }); + } + + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + isStrict: false, + isAsmJs: false, + definitions: new StackedSetMap(), + renames: new StackedSetMap() + }; + const state = (this.state = initialState || {}); + this.comments = comments; + if (this.hooks.program.call(ast, comments) === undefined) { + this.detectMode(ast.body); + this.prewalkStatements(ast.body); + this.blockPrewalkStatements(ast.body); + this.walkStatements(ast.body); + } + this.scope = oldScope; + this.state = oldState; + this.comments = oldComments; + return state; + } + + evaluate(source) { + const ast = Parser.parse("(" + source + ")", { + sourceType: this.sourceType, + locations: false + }); + // TODO(https://github.com/acornjs/acorn/issues/741) + // @ts-ignore + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); + } + // TODO(https://github.com/acornjs/acorn/issues/741) + // @ts-ignore + return this.evaluateExpression(ast.body[0].expression); + } + + getComments(range) { + return this.comments.filter( + comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] + ); + } + + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + let options = {}; + let errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + const val = vm.runInNewContext(`(function(){return {${value}};})()`); + Object.assign(options, val); + } catch (e) { + e.comment = comment; + errors.push(e); + } + } + } + return { options, errors }; + } + + getNameForExpression(expression) { + let expr = expression; + const exprName = []; + while ( + expr.type === "MemberExpression" && + expr.property.type === (expr.computed ? "Literal" : "Identifier") + ) { + exprName.push(expr.computed ? expr.property.value : expr.property.name); + expr = expr.object; + } + let free; + if (expr.type === "Identifier") { + free = !this.scope.definitions.has(expr.name); + exprName.push(this.scope.renames.get(expr.name) || expr.name); + } else if ( + expr.type === "ThisExpression" && + this.scope.renames.get("this") + ) { + free = true; + exprName.push(this.scope.renames.get("this")); + } else if (expr.type === "ThisExpression") { + free = this.scope.topLevelScope; + exprName.push("this"); + } else { + return null; + } + let prefix = ""; + for (let i = exprName.length - 1; i >= 2; i--) { + prefix += exprName[i] + "."; + } + if (exprName.length > 1) { + prefix += exprName[1]; + } + const name = prefix ? prefix + "." + exprName[0] : exprName[0]; + const nameGeneral = prefix; + return { + name, + nameGeneral, + free + }; + } + + static parse(code, options) { + const type = options ? options.sourceType : "module"; + const parserOptions = Object.assign( + Object.create(null), + defaultParserOptions, + options + ); + + if (type === "auto") { + parserOptions.sourceType = "module"; + } else if (parserOptions.sourceType === "script") { + parserOptions.allowReturnOutsideFunction = true; + } + + let ast; + let error; + let threw = false; + try { + ast = acornParser.parse(code, parserOptions); + } catch (e) { + error = e; + threw = true; + } + + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + parserOptions.allowReturnOutsideFunction = true; + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = acornParser.parse(code, parserOptions); + threw = false; + } catch (e) { + threw = true; + } + } + + if (threw) { + throw error; + } + + return ast; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Parser.prototype, "getCommentOptions", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {TODO} range Range + * @returns {void} + * @this {Parser} + */ + function(range) { + return this.parseCommentOptions(range).options; + }, + "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead" + ) +}); + +module.exports = Parser; + + +/***/ }), + +/***/ 23999: +/***/ ((__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__(85622); + +const BasicEvaluatedExpression = __webpack_require__(96770); +const ConstDependency = __webpack_require__(71101); +const UnsupportedFeatureWarning = __webpack_require__(99953); + +const ParserHelpers = exports; + +ParserHelpers.addParsedVariableToModule = (parser, name, expression) => { + if (!parser.state.current.addVariable) return false; + var deps = []; + parser.parse(expression, { + current: { + addDependency: dep => { + dep.userRequest = name; + deps.push(dep); + } + }, + module: parser.state.module + }); + parser.state.current.addVariable(name, expression, deps); + return true; +}; + +ParserHelpers.requireFileAsExpression = (context, pathToModule) => { + var moduleJsPath = path.relative(context, pathToModule); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); + } + return "require(" + JSON.stringify(moduleJsPath) + ")"; +}; + +ParserHelpers.toConstantDependency = (parser, value) => { + return function constDependency(expr) { + var dep = new ConstDependency(value, expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; + +ParserHelpers.toConstantDependencyWithWebpackRequire = (parser, value) => { + return function constDependencyWithWebpackRequire(expr) { + var dep = new ConstDependency(value, expr.range, true); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; + +ParserHelpers.evaluateToString = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToBoolean = value => { + return function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { + return function identifierExpression(expr) { + let evex = new BasicEvaluatedExpression() + .setIdentifier(identifier) + .setRange(expr.range); + if (truthy === true) { + evex = evex.setTruthy(); + } else if (truthy === false) { + evex = evex.setFalsy(); + } + return evex; + }; +}; + +ParserHelpers.expressionIsUnsupported = (parser, message) => { + return function unsupportedExpression(expr) { + var dep = new ConstDependency("(void 0)", expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + if (!parser.state.module) return; + parser.state.module.warnings.push( + new UnsupportedFeatureWarning(parser.state.module, message, expr.loc) + ); + return true; + }; +}; + +ParserHelpers.skipTraversal = function skipTraversal() { + return true; +}; + +ParserHelpers.approve = function approve() { + return true; +}; + + +/***/ }), + +/***/ 27850: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const PrefetchDependency = __webpack_require__(14237); + +class PrefetchPlugin { + constructor(context, request) { + if (!request) { + this.request = context; + } else { + this.context = context; + this.request = request; + } + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "PrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { + compilation.prefetch( + this.context || compiler.context, + new PrefetchDependency(this.request), + callback + ); + }); + } +} +module.exports = PrefetchPlugin; + + +/***/ }), + +/***/ 63123: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(26336); + +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ + +const createDefaultHandler = (profile, logger) => { + let lastState; + let lastStateTime; + + const defaultHandler = (percentage, msg, ...args) => { + logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); + if (profile) { + let state = msg; + state = state.replace(/^\d+\/\d+\s+/, ""); + if (percentage === 0) { + lastState = null; + lastStateTime = Date.now(); + } else if (state !== lastState || percentage === 1) { + const now = Date.now(); + if (lastState) { + const diff = now - lastStateTime; + const stateMsg = `${diff}ms ${lastState}`; + if (diff > 1000) { + logger.warn(stateMsg); + } else if (diff > 10) { + logger.info(stateMsg); + } else if (diff > 0) { + logger.log(stateMsg); + } else { + logger.debug(stateMsg); + } + } + lastState = state; + lastStateTime = now; + } + } + if (percentage === 1) logger.status(); + }; + + return defaultHandler; +}; + +class ProgressPlugin { + /** + * @param {ProgressPluginArgument} options options + */ + constructor(options) { + if (typeof options === "function") { + options = { + handler: options + }; + } + + options = options || {}; + validateOptions(schema, options, "Progress Plugin"); + options = Object.assign({}, ProgressPlugin.defaultOptions, options); + + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showActiveModules = options.activeModules; + } + + apply(compiler) { + const { modulesCount } = this; + const handler = + this.handler || + createDefaultHandler( + this.profile, + compiler.getInfrastructureLogger("webpack.Progress") + ); + const showEntries = this.showEntries; + const showModules = this.showModules; + const showActiveModules = this.showActiveModules; + if (compiler.compilers) { + const states = new Array(compiler.compilers.length); + compiler.compilers.forEach((compiler, idx) => { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + handler( + states + .map(state => (state && state[0]) || 0) + .reduce((a, b) => a + b) / states.length, + `[${idx}] ${msg}`, + ...args + ); + }).apply(compiler); + }); + } else { + let lastModulesCount = 0; + let lastEntriesCount = 0; + let moduleCount = modulesCount; + let entriesCount = 1; + let doneModules = 0; + let doneEntries = 0; + const activeModules = new Set(); + let lastActiveModule = ""; + + const update = () => { + const percentByModules = + doneModules / Math.max(lastModulesCount, moduleCount); + const percentByEntries = + doneEntries / Math.max(lastEntriesCount, entriesCount); + + const items = [ + 0.1 + Math.max(percentByModules, percentByEntries) * 0.6, + "building" + ]; + if (showEntries) { + items.push(`${doneEntries}/${entriesCount} entries`); + } + if (showModules) { + items.push(`${doneModules}/${moduleCount} modules`); + } + if (showActiveModules) { + items.push(`${activeModules.size} active`); + items.push(lastActiveModule); + } + handler(...items); + }; + + const moduleAdd = module => { + moduleCount++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.add(ident); + lastActiveModule = ident; + } + } + update(); + }; + + const entryAdd = (entry, name) => { + entriesCount++; + update(); + }; + + 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(); + }; + + const entryDone = (entry, name) => { + doneEntries++; + update(); + }; + + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = moduleCount; + lastEntriesCount = entriesCount; + moduleCount = entriesCount = 0; + doneModules = doneEntries = 0; + handler(0, "compiling"); + + compilation.hooks.buildModule.tap("ProgressPlugin", moduleAdd); + compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); + compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); + + compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); + compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); + compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); + + const hooks = { + finishModules: "finish module graph", + seal: "sealing", + beforeChunks: "chunk graph", + afterChunks: "after chunk graph", + optimizeDependenciesBasic: "basic dependencies optimization", + optimizeDependencies: "dependencies optimization", + optimizeDependenciesAdvanced: "advanced dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + optimize: "optimizing", + optimizeModulesBasic: "basic module optimization", + optimizeModules: "module optimization", + optimizeModulesAdvanced: "advanced module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunksBasic: "basic chunk optimization", + optimizeChunks: "chunk optimization", + optimizeChunksAdvanced: "advanced chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModulesBasic: "basic chunk modules optimization", + optimizeChunkModules: "chunk modules optimization", + optimizeChunkModulesAdvanced: "advanced chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + optimizeModuleOrder: "module order optimization", + advancedOptimizeModuleOrder: "advanced module order optimization", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + optimizeChunkOrder: "chunk order optimization", + beforeChunkIds: "before chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + additionalChunkAssets: "additional chunk assets processing", + record: "recording", + additionalAssets: "additional asset processing", + optimizeChunkAssets: "chunk asset optimization", + afterOptimizeChunkAssets: "after chunk asset optimization", + optimizeAssets: "asset optimization", + afterOptimizeAssets: "after asset optimization", + afterSeal: "after seal" + }; + const numberOfHooks = Object.keys(hooks).length; + Object.keys(hooks).forEach((name, idx) => { + const title = hooks[name]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[name].intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(percentage, title); + }, + tap: (context, tap) => { + if (context) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + context.reportProgress = (p, ...args) => { + handler(percentage, title, tap.name, ...args); + }; + } + handler(percentage, title, tap.name); + } + }); + }); + }); + compiler.hooks.emit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.95, "emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.95, "emitting", tap.name, ...args); + }; + } + handler(0.95, "emitting", tap.name); + } + }); + compiler.hooks.afterEmit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.98, "after emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.98, "after emitting", tap.name, ...args); + }; + } + handler(0.98, "after emitting", tap.name); + } + }); + compiler.hooks.done.tap("ProgressPlugin", () => { + handler(1, ""); + }); + } + } +} + +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 500, + modules: true, + activeModules: true, + // TODO webpack 5 default this to true + entries: false +}; + +module.exports = ProgressPlugin; + + +/***/ }), + +/***/ 72861: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); + +const NullFactory = __webpack_require__(40438); + +class ProvidePlugin { + constructor(definitions) { + this.definitions = definitions; + } + + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "ProvidePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + Object.keys(definitions).forEach(name => { + var request = [].concat(definitions[name]); + var splittedName = name.split("."); + if (splittedName.length > 0) { + splittedName.slice(1).forEach((_, i) => { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(name) + .tap("ProvidePlugin", ParserHelpers.approve); + }); + } + parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { + let nameIdentifier = name; + const scopedName = name.includes("."); + let expression = `require(${JSON.stringify(request[0])})`; + if (scopedName) { + nameIdentifier = `__webpack_provided_${name.replace( + /\./g, + "_dot_" + )}`; + } + if (request.length > 1) { + expression += request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + } + if ( + !ParserHelpers.addParsedVariableToModule( + parser, + nameIdentifier, + expression + ) + ) { + return false; + } + if (scopedName) { + ParserHelpers.toConstantDependency( + parser, + nameIdentifier + )(expr); + } + return true; + }); + }); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ProvidePlugin", handler); + + // Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032 + } + ); + } +} +module.exports = ProvidePlugin; + + +/***/ }), + +/***/ 82353: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Module = __webpack_require__(75993); +const { OriginalSource, RawSource } = __webpack_require__(53665); + +module.exports = class RawModule extends Module { + constructor(source, identifier, readableIdentifier) { + super("javascript/dynamic", null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.built = false; + } + + identifier() { + return this.identifierStr; + } + + size() { + return this.sourceStr.length; + } + + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); + } + + needRebuild() { + return false; + } + + build(options, compilations, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } + + source() { + if (this.useSourceMap) { + return new OriginalSource(this.sourceStr, this.identifier()); + } else { + return new RawSource(this.sourceStr); + } + } + + updateHash(hash) { + hash.update(this.sourceStr); + super.updateHash(hash); + } +}; + + +/***/ }), + +/***/ 40355: +/***/ ((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__(94658); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Chunk")} Chunk */ +/** @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 {Record=} usedIds + */ + +/** + * @typedef {Object} Records + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + */ + +class RecordIdsPlugin { + /** + * @param {Object} options Options object + * @param {boolean=} options.portableIds true, when ids need to be portable + */ + constructor(options) { + this.options = options || {}; + } + + /** + * @param {Compiler} compiler the Compiler + * @returns {void} + */ + apply(compiler) { + const portableIds = this.options.portableIds; + compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { + compilation.hooks.recordModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + if (!records.modules.usedIds) records.modules.usedIds = {}; + for (const module of modules) { + if (typeof module.id !== "number") continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + records.modules.byIdentifier[identifier] = module.id; + records.modules.usedIds[module.id] = module.id; + } + } + ); + compilation.hooks.reviveModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + if (module.id !== null) continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + module.id = id; + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + } + ); + + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = module => { + if (portableIds) { + return identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ); + } + return module.identifier(); + }; + + /** + * @param {Chunk} chunk the chunk + * @returns {string[]} sources of the chunk + */ + const getChunkSources = chunk => { + /** @type {string[]} */ + const sources = []; + for (const chunkGroup of chunk.groupsIterable) { + const index = chunkGroup.chunks.indexOf(chunk); + 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" && + origin.loc.start + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + } + return sources; + }; + + compilation.hooks.recordChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.bySource) records.chunks.bySource = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const chunk of chunks) { + if (typeof chunk.id !== "number") continue; + const name = chunk.name; + if (name) records.chunks.byName[name] = chunk.id; + const sources = getChunkSources(chunk); + for (const source of sources) { + records.chunks.bySource[source] = chunk.id; + } + usedIds.add(chunk.id); + } + records.chunks.usedIds = Array.from(usedIds).sort(); + } + ); + compilation.hooks.reviveChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) return; + /** @type {Set} */ + const usedIds = new Set(); + if (records.chunks.byName) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + if (!chunk.name) continue; + const id = records.chunks.byName[chunk.name]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + const sources = getChunkSources(chunk); + for (const source of sources) { + const id = records.chunks.bySource[source]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } + } + ); + }); + } +} +module.exports = RecordIdsPlugin; + + +/***/ }), + +/***/ 15377: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const WebpackError = __webpack_require__(97391); + +module.exports = class RemovedPluginError extends WebpackError { + constructor(message) { + super(message); + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 54254: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; +const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; +const SEPARATOR_REGEXP = /[/\\]$/; +const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g; +const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g; +const MATCH_RESOURCE_REGEXP = /!=!/; + +const normalizeBackSlashDirection = request => { + return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); +}; + +const createRegExpForPath = path => { + const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); + return new RegExp(`(^|!)${regexpTypePartial}`, "g"); +}; + +class RequestShortener { + constructor(directory) { + directory = normalizeBackSlashDirection(directory); + if (SEPARATOR_REGEXP.test(directory)) { + directory = directory.substr(0, directory.length - 1); + } + + if (directory) { + this.currentDirectoryRegExp = createRegExpForPath(directory); + } + + const dirname = path.dirname(directory); + const endsWithSeparator = SEPARATOR_REGEXP.test(dirname); + const parentDirectory = endsWithSeparator + ? dirname.substr(0, dirname.length - 1) + : dirname; + if (parentDirectory && parentDirectory !== directory) { + this.parentDirectoryRegExp = createRegExpForPath(`${parentDirectory}/`); + } + + if (__dirname.length >= 2) { + const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); + const buildinsAsModule = + this.currentDirectoryRegExp && + this.currentDirectoryRegExp.test(buildins); + this.buildinsAsModule = buildinsAsModule; + this.buildinsRegExp = createRegExpForPath(buildins); + } + + this.cache = new Map(); + } + + shorten(request) { + if (!request) return request; + const cacheEntry = this.cache.get(request); + if (cacheEntry !== undefined) { + return cacheEntry; + } + let result = normalizeBackSlashDirection(request); + if (this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); + } + if (this.currentDirectoryRegExp) { + result = result.replace(this.currentDirectoryRegExp, "!."); + } + if (this.parentDirectoryRegExp) { + result = result.replace(this.parentDirectoryRegExp, "!../"); + } + if (!this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); + } + result = result.replace(INDEX_JS_REGEXP, "$1"); + result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); + result = result.replace(MATCH_RESOURCE_REGEXP, " = "); + this.cache.set(request, result); + return result; + } +} + +module.exports = RequestShortener; + + +/***/ }), + +/***/ 88226: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); + +module.exports = class RequireJsStuffPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + if (parserOptions.requireJs !== undefined && !parserOptions.requireJs) + return; + + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + + parser.hooks.expression + .for("require.version") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("0.0.0") + ) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.oe" + ) + ); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireJsStuffPlugin", handler); + } + ); + } +}; + + +/***/ }), + +/***/ 50588: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + +const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(92402); +const Factory = __webpack_require__(87450).ResolverFactory; +const { cachedCleverMerge } = __webpack_require__(67916); + +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ + +const EMTPY_RESOLVE_OPTIONS = {}; + +module.exports = class ResolverFactory extends Tapable { + constructor() { + super(); + this.hooks = { + resolveOptions: new HookMap( + () => new SyncWaterfallHook(["resolveOptions"]) + ), + resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"])) + }; + this._pluginCompat.tap("ResolverFactory", options => { + let match; + match = /^resolve-options (.+)$/.exec(options.name); + if (match) { + this.hooks.resolveOptions + .for(match[1]) + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + match = /^resolver (.+)$/.exec(options.name); + if (match) { + this.hooks.resolver + .for(match[1]) + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + }); + this.cache2 = new Map(); + } + + get(type, resolveOptions) { + resolveOptions = resolveOptions || EMTPY_RESOLVE_OPTIONS; + const ident = `${type}|${JSON.stringify(resolveOptions)}`; + const resolver = this.cache2.get(ident); + if (resolver) return resolver; + const newResolver = this._create(type, resolveOptions); + this.cache2.set(ident, newResolver); + return newResolver; + } + + _create(type, resolveOptions) { + const originalResolveOptions = Object.assign({}, resolveOptions); + resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); + const resolver = Factory.createResolver(resolveOptions); + if (!resolver) { + throw new Error("No resolver created"); + } + /** @type {Map} */ + const childCache = new Map(); + 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); + return resolver; + } +}; + + +/***/ }), + +/***/ 84247: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* +: +: [] +: { + resource: { + test: , + include: , + exclude: , + }, + resource: , -> resource.test + test: , -> resource.test + include: , -> resource.include + exclude: , -> resource.exclude + resourceQuery: , + compiler: , + issuer: , + use: "loader", -> use[0].loader + loader: <>, -> use[0].loader + loaders: <>, -> use + options: {}, -> use[0].options, + query: {}, -> options + parser: {}, + use: [ + "loader" -> use[x].loader + ], + use: [ + { + loader: "loader", + options: {} + } + ], + rules: [ + + ], + oneOf: [ + + ] +} + +: /regExp/ +: function(arg) {} +: "starting" +: [] // or +: { and: [] } +: { or: [] } +: { not: [] } +: { test: , include: , exclude: } + + +normalized: + +{ + resource: function(), + resourceQuery: function(), + compiler: function(), + issuer: function(), + use: [ + { + loader: string, + options: string, + : + } + ], + rules: [], + oneOf: [], + : , +} + +*/ + + + +const notMatcher = matcher => { + return str => { + return !matcher(str); + }; +}; + +const orMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (items[i](str)) return true; + } + return false; + }; +}; + +const andMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (!items[i](str)) return false; + } + return true; + }; +}; + +module.exports = class RuleSet { + constructor(rules) { + this.references = Object.create(null); + this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); + } + + static normalizeRules(rules, refs, ident) { + if (Array.isArray(rules)) { + return rules.map((rule, idx) => { + return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`); + }); + } else if (rules) { + return [RuleSet.normalizeRule(rules, refs, ident)]; + } else { + return []; + } + } + + static normalizeRule(rule, refs, ident) { + if (typeof rule === "string") { + return { + use: [ + { + loader: rule + } + ] + }; + } + if (!rule) { + throw new Error("Unexcepted null when object was expected as rule"); + } + if (typeof rule !== "object") { + throw new Error( + "Unexcepted " + + typeof rule + + " when object was expected as rule (" + + rule + + ")" + ); + } + + const newRule = {}; + let useSource; + let resourceSource; + let condition; + + const checkUseSource = newSource => { + if (useSource && useSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one result source (provided " + + newSource + + " and " + + useSource + + ")" + ) + ) + ); + } + useSource = newSource; + }; + + const checkResourceSource = newSource => { + if (resourceSource && resourceSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one resource source (provided " + + newSource + + " and " + + resourceSource + + ")" + ) + ) + ); + } + resourceSource = newSource; + }; + + if (rule.test || rule.include || rule.exclude) { + checkResourceSource("test + include + exclude"); + condition = { + test: rule.test, + include: rule.include, + exclude: rule.exclude + }; + try { + newRule.resource = RuleSet.normalizeCondition(condition); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(condition, error)); + } + } + + if (rule.resource) { + checkResourceSource("resource"); + try { + newRule.resource = RuleSet.normalizeCondition(rule.resource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); + } + } + + if (rule.realResource) { + try { + newRule.realResource = RuleSet.normalizeCondition(rule.realResource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); + } + } + + if (rule.resourceQuery) { + try { + newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); + } + } + + if (rule.compiler) { + try { + newRule.compiler = RuleSet.normalizeCondition(rule.compiler); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); + } + } + + if (rule.issuer) { + try { + newRule.issuer = RuleSet.normalizeCondition(rule.issuer); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + } + } + + if (rule.loader && rule.loaders) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Provided loader and loaders for rule (use only one of them)" + ) + ) + ); + } + + const loader = rule.loaders || rule.loader; + if (typeof loader === "string" && !rule.options && !rule.query) { + checkUseSource("loader"); + newRule.use = RuleSet.normalizeUse(loader.split("!"), ident); + } else if (typeof loader === "string" && (rule.options || rule.query)) { + checkUseSource("loader + options/query"); + newRule.use = RuleSet.normalizeUse( + { + loader: loader, + options: rule.options, + query: rule.query + }, + ident + ); + } else if (loader && (rule.options || rule.query)) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query cannot be used with loaders (use options for each array item)" + ) + ) + ); + } else if (loader) { + checkUseSource("loaders"); + newRule.use = RuleSet.normalizeUse(loader, ident); + } else if (rule.options || rule.query) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query provided without loader (use loader + options)" + ) + ) + ); + } + + if (rule.use) { + checkUseSource("use"); + newRule.use = RuleSet.normalizeUse(rule.use, ident); + } + + if (rule.rules) { + newRule.rules = RuleSet.normalizeRules( + rule.rules, + refs, + `${ident}-rules` + ); + } + + if (rule.oneOf) { + newRule.oneOf = RuleSet.normalizeRules( + rule.oneOf, + refs, + `${ident}-oneOf` + ); + } + + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "resourceQuery", + "compiler", + "test", + "include", + "exclude", + "issuer", + "loader", + "options", + "query", + "loaders", + "use", + "rules", + "oneOf" + ].includes(key); + }); + for (const key of keys) { + newRule[key] = rule[key]; + } + + if (Array.isArray(newRule.use)) { + for (const item of newRule.use) { + if (item.ident) { + refs[item.ident] = item.options; + } + } + } + + return newRule; + } + + static buildErrorMessage(condition, error) { + const conditionAsText = JSON.stringify( + condition, + (key, value) => { + return value === undefined ? "undefined" : value; + }, + 2 + ); + return error.message + " in " + conditionAsText; + } + + static normalizeUse(use, ident) { + if (typeof use === "function") { + return data => RuleSet.normalizeUse(use(data), ident); + } + if (Array.isArray(use)) { + return use + .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) + .reduce((arr, items) => arr.concat(items), []); + } + return [RuleSet.normalizeUseItem(use, ident)]; + } + + static normalizeUseItemString(useItemString) { + const idx = useItemString.indexOf("?"); + if (idx >= 0) { + return { + loader: useItemString.substr(0, idx), + options: useItemString.substr(idx + 1) + }; + } + return { + loader: useItemString, + options: undefined + }; + } + + static normalizeUseItem(item, ident) { + if (typeof item === "string") { + return RuleSet.normalizeUseItemString(item); + } + + const newItem = {}; + + if (item.options && item.query) { + throw new Error("Provided options and query in use"); + } + + if (!item.loader) { + throw new Error("No loader specified"); + } + + newItem.options = item.options || item.query; + + if (typeof newItem.options === "object" && newItem.options) { + if (newItem.options.ident) { + newItem.ident = newItem.options.ident; + } else { + newItem.ident = ident; + } + } + + const keys = Object.keys(item).filter(function(key) { + return !["options", "query"].includes(key); + }); + + for (const key of keys) { + newItem[key] = item[key]; + } + + return newItem; + } + + static normalizeCondition(condition) { + if (!condition) throw new Error("Expected condition but got falsy value"); + if (typeof condition === "string") { + return str => str.indexOf(condition) === 0; + } + if (typeof condition === "function") { + return condition; + } + if (condition instanceof RegExp) { + return condition.test.bind(condition); + } + if (Array.isArray(condition)) { + const items = condition.map(c => RuleSet.normalizeCondition(c)); + return orMatcher(items); + } + if (typeof condition !== "object") { + throw Error( + "Unexcepted " + + typeof condition + + " when condition was expected (" + + condition + + ")" + ); + } + + const matchers = []; + Object.keys(condition).forEach(key => { + const value = condition[key]; + switch (key) { + case "or": + case "include": + case "test": + if (value) matchers.push(RuleSet.normalizeCondition(value)); + break; + case "and": + if (value) { + const items = value.map(c => RuleSet.normalizeCondition(c)); + matchers.push(andMatcher(items)); + } + break; + case "not": + case "exclude": + if (value) { + const matcher = RuleSet.normalizeCondition(value); + matchers.push(notMatcher(matcher)); + } + break; + default: + throw new Error("Unexcepted property " + key + " in condition"); + } + }); + if (matchers.length === 0) { + throw new Error("Excepted condition but got " + condition); + } + if (matchers.length === 1) { + return matchers[0]; + } + return andMatcher(matchers); + } + + exec(data) { + const result = []; + this._run( + data, + { + rules: this.rules + }, + result + ); + return result; + } + + _run(data, rule, result) { + // test conditions + if (rule.resource && !data.resource) return false; + if (rule.realResource && !data.realResource) return false; + if (rule.resourceQuery && !data.resourceQuery) return false; + if (rule.compiler && !data.compiler) return false; + if (rule.issuer && !data.issuer) return false; + if (rule.resource && !rule.resource(data.resource)) return false; + if (rule.realResource && !rule.realResource(data.realResource)) + return false; + if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false; + if ( + data.resourceQuery && + rule.resourceQuery && + !rule.resourceQuery(data.resourceQuery) + ) { + return false; + } + if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { + return false; + } + + // apply + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "realResource", + "resourceQuery", + "compiler", + "issuer", + "rules", + "oneOf", + "use", + "enforce" + ].includes(key); + }); + for (const key of keys) { + result.push({ + type: key, + value: rule[key] + }); + } + + if (rule.use) { + const process = use => { + if (typeof use === "function") { + process(use(data)); + } else if (Array.isArray(use)) { + use.forEach(process); + } else { + result.push({ + type: "use", + value: use, + enforce: rule.enforce + }); + } + }; + process(rule.use); + } + + if (rule.rules) { + for (let i = 0; i < rule.rules.length; i++) { + this._run(data, rule.rules[i], result); + } + } + + if (rule.oneOf) { + for (let i = 0; i < rule.oneOf.length; i++) { + if (this._run(data, rule.oneOf[i], result)) break; + } + } + + return true; + } + + findOptionsByIdent(ident) { + const options = this.references[ident]; + if (!options) { + throw new Error("Can't find options with ident '" + ident + "'"); + } + return options; + } +}; + + +/***/ }), + +/***/ 44006: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); + +/** @typedef {import("./Module")} Module */ + +module.exports = class RuntimeTemplate { + constructor(outputOptions, requestShortener) { + this.outputOptions = outputOptions || {}; + this.requestShortener = requestShortener; + } + + /** + * 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) + " "; + } + } + + throwMissingModuleErrorFunction({ request }) { + const err = `Cannot find module '${request}'`; + return `function webpackMissingModule() { var e = new Error(${JSON.stringify( + err + )}); e.code = 'MODULE_NOT_FOUND'; throw e; }`; + } + + missingModule({ request }) { + return `!(${this.throwMissingModuleErrorFunction({ request })}())`; + } + + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; + } + + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; + } + + moduleId({ module, request }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (module.id === null) { + throw new Error( + `RuntimeTemplate.moduleId(): Module ${module.identifier()} has no id. This should not happen.` + ); + } + return `${this.comment({ request })}${JSON.stringify(module.id)}`; + } + + moduleRaw({ module, request }) { + if (!module) { + return this.missingModule({ + request + }); + } + return `__webpack_require__(${this.moduleId({ module, request })})`; + } + + moduleExports({ module, request }) { + return this.moduleRaw({ + module, + request + }); + } + + moduleNamespace({ module, request, strict }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = this.moduleId({ + module, + request + }); + const exportsType = module.buildMeta && module.buildMeta.exportsType; + if (exportsType === "namespace") { + const rawModule = this.moduleRaw({ + module, + request + }); + return rawModule; + } else if (exportsType === "named") { + return `__webpack_require__.t(${moduleId}, 3)`; + } else if (strict) { + return `__webpack_require__.t(${moduleId}, 1)`; + } else { + return `__webpack_require__.t(${moduleId}, 7)`; + } + } + + moduleNamespacePromise({ block, module, request, message, strict, weak }) { + if (!module) { + return this.missingModulePromise({ + request + }); + } + if (module.id === null) { + throw new Error( + `RuntimeTemplate.moduleNamespacePromise(): Module ${module.identifier()} has no id. This should not happen.` + ); + } + const promise = this.blockPromise({ + block, + message + }); + + let getModuleFunction; + let idExpr = JSON.stringify(module.id); + 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"; + } + header += `if(!__webpack_require__.m[${idExpr}]) { var e = new Error("Module '" + ${idExpr} + "' is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } `; + } + const moduleId = this.moduleId({ + module, + request + }); + const exportsType = module.buildMeta && module.buildMeta.exportsType; + if (exportsType === "namespace") { + if (header) { + const rawModule = this.moduleRaw({ + module, + request + }); + getModuleFunction = `function() { ${header}return ${rawModule}; }`; + } else { + getModuleFunction = `__webpack_require__.bind(null, ${comment}${idExpr})`; + } + } else if (exportsType === "named") { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 3); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 3)`; + } + } else if (strict) { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 1); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 1)`; + } + } else { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 7); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 7)`; + } + } + + return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`; + } + + /** + * + * @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 {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 + * @returns {string} the import statement + */ + importStatement({ update, module, request, importVar, originModule }) { + if (!module) { + return this.missingModuleStatement({ + request + }); + } + const moduleId = this.moduleId({ + module, + request + }); + const optDeclaration = update ? "" : "var "; + + const exportsType = module.buildMeta && module.buildMeta.exportsType; + let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; + + if (!exportsType && !originModule.buildMeta.strictHarmonyModule) { + content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; + } + if (exportsType === "named") { + if (Array.isArray(module.buildMeta.providedExports)) { + content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId}, 1);\n`; + } else { + content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId});\n`; + } + } + return content; + } + + exportFromImport({ + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + importVar + }) { + if (!module) { + return this.missingModule({ + request + }); + } + const exportsType = module.buildMeta && module.buildMeta.exportsType; + + if (!exportsType) { + if (exportName === "default") { + if (!originModule.buildMeta.strictHarmonyModule) { + if (isCall) { + return `${importVar}_default()`; + } else if (asiSafe) { + return `(${importVar}_default())`; + } else { + return `${importVar}_default.a`; + } + } else { + return importVar; + } + } else if (originModule.buildMeta.strictHarmonyModule) { + if (exportName) { + return "/* non-default import from non-esm module */undefined"; + } else { + return `/*#__PURE__*/__webpack_require__.t(${importVar})`; + } + } + } + + if (exportsType === "named") { + if (exportName === "default") { + return importVar; + } else if (!exportName) { + return `${importVar}_namespace`; + } + } + + if (exportName) { + const used = module.isUsed(exportName); + if (!used) { + const comment = Template.toNormalComment(`unused export ${exportName}`); + return `${comment} undefined`; + } + const comment = + used !== exportName ? Template.toNormalComment(exportName) + " " : ""; + const access = `${importVar}[${comment}${JSON.stringify(used)}]`; + if (isCall) { + if (callContext === false && asiSafe) { + return `(0,${access})`; + } else if (callContext === false) { + return `Object(${access})`; + } + } + return access; + } else { + return importVar; + } + } + + blockPromise({ block, message }) { + if (!block || !block.chunkGroup || block.chunkGroup.chunks.length === 0) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunks = block.chunkGroup.chunks.filter( + chunk => !chunk.hasRuntime() && chunk.id !== null + ); + const comment = this.comment({ + message, + chunkName: block.chunkName, + chunkReason: block.chunkReason + }); + if (chunks.length === 1) { + const chunkId = JSON.stringify(chunks[0].id); + return `__webpack_require__.e(${comment}${chunkId})`; + } else if (chunks.length > 0) { + const requireChunkId = chunk => + `__webpack_require__.e(${JSON.stringify(chunk.id)})`; + return `Promise.all(${comment.trim()}[${chunks + .map(requireChunkId) + .join(", ")}])`; + } else { + return `Promise.resolve(${comment.trim()})`; + } + } + + onError() { + return "__webpack_require__.oe"; + } + + defineEsModuleFlagStatement({ exportsArgument }) { + return `__webpack_require__.r(${exportsArgument});\n`; + } +}; + + +/***/ }), + +/***/ 37098: +/***/ ((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__(53665); + +/** @typedef {import("./Compilation")} Compilation */ + +class SetVarMainTemplatePlugin { + /** + * @param {string} varExpression the accessor where the library is exported + * @param {boolean} copyObject specify copying the exports + */ + constructor(varExpression, copyObject) { + /** @type {string} */ + this.varExpression = varExpression; + /** @type {boolean} */ + this.copyObject = copyObject; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const varExpression = mainTemplate.getAssetPath(this.varExpression, { + hash, + chunk + }); + if (this.copyObject) { + return new ConcatSource( + `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, + source, + "))" + ); + } else { + const prefix = `${varExpression} =\n`; + return new ConcatSource(prefix, source); + } + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "SetVarMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap( + "SetVarMainTemplatePlugin", + paths => { + if (this.varExpression) paths.push(this.varExpression); + return paths; + } + ); + mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => { + hash.update("set var"); + hash.update(`${this.varExpression}`); + hash.update(`${this.copyObject}`); + }); + } +} + +module.exports = SetVarMainTemplatePlugin; + + +/***/ }), + +/***/ 19070: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const SingleEntryDependency = __webpack_require__(84828); + +/** @typedef {import("./Compiler")} Compiler */ + +class SingleEntryPlugin { + /** + * An entry plugin which will handle + * creation of the SingleEntryDependency + * + * @param {string} context context path + * @param {string} entry entry path + * @param {string} name entry key name + */ + constructor(context, entry, name) { + this.context = context; + this.entry = entry; + this.name = name; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "SingleEntryPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "SingleEntryPlugin", + (compilation, callback) => { + const { entry, name, context } = this; + + const dep = SingleEntryPlugin.createDependency(entry, name); + compilation.addEntry(context, dep, name, callback); + } + ); + } + + /** + * @param {string} entry entry request + * @param {string} name entry name + * @returns {SingleEntryDependency} the dependency + */ + static createDependency(entry, name) { + const dep = new SingleEntryDependency(entry); + dep.loc = { name }; + return dep; + } +} + +module.exports = SingleEntryPlugin; + + +/***/ }), + +/***/ 12496: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + +const SizeFormatHelpers = exports; + +SizeFormatHelpers.formatSize = size => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; + } + + if (size <= 0) { + return "0 bytes"; + } + + const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; + const index = Math.floor(Math.log(size) / Math.log(1024)); + + return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ + abbreviations[index] + }`; +}; + + +/***/ }), + +/***/ 24113: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ModuleFilenameHelpers = __webpack_require__(71474); + +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; + } + + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + } + if (options.lineToLine === true) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.lineToLine = true; + } + ); + } else if (options.lineToLine) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + if (!module.resource) return; + let resourcePath = module.resource; + const idx = resourcePath.indexOf("?"); + if (idx >= 0) resourcePath = resourcePath.substr(0, idx); + module.lineToLine = ModuleFilenameHelpers.matchObject( + options.lineToLine, + resourcePath + ); + } + ); + } + } +} + +module.exports = SourceMapDevToolModuleOptionsPlugin; + + +/***/ }), + +/***/ 11851: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const { ConcatSource, RawSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); +const createHash = __webpack_require__(15660); +const { absolutify } = __webpack_require__(94658); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(7368); + +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("source-map").RawSourceMap} SourceMap */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compilation")} SourceMapDefinition */ + +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {Array} [modules] + * @property {string} source + * @property {string} file + * @property {SourceMap} sourceMap + * @property {Chunk} chunk + */ + +/** + * @param {string} name file path + * @returns {string} file name + */ +const basename = name => { + if (!name.includes("/")) return name; + return name.substr(name.lastIndexOf("/") + 1); +}; + +/** + * @type {WeakMap} + */ +const assetsCache = new WeakMap(); + +/** + * Creating {@link SourceMapTask} for given file + * @param {string} file current compiled file + * @param {Source} asset the asset + * @param {Chunk} chunk related chunk + * @param {SourceMapDevToolPluginOptions} options source map options + * @param {Compilation} compilation compilation instance + * @returns {SourceMapTask | undefined} created task instance or `undefined` + */ +const getTaskForFile = (file, asset, chunk, options, compilation) => { + let source, sourceMap; + /** + * Check if asset can build source map + */ + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = sourceAndMap.map; + source = sourceAndMap.source; + } else { + sourceMap = asset.map(options); + source = asset.source(); + } + if (!sourceMap || typeof source !== "string") return; + const context = compilation.options.context; + const modules = sourceMap.sources.map(source => { + if (source.startsWith("webpack://")) { + source = absolutify(context, source.slice(10)); + } + const module = compilation.findModule(source); + return module || source; + }); + + return { + chunk, + file, + asset, + source, + sourceMap, + modules + }; +}; + +class SourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions} [options] options object + * @throws {Error} throws error, if got more than 1 arguments + */ + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "SourceMapDevToolPlugin only takes one argument (pass an options object)" + ); + } + + if (!options) options = {}; + + validateOptions(schema, options, "SourceMap DevTool Plugin"); + + /** @type {string | false} */ + this.sourceMapFilename = options.filename; + /** @type {string | false} */ + this.sourceMappingURLComment = + options.append === false + ? false + : options.append || "\n//# sourceMappingURL=[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; + } + + /** + * Apply compiler + * @param {Compiler} compiler compiler instance + * @returns {void} + */ + apply(compiler) { + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || /\.(m?js|css)($|\?)/i; + + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + + compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + + compilation.hooks.afterOptimizeChunkAssets.tap( + /** @type {TODO} */ + ({ name: "SourceMapDevToolPlugin", context: true }), + /** + * @param {object} context hook context + * @param {Array} chunks resulted chunks + * @throws {Error} throws error, if `sourceMapFilename === false && sourceMappingURLComment === false` + * @returns {void} + */ + (context, chunks) => { + /** @type {Map} */ + const moduleToSourceNameMapping = new Map(); + /** + * @type {Function} + * @returns {void} + */ + const reportProgress = + context && context.reportProgress + ? context.reportProgress + : () => {}; + + const files = []; + for (const chunk of chunks) { + for (const file of chunk.files) { + if (matchObject(file)) { + files.push({ + file, + chunk + }); + } + } + } + + reportProgress(0.0); + const tasks = []; + files.forEach(({ file, chunk }, idx) => { + const asset = compilation.getAsset(file).source; + const cache = assetsCache.get(asset); + /** + * If presented in cache, reassigns assets. Cache assets already have source maps. + */ + if (cache && cache.file === file) { + for (const cachedFile in cache.assets) { + if (cachedFile === file) { + compilation.updateAsset(cachedFile, cache.assets[cachedFile]); + } else { + compilation.emitAsset(cachedFile, cache.assets[cachedFile], { + development: true + }); + } + /** + * Add file to chunk, if not presented there + */ + if (cachedFile !== file) chunk.files.push(cachedFile); + } + return; + } + + reportProgress( + (0.5 * idx) / files.length, + file, + "generate SourceMap" + ); + /** @type {SourceMapTask | undefined} */ + const task = getTaskForFile( + file, + asset, + chunk, + options, + compilation + ); + + if (task) { + const modules = task.modules; + + 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 + ) + ); + } + } + + tasks.push(task); + } + }); + + 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 + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } + + // elsewise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + tasks.forEach((task, index) => { + reportProgress( + 0.5 + (0.5 * index) / tasks.length, + task.file, + "attach SourceMap" + ); + const assets = Object.create(null); + const chunk = task.chunk; + const file = task.file; + const asset = task.asset; + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + const moduleFilenames = modules.map(m => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + assetsCache.set(asset, { file, assets }); + /** @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; + let query = ""; + const idx = filename.indexOf("?"); + if (idx >= 0) { + query = filename.substr(idx); + filename = filename.substr(0, idx); + } + const pathParams = { + chunk, + filename: options.fileContext + ? path.relative(options.fileContext, filename) + : filename, + query, + basename: basename(filename), + contentHash: createHash("md4") + .update(sourceMapString) + .digest("hex") + }; + let sourceMapFile = compilation.getPath( + sourceMapFilename, + pathParams + ); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile.replace(/\\/g, "/") + : path + .relative(path.dirname(file), sourceMapFile) + .replace(/\\/g, "/"); + /** + * Add source map url to compilation asset, if {@link currentSourceMappingURLComment} presented + */ + if (currentSourceMappingURLComment !== false) { + const asset = new ConcatSource( + new RawSource(source), + compilation.getPath( + currentSourceMappingURLComment, + Object.assign({ url: sourceMapUrl }, pathParams) + ) + ); + assets[file] = asset; + compilation.updateAsset(file, asset); + } + /** + * Add source map file to compilation assets and chunk files + */ + const asset = new RawSource(sourceMapString); + assets[sourceMapFile] = asset; + compilation.emitAsset(sourceMapFile, asset, { + development: true + }); + chunk.files.push(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; + compilation.updateAsset(file, asset); + } + }); + reportProgress(1.0); + } + ); + }); + } +} + +module.exports = SourceMapDevToolPlugin; + + +/***/ }), + +/***/ 99977: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequestShortener = __webpack_require__(54254); +const SizeFormatHelpers = __webpack_require__(12496); +const formatLocation = __webpack_require__(49); +const identifierUtils = __webpack_require__(94658); +const compareLocations = __webpack_require__(22562); +const { LogType } = __webpack_require__(47194); + +const optionsOrFallback = (...args) => { + let optionValues = []; + optionValues.push(...args); + return optionValues.find(optionValue => optionValue !== undefined); +}; + +const compareId = (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; +}; + +class Stats { + constructor(compilation) { + this.compilation = compilation; + this.hash = compilation.hash; + this.startTime = undefined; + this.endTime = undefined; + } + + static filterWarnings(warnings, warningsFilter) { + // we dont have anything to filter so all warnings can be shown + if (!warningsFilter) { + return warnings; + } + + // create a chain of filters + // if they return "true" a warning should be suppressed + const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { + if (typeof filter === "string") { + return warning => warning.includes(filter); + } + + if (filter instanceof RegExp) { + return warning => filter.test(warning); + } + + if (typeof filter === "function") { + return filter; + } + + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + }); + return warnings.filter(warning => { + return !normalizedWarningsFilters.some(check => check(warning)); + }); + } + + formatFilePath(filePath) { + const OPTIONS_REGEXP = /^(\s|\S)*!/; + return filePath.includes("!") + ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` + : `${filePath}`; + } + + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); + } + + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); + } + + // remove a prefixed "!" that can be specified to reverse sort order + normalizeFieldKey(field) { + if (field[0] === "!") { + return field.substr(1); + } + return field; + } + + // if a field is prefixed by a "!" reverse sort order + sortOrderRegular(field) { + if (field[0] === "!") { + return false; + } + return true; + } + + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const optionOrLocalFallback = (v, def) => + v !== undefined ? v : options.all !== undefined ? options.all : def; + + const testAgainstGivenOption = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } + }; + + const compilation = this.compilation; + const context = optionsOrFallback( + options.context, + compilation.compiler.context + ); + const requestShortener = + compilation.compiler.context === context + ? compilation.requestShortener + : new RequestShortener(context); + const showPerformance = optionOrLocalFallback(options.performance, true); + const showHash = optionOrLocalFallback(options.hash, true); + const showEnv = optionOrLocalFallback(options.env, false); + const showVersion = optionOrLocalFallback(options.version, true); + const showTimings = optionOrLocalFallback(options.timings, true); + const showBuiltAt = optionOrLocalFallback(options.builtAt, true); + const showAssets = optionOrLocalFallback(options.assets, true); + const showEntrypoints = optionOrLocalFallback(options.entrypoints, true); + const showChunkGroups = optionOrLocalFallback( + options.chunkGroups, + !forToString + ); + const showChunks = optionOrLocalFallback(options.chunks, !forToString); + const showChunkModules = optionOrLocalFallback(options.chunkModules, true); + const showChunkOrigins = optionOrLocalFallback( + options.chunkOrigins, + !forToString + ); + const showModules = optionOrLocalFallback(options.modules, true); + const showNestedModules = optionOrLocalFallback( + options.nestedModules, + true + ); + const showModuleAssets = optionOrLocalFallback( + options.moduleAssets, + !forToString + ); + const showDepth = optionOrLocalFallback(options.depth, !forToString); + const showCachedModules = optionOrLocalFallback(options.cached, true); + const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true); + const showReasons = optionOrLocalFallback(options.reasons, !forToString); + const showUsedExports = optionOrLocalFallback( + options.usedExports, + !forToString + ); + const showProvidedExports = optionOrLocalFallback( + options.providedExports, + !forToString + ); + const showOptimizationBailout = optionOrLocalFallback( + options.optimizationBailout, + !forToString + ); + const showChildren = optionOrLocalFallback(options.children, true); + const showSource = optionOrLocalFallback(options.source, !forToString); + const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true); + const showErrors = optionOrLocalFallback(options.errors, true); + const showErrorDetails = optionOrLocalFallback( + options.errorDetails, + !forToString + ); + const showWarnings = optionOrLocalFallback(options.warnings, true); + const warningsFilter = optionsOrFallback(options.warningsFilter, null); + const showPublicPath = optionOrLocalFallback( + options.publicPath, + !forToString + ); + const showLogging = optionOrLocalFallback( + options.logging, + forToString ? "info" : true + ); + const showLoggingTrace = optionOrLocalFallback( + options.loggingTrace, + !forToString + ); + const loggingDebug = [] + .concat(optionsOrFallback(options.loggingDebug, [])) + .map(testAgainstGivenOption); + + const excludeModules = [] + .concat(optionsOrFallback(options.excludeModules, options.exclude, [])) + .map(testAgainstGivenOption); + const excludeAssets = [] + .concat(optionsOrFallback(options.excludeAssets, [])) + .map(testAgainstGivenOption); + const maxModules = optionsOrFallback( + options.maxModules, + forToString ? 15 : Infinity + ); + const sortModules = optionsOrFallback(options.modulesSort, "id"); + const sortChunks = optionsOrFallback(options.chunksSort, "id"); + const sortAssets = optionsOrFallback(options.assetsSort, ""); + const showOutputPath = optionOrLocalFallback( + options.outputPath, + !forToString + ); + + if (!showCachedModules) { + excludeModules.push((ident, module) => !module.built); + } + + const createModuleFilter = () => { + let i = 0; + return module => { + if (excludeModules.length > 0) { + const ident = requestShortener.shorten(module.resource); + const excluded = excludeModules.some(fn => fn(ident, module)); + if (excluded) return false; + } + const result = i < maxModules; + i++; + return result; + }; + }; + + const createAssetFilter = () => { + return asset => { + if (excludeAssets.length > 0) { + const ident = asset.name; + const excluded = excludeAssets.some(fn => fn(ident, asset)); + if (excluded) return false; + } + return showCachedAssets || asset.emitted; + }; + }; + + const sortByFieldAndOrder = (fieldKey, a, b) => { + if (a[fieldKey] === null && b[fieldKey] === null) return 0; + if (a[fieldKey] === null) return 1; + if (b[fieldKey] === null) return -1; + if (a[fieldKey] === b[fieldKey]) return 0; + if (typeof a[fieldKey] !== typeof b[fieldKey]) + return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1; + return a[fieldKey] < b[fieldKey] ? -1 : 1; + }; + + const sortByField = (field, originalArray) => { + const originalMap = originalArray.reduce((map, v, i) => { + map.set(v, i); + return map; + }, new Map()); + return (a, b) => { + if (field) { + const fieldKey = this.normalizeFieldKey(field); + + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = this.sortOrderRegular(field); + + const cmp = sortByFieldAndOrder( + fieldKey, + sortIsRegular ? a : b, + sortIsRegular ? b : a + ); + if (cmp) return cmp; + } + return originalMap.get(a) - originalMap.get(b); + }; + }; + + const formatError = e => { + let text = ""; + if (typeof e === "string") { + e = { message: e }; + } + if (e.chunk) { + text += `chunk ${e.chunk.name || e.chunk.id}${ + e.chunk.hasRuntime() + ? " [entry]" + : e.chunk.canBeInitial() + ? " [initial]" + : "" + }\n`; + } + if (e.file) { + text += `${e.file}\n`; + } + if ( + e.module && + e.module.readableIdentifier && + typeof e.module.readableIdentifier === "function" + ) { + text += this.formatFilePath( + e.module.readableIdentifier(requestShortener) + ); + if (typeof e.loc === "object") { + const locInfo = formatLocation(e.loc); + if (locInfo) text += ` ${locInfo}`; + } + text += "\n"; + } + text += e.message; + if (showErrorDetails && e.details) { + text += `\n${e.details}`; + } + if (showErrorDetails && e.missing) { + text += e.missing.map(item => `\n[${item}]`).join(""); + } + if (showModuleTrace && e.origin) { + text += `\n @ ${this.formatFilePath( + e.origin.readableIdentifier(requestShortener) + )}`; + if (typeof e.originLoc === "object") { + const locInfo = formatLocation(e.originLoc); + if (locInfo) text += ` ${locInfo}`; + } + if (e.dependencies) { + for (const dep of e.dependencies) { + if (!dep.loc) continue; + if (typeof dep.loc === "string") continue; + const locInfo = formatLocation(dep.loc); + if (!locInfo) continue; + text += ` ${locInfo}`; + } + } + let current = e.origin; + while (current.issuer) { + current = current.issuer; + text += `\n @ ${current.readableIdentifier(requestShortener)}`; + } + } + return text; + }; + + const obj = { + errors: compilation.errors.map(formatError), + warnings: Stats.filterWarnings( + compilation.warnings.map(formatError), + warningsFilter + ) + }; + + //We just hint other renderers since actually omitting + //errors/warnings from the JSON would be kind of weird. + Object.defineProperty(obj, "_showWarnings", { + value: showWarnings, + enumerable: false + }); + Object.defineProperty(obj, "_showErrors", { + value: showErrors, + enumerable: false + }); + + if (showVersion) { + obj.version = __webpack_require__(71618)/* .version */ .i8; + } + + if (showHash) obj.hash = this.hash; + if (showTimings && this.startTime && this.endTime) { + obj.time = this.endTime - this.startTime; + } + + if (showBuiltAt && this.endTime) { + obj.builtAt = this.endTime; + } + + if (showEnv && options._env) { + obj.env = options._env; + } + + if (compilation.needAdditionalPass) { + obj.needAdditionalPass = true; + } + if (showPublicPath) { + obj.publicPath = this.compilation.mainTemplate.getPublicPath({ + hash: this.compilation.hash + }); + } + if (showOutputPath) { + obj.outputPath = this.compilation.mainTemplate.outputOptions.path; + } + if (showAssets) { + const assetsByFile = {}; + const compilationAssets = compilation + .getAssets() + .sort((a, b) => (a.name < b.name ? -1 : 1)); + obj.assetsByChunkName = {}; + obj.assets = compilationAssets + .map(({ name, source, info }) => { + const obj = { + name, + size: source.size(), + chunks: [], + chunkNames: [], + info, + // TODO webpack 5: remove .emitted + emitted: source.emitted || compilation.emittedAssets.has(name) + }; + + if (showPerformance) { + obj.isOverSizeLimit = source.isOverSizeLimit; + } + + assetsByFile[name] = obj; + return obj; + }) + .filter(createAssetFilter()); + obj.filteredAssets = compilationAssets.length - obj.assets.length; + + for (const chunk of compilation.chunks) { + for (const asset of chunk.files) { + if (assetsByFile[asset]) { + for (const id of chunk.ids) { + assetsByFile[asset].chunks.push(id); + } + if (chunk.name) { + assetsByFile[asset].chunkNames.push(chunk.name); + if (obj.assetsByChunkName[chunk.name]) { + obj.assetsByChunkName[chunk.name] = [] + .concat(obj.assetsByChunkName[chunk.name]) + .concat([asset]); + } else { + obj.assetsByChunkName[chunk.name] = asset; + } + } + } + } + } + obj.assets.sort(sortByField(sortAssets, obj.assets)); + } + + const fnChunkGroup = groupMap => { + const obj = {}; + for (const keyValuePair of groupMap) { + const name = keyValuePair[0]; + const cg = keyValuePair[1]; + const children = cg.getChildrenByOrders(); + obj[name] = { + chunks: cg.chunks.map(c => c.id), + assets: cg.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ), + children: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = groups.map(group => ({ + name: group.name, + chunks: group.chunks.map(c => c.id), + assets: group.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ) + })); + return obj; + }, Object.create(null)), + childAssets: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = Array.from( + groups.reduce((set, group) => { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + return set; + }, new Set()) + ); + return obj; + }, Object.create(null)) + }; + if (showPerformance) { + obj[name].isOverSizeLimit = cg.isOverSizeLimit; + } + } + + return obj; + }; + + if (showEntrypoints) { + obj.entrypoints = fnChunkGroup(compilation.entrypoints); + } + + if (showChunkGroups) { + obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); + } + + const fnModule = module => { + const path = []; + let current = module; + while (current.issuer) { + path.push((current = current.issuer)); + } + path.reverse(); + const obj = { + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + index: module.index, + index2: module.index2, + size: module.size(), + cacheable: module.buildInfo.cacheable, + built: !!module.built, + optional: module.optional, + prefetched: module.prefetched, + chunks: Array.from(module.chunksIterable, chunk => chunk.id), + issuer: module.issuer && module.issuer.identifier(), + issuerId: module.issuer && module.issuer.id, + issuerName: + module.issuer && module.issuer.readableIdentifier(requestShortener), + issuerPath: + module.issuer && + path.map(module => ({ + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + profile: module.profile + })), + profile: module.profile, + failed: !!module.error, + errors: module.errors ? module.errors.length : 0, + warnings: module.warnings ? module.warnings.length : 0 + }; + if (showModuleAssets) { + obj.assets = Object.keys(module.buildInfo.assets || {}); + } + if (showReasons) { + obj.reasons = module.reasons + .sort((a, b) => { + if (a.module && !b.module) return -1; + if (!a.module && b.module) return 1; + if (a.module && b.module) { + const cmp = compareId(a.module.id, b.module.id); + if (cmp) return cmp; + } + if (a.dependency && !b.dependency) return -1; + if (!a.dependency && b.dependency) return 1; + if (a.dependency && b.dependency) { + const cmp = compareLocations(a.dependency.loc, b.dependency.loc); + if (cmp) return cmp; + if (a.dependency.type < b.dependency.type) return -1; + if (a.dependency.type > b.dependency.type) return 1; + } + return 0; + }) + .map(reason => { + const obj = { + moduleId: reason.module ? reason.module.id : null, + moduleIdentifier: reason.module + ? reason.module.identifier() + : null, + module: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + moduleName: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + explanation: reason.explanation, + userRequest: reason.dependency + ? reason.dependency.userRequest + : null + }; + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + obj.loc = locInfo; + } + } + return obj; + }); + } + if (showUsedExports) { + if (module.used === true) { + obj.usedExports = module.usedExports; + } else if (module.used === false) { + obj.usedExports = false; + } + } + if (showProvidedExports) { + obj.providedExports = Array.isArray(module.buildMeta.providedExports) + ? module.buildMeta.providedExports + : null; + } + if (showOptimizationBailout) { + obj.optimizationBailout = module.optimizationBailout.map(item => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + } + if (showDepth) { + obj.depth = module.depth; + } + if (showNestedModules) { + if (module.modules) { + const modules = module.modules; + obj.modules = modules + .sort(sortByField("depth", modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + } + if (showSource && module._source) { + obj.source = module._source.source(); + } + return obj; + }; + if (showChunks) { + obj.chunks = compilation.chunks.map(chunk => { + const parents = new Set(); + const children = new Set(); + const siblings = new Set(); + const childIdByOrder = chunk.getChildIdsByOrders(); + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(chunk.id); + } + } + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(chunk.id); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) siblings.add(sibling.id); + } + } + const obj = { + id: chunk.id, + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: chunk.recorded, + reason: chunk.chunkReason, + size: chunk.modulesSize(), + names: chunk.name ? [chunk.name] : [], + files: chunk.files.slice(), + hash: chunk.renderedHash, + siblings: Array.from(siblings).sort(compareId), + parents: Array.from(parents).sort(compareId), + children: Array.from(children).sort(compareId), + childrenByOrder: childIdByOrder + }; + if (showChunkModules) { + const modules = chunk.getModules(); + obj.modules = modules + .slice() + .sort(sortByField("depth", modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + if (showChunkOrigins) { + obj.origins = Array.from(chunk.groupsIterable, g => g.origins) + .reduce((a, b) => a.concat(b), []) + .map(origin => ({ + moduleId: origin.module ? origin.module.id : undefined, + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request, + reasons: origin.reasons || [] + })) + .sort((a, b) => { + const cmp1 = compareId(a.moduleId, b.moduleId); + if (cmp1) return cmp1; + const cmp2 = compareId(a.loc, b.loc); + if (cmp2) return cmp2; + const cmp3 = compareId(a.request, b.request); + if (cmp3) return cmp3; + return 0; + }); + } + return obj; + }); + obj.chunks.sort(sortByField(sortChunks, obj.chunks)); + } + if (showModules) { + obj.modules = compilation.modules + .slice() + .sort(sortByField("depth", compilation.modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = compilation.modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + if (showLogging) { + const util = __webpack_require__(31669); + obj.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (showLogging) { + case "none": + 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 true: + 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; + } + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some(fn => fn(origin)); + let collapseCounter = 0; + let processedLogEntries = logEntries; + if (!debugMode) { + processedLogEntries = processedLogEntries.filter(entry => { + if (!acceptedTypes.has(entry.type)) return false; + if (!collapsedGroups) { + switch (entry.type) { + case LogType.groupCollapsed: + collapseCounter++; + return collapseCounter === 1; + case LogType.group: + if (collapseCounter > 0) collapseCounter++; + return collapseCounter === 0; + case LogType.groupEnd: + if (collapseCounter > 0) { + collapseCounter--; + return false; + } + return true; + default: + return collapseCounter === 0; + } + } + return true; + }); + } + processedLogEntries = processedLogEntries.map(entry => { + 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)); + } + return { + type: + (debugMode || collapsedGroups) && + entry.type === LogType.groupCollapsed + ? LogType.group + : entry.type, + message, + trace: showLoggingTrace && entry.trace ? entry.trace : undefined + }; + }); + let name = identifierUtils + .makePathsRelative(context, origin, compilation.cache) + .replace(/\|/g, " "); + if (name in obj.logging) { + let i = 1; + while (`${name}#${i}` in obj.logging) { + i++; + } + name = `${name}#${i}`; + } + obj.logging[name] = { + entries: processedLogEntries, + filteredEntries: logEntries.length - processedLogEntries.length, + debug: debugMode + }; + } + } + if (showChildren) { + obj.children = compilation.children.map((child, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = new Stats(child).toJson(childOptions, forToString); + delete obj.hash; + delete obj.version; + if (child.name) { + obj.name = identifierUtils.makePathsRelative( + context, + child.name, + compilation.cache + ); + } + return obj; + }); + } + + return obj; + } + + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const useColors = optionsOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } + + static jsonToString(obj, useColors) { + const buf = []; + + const defaultColors = { + bold: "\u001b[1m", + yellow: "\u001b[1m\u001b[33m", + red: "\u001b[1m\u001b[31m", + green: "\u001b[1m\u001b[32m", + cyan: "\u001b[1m\u001b[36m", + magenta: "\u001b[1m\u001b[35m" + }; + + const colors = Object.keys(defaultColors).reduce( + (obj, color) => { + obj[color] = str => { + if (useColors) { + buf.push( + useColors === true || useColors[color] === undefined + ? defaultColors[color] + : useColors[color] + ); + } + buf.push(str); + if (useColors) { + buf.push("\u001b[39m\u001b[22m"); + } + }; + return obj; + }, + { + normal: str => buf.push(str) + } + ); + + const coloredTime = time => { + let times = [800, 400, 200, 100]; + if (obj.time) { + times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; + } + if (time < times[3]) colors.normal(`${time}ms`); + else if (time < times[2]) colors.bold(`${time}ms`); + else if (time < times[1]) colors.green(`${time}ms`); + else if (time < times[0]) colors.yellow(`${time}ms`); + else colors.red(`${time}ms`); + }; + + const newline = () => buf.push("\n"); + + const getText = (arr, row, col) => { + return arr[row][col].value; + }; + + const table = (array, align, splitter) => { + const rows = array.length; + const cols = array[0].length; + const colSizes = new Array(cols); + for (let col = 0; col < cols; col++) { + colSizes[col] = 0; + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const value = `${getText(array, row, col)}`; + if (value.length > colSizes[col]) { + colSizes[col] = value.length; + } + } + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const format = array[row][col].color; + const value = `${getText(array, row, col)}`; + let l = value.length; + if (align[col] === "l") { + format(value); + } + for (; l < colSizes[col] && col !== cols - 1; l++) { + colors.normal(" "); + } + if (align[col] === "r") { + format(value); + } + if (col + 1 < cols && colSizes[col] !== 0) { + colors.normal(splitter || " "); + } + } + newline(); + } + }; + + const getAssetColor = (asset, defaultColor) => { + if (asset.isOverSizeLimit) { + return colors.yellow; + } + + return defaultColor; + }; + + if (obj.hash) { + colors.normal("Hash: "); + colors.bold(obj.hash); + newline(); + } + if (obj.version) { + colors.normal("Version: webpack "); + colors.bold(obj.version); + newline(); + } + if (typeof obj.time === "number") { + colors.normal("Time: "); + colors.bold(obj.time); + colors.normal("ms"); + newline(); + } + if (typeof obj.builtAt === "number") { + const builtAtDate = new Date(obj.builtAt); + let timeZone = undefined; + + try { + builtAtDate.toLocaleTimeString(); + } catch (err) { + // Force UTC if runtime timezone is unsupported + timeZone = "UTC"; + } + + colors.normal("Built at: "); + colors.normal( + builtAtDate.toLocaleDateString(undefined, { + day: "2-digit", + month: "2-digit", + year: "numeric", + timeZone + }) + ); + colors.normal(" "); + colors.bold(builtAtDate.toLocaleTimeString(undefined, { timeZone })); + newline(); + } + if (obj.env) { + colors.normal("Environment (--env): "); + colors.bold(JSON.stringify(obj.env, null, 2)); + newline(); + } + if (obj.publicPath) { + colors.normal("PublicPath: "); + colors.bold(obj.publicPath); + newline(); + } + + if (obj.assets && obj.assets.length > 0) { + const t = [ + [ + { + value: "Asset", + color: colors.bold + }, + { + value: "Size", + color: colors.bold + }, + { + value: "Chunks", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "Chunk Names", + color: colors.bold + } + ] + ]; + for (const asset of obj.assets) { + t.push([ + { + value: asset.name, + color: getAssetColor(asset, colors.green) + }, + { + value: SizeFormatHelpers.formatSize(asset.size), + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunks.join(", "), + color: colors.bold + }, + { + value: [ + asset.emitted && "[emitted]", + asset.info.immutable && "[immutable]", + asset.info.development && "[dev]", + asset.info.hotModuleReplacement && "[hmr]" + ] + .filter(Boolean) + .join(" "), + color: colors.green + }, + { + value: asset.isOverSizeLimit ? "[big]" : "", + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunkNames.join(", "), + color: colors.normal + } + ]); + } + table(t, "rrrlll"); + } + if (obj.filteredAssets > 0) { + colors.normal(" "); + if (obj.assets.length > 0) colors.normal("+ "); + colors.normal(obj.filteredAssets); + if (obj.assets.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset"); + newline(); + } + + const processChunkGroups = (namedGroups, prefix) => { + for (const name of Object.keys(namedGroups)) { + const cg = namedGroups[name]; + colors.normal(`${prefix} `); + colors.bold(name); + if (cg.isOverSizeLimit) { + colors.normal(" "); + colors.yellow("[big]"); + } + colors.normal(" ="); + for (const asset of cg.assets) { + colors.normal(" "); + colors.green(asset); + } + for (const name of Object.keys(cg.childAssets)) { + const assets = cg.childAssets[name]; + if (assets && assets.length > 0) { + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const asset of assets) { + colors.normal(" "); + colors.green(asset); + } + colors.magenta(")"); + } + } + newline(); + } + }; + + if (obj.entrypoints) { + processChunkGroups(obj.entrypoints, "Entrypoint"); + } + + if (obj.namedChunkGroups) { + let outputChunkGroups = obj.namedChunkGroups; + if (obj.entrypoints) { + outputChunkGroups = Object.keys(outputChunkGroups) + .filter(name => !obj.entrypoints[name]) + .reduce((result, name) => { + result[name] = obj.namedChunkGroups[name]; + return result; + }, {}); + } + processChunkGroups(outputChunkGroups, "Chunk Group"); + } + + const modulesByIdentifier = {}; + if (obj.modules) { + for (const module of obj.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; + } + } else if (obj.chunks) { + for (const chunk of obj.chunks) { + if (chunk.modules) { + for (const module of chunk.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; + } + } + } + } + + const processModuleAttributes = module => { + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(module.size)); + if (module.chunks) { + for (const chunk of module.chunks) { + colors.normal(" {"); + colors.yellow(chunk); + colors.normal("}"); + } + } + if (typeof module.depth === "number") { + colors.normal(` [depth ${module.depth}]`); + } + if (module.cacheable === false) { + colors.red(" [not cacheable]"); + } + if (module.optional) { + colors.yellow(" [optional]"); + } + if (module.built) { + colors.green(" [built]"); + } + if (module.assets && module.assets.length) { + colors.magenta( + ` [${module.assets.length} asset${ + module.assets.length === 1 ? "" : "s" + }]` + ); + } + if (module.prefetched) { + colors.magenta(" [prefetched]"); + } + if (module.failed) colors.red(" [failed]"); + if (module.warnings) { + colors.yellow( + ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` + ); + } + if (module.errors) { + colors.red( + ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` + ); + } + }; + + const processModuleContent = (module, prefix) => { + if (Array.isArray(module.providedExports)) { + colors.normal(prefix); + if (module.providedExports.length === 0) { + colors.cyan("[no exports]"); + } else { + colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); + } + newline(); + } + if (module.usedExports !== undefined) { + if (module.usedExports !== true) { + colors.normal(prefix); + if (module.usedExports === null) { + colors.cyan("[used exports unknown]"); + } else if (module.usedExports === false) { + colors.cyan("[no exports used]"); + } else if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + colors.cyan("[no exports used]"); + } else if (Array.isArray(module.usedExports)) { + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === module.usedExports.length + ) { + colors.cyan("[all exports used]"); + } else { + colors.cyan( + `[only some exports used: ${module.usedExports.join(", ")}]` + ); + } + } + newline(); + } + } + if (Array.isArray(module.optimizationBailout)) { + for (const item of module.optimizationBailout) { + colors.normal(prefix); + colors.yellow(item); + newline(); + } + } + if (module.reasons) { + for (const reason of module.reasons) { + colors.normal(prefix); + if (reason.type) { + colors.normal(reason.type); + colors.normal(" "); + } + if (reason.userRequest) { + colors.cyan(reason.userRequest); + colors.normal(" "); + } + if (reason.moduleId !== null) { + colors.normal("["); + colors.normal(reason.moduleId); + colors.normal("]"); + } + if (reason.module && reason.module !== reason.moduleId) { + colors.normal(" "); + colors.magenta(reason.module); + } + if (reason.loc) { + colors.normal(" "); + colors.normal(reason.loc); + } + if (reason.explanation) { + colors.normal(" "); + colors.cyan(reason.explanation); + } + newline(); + } + } + if (module.profile) { + colors.normal(prefix); + let sum = 0; + if (module.issuerPath) { + for (const m of module.issuerPath) { + colors.normal("["); + colors.normal(m.id); + colors.normal("] "); + if (m.profile) { + const time = (m.profile.factory || 0) + (m.profile.building || 0); + coloredTime(time); + sum += time; + colors.normal(" "); + } + colors.normal("-> "); + } + } + for (const key of Object.keys(module.profile)) { + colors.normal(`${key}:`); + const time = module.profile[key]; + coloredTime(time); + colors.normal(" "); + sum += time; + } + colors.normal("= "); + coloredTime(sum); + newline(); + } + if (module.modules) { + processModulesList(module, prefix + "| "); + } + }; + + const processModulesList = (obj, prefix) => { + if (obj.modules) { + let maxModuleId = 0; + for (const module of obj.modules) { + if (typeof module.id === "number") { + if (maxModuleId < module.id) maxModuleId = module.id; + } + } + let contentPrefix = prefix + " "; + if (maxModuleId >= 10) contentPrefix += " "; + if (maxModuleId >= 100) contentPrefix += " "; + if (maxModuleId >= 1000) contentPrefix += " "; + for (const module of obj.modules) { + colors.normal(prefix); + const name = module.name || module.identifier; + if (typeof module.id === "string" || typeof module.id === "number") { + if (typeof module.id === "number") { + if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" "); + if (module.id < 100 && maxModuleId >= 100) colors.normal(" "); + if (module.id < 10 && maxModuleId >= 10) colors.normal(" "); + } else { + if (maxModuleId >= 1000) colors.normal(" "); + if (maxModuleId >= 100) colors.normal(" "); + if (maxModuleId >= 10) colors.normal(" "); + } + if (name !== module.id) { + colors.normal("["); + colors.normal(module.id); + colors.normal("]"); + colors.normal(" "); + } else { + colors.normal("["); + colors.bold(module.id); + colors.normal("]"); + } + } + if (name !== module.id) { + colors.bold(name); + } + processModuleAttributes(module); + newline(); + processModuleContent(module, contentPrefix); + } + if (obj.filteredModules > 0) { + colors.normal(prefix); + colors.normal(" "); + if (obj.modules.length > 0) colors.normal(" + "); + colors.normal(obj.filteredModules); + if (obj.modules.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredModules !== 1 ? " modules" : " module"); + newline(); + } + } + }; + + if (obj.chunks) { + for (const chunk of obj.chunks) { + colors.normal("chunk "); + if (chunk.id < 1000) colors.normal(" "); + if (chunk.id < 100) colors.normal(" "); + if (chunk.id < 10) colors.normal(" "); + colors.normal("{"); + colors.yellow(chunk.id); + colors.normal("} "); + colors.green(chunk.files.join(", ")); + if (chunk.names && chunk.names.length > 0) { + colors.normal(" ("); + colors.normal(chunk.names.join(", ")); + colors.normal(")"); + } + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(chunk.size)); + for (const id of chunk.parents) { + colors.normal(" <{"); + colors.yellow(id); + colors.normal("}>"); + } + for (const id of chunk.siblings) { + colors.normal(" ={"); + colors.yellow(id); + colors.normal("}="); + } + for (const id of chunk.children) { + colors.normal(" >{"); + colors.yellow(id); + colors.normal("}<"); + } + if (chunk.childrenByOrder) { + for (const name of Object.keys(chunk.childrenByOrder)) { + const children = chunk.childrenByOrder[name]; + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const id of children) { + colors.normal(" {"); + colors.yellow(id); + colors.normal("}"); + } + colors.magenta(")"); + } + } + if (chunk.entry) { + colors.yellow(" [entry]"); + } else if (chunk.initial) { + colors.yellow(" [initial]"); + } + if (chunk.rendered) { + colors.green(" [rendered]"); + } + if (chunk.recorded) { + colors.green(" [recorded]"); + } + if (chunk.reason) { + colors.yellow(` ${chunk.reason}`); + } + newline(); + if (chunk.origins) { + for (const origin of chunk.origins) { + colors.normal(" > "); + if (origin.reasons && origin.reasons.length) { + colors.yellow(origin.reasons.join(" ")); + colors.normal(" "); + } + if (origin.request) { + colors.normal(origin.request); + colors.normal(" "); + } + if (origin.module) { + colors.normal("["); + colors.normal(origin.moduleId); + colors.normal("] "); + const module = modulesByIdentifier[`$${origin.module}`]; + if (module) { + colors.bold(module.name); + colors.normal(" "); + } + } + if (origin.loc) { + colors.normal(origin.loc); + } + newline(); + } + } + processModulesList(chunk, " "); + } + } + + processModulesList(obj, ""); + + if (obj.logging) { + for (const origin of Object.keys(obj.logging)) { + const logData = obj.logging[origin]; + if (logData.entries.length > 0) { + newline(); + if (logData.debug) { + colors.red("DEBUG "); + } + colors.bold("LOG from " + origin); + newline(); + let indent = ""; + for (const entry of logData.entries) { + let color = colors.normal; + let prefix = " "; + switch (entry.type) { + case LogType.clear: + colors.normal(`${indent}-------`); + newline(); + continue; + case LogType.error: + color = colors.red; + prefix = " "; + break; + case LogType.warn: + color = colors.yellow; + prefix = " "; + break; + case LogType.info: + color = colors.green; + prefix = " "; + break; + case LogType.log: + color = colors.bold; + break; + case LogType.trace: + case LogType.debug: + color = colors.normal; + break; + case LogType.status: + color = colors.magenta; + prefix = " "; + break; + case LogType.profile: + color = colors.magenta; + prefix = "

"; + break; + case LogType.profileEnd: + color = colors.magenta; + prefix = "

"; + break; + case LogType.time: + color = colors.magenta; + prefix = " "; + break; + case LogType.group: + color = colors.cyan; + prefix = "<-> "; + break; + case LogType.groupCollapsed: + color = colors.cyan; + prefix = "<+> "; + break; + case LogType.groupEnd: + if (indent.length >= 2) + indent = indent.slice(0, indent.length - 2); + continue; + } + if (entry.message) { + for (const line of entry.message.split("\n")) { + colors.normal(`${indent}${prefix}`); + color(line); + newline(); + } + } + if (entry.trace) { + for (const line of entry.trace) { + colors.normal(`${indent}| ${line}`); + newline(); + } + } + switch (entry.type) { + case LogType.group: + indent += " "; + break; + } + } + if (logData.filteredEntries) { + colors.normal(`+ ${logData.filteredEntries} hidden lines`); + newline(); + } + } + } + } + + if (obj._showWarnings && obj.warnings) { + for (const warning of obj.warnings) { + newline(); + colors.yellow(`WARNING in ${warning}`); + newline(); + } + } + if (obj._showErrors && obj.errors) { + for (const error of obj.errors) { + newline(); + colors.red(`ERROR in ${error}`); + newline(); + } + } + if (obj.children) { + for (const child of obj.children) { + const childString = Stats.jsonToString(child, useColors); + if (childString) { + if (child.name) { + colors.normal("Child "); + colors.bold(child.name); + colors.normal(":"); + } else { + colors.normal("Child"); + } + newline(); + buf.push(" "); + buf.push(childString.replace(/\n/g, "\n ")); + newline(); + } + } + } + if (obj.needAdditionalPass) { + colors.yellow( + "Compilation needs an additional pass and will compile again." + ); + } + + while (buf[buf.length - 1] === "\n") { + buf.pop(); + } + return buf.join(""); + } + + static presetToOptions(name) { + // Accepted values: none, errors-only, minimal, normal, detailed, verbose + // Any other falsy value will behave as 'none', truthy values as 'normal' + const pn = + (typeof name === "string" && name.toLowerCase()) || name || "none"; + switch (pn) { + case "none": + return { + all: false + }; + case "verbose": + return { + entrypoints: true, + chunkGroups: true, + modules: false, + chunks: true, + chunkModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: "verbose", + exclude: false, + maxModules: Infinity + }; + case "detailed": + return { + entrypoints: true, + chunkGroups: true, + chunks: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: true, + exclude: false, + maxModules: Infinity + }; + case "minimal": + return { + all: false, + modules: true, + maxModules: 0, + errors: true, + warnings: true, + logging: "warn" + }; + case "errors-only": + return { + all: false, + errors: true, + moduleTrace: true, + logging: "error" + }; + case "errors-warnings": + return { + all: false, + errors: true, + warnings: true, + logging: "warn" + }; + default: + return {}; + } + } + + static getChildOptions(options, idx) { + let innerOptions; + if (Array.isArray(options.children)) { + if (idx < options.children.length) { + innerOptions = options.children[idx]; + } + } else if (typeof options.children === "object" && options.children) { + innerOptions = options.children; + } + if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { + innerOptions = Stats.presetToOptions(innerOptions); + } + if (!innerOptions) { + return options; + } + const childOptions = Object.assign({}, options); + delete childOptions.children; // do not inherit children + return Object.assign(childOptions, innerOptions); + } +} + +module.exports = Stats; + + +/***/ }), + +/***/ 97365: +/***/ ((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__(53665); +const Template = __webpack_require__(96066); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @typedef {Object} SystemMainTemplatePluginOptions + * @param {string=} name the library name + */ + +class SystemMainTemplatePlugin { + /** + * @param {SystemMainTemplatePluginOptions} options the plugin options + */ + constructor(options) { + this.name = options.name; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const externals = chunk.getModules().filter(m => m.external); + + // The name this bundle should be registered as with System + const name = this.name + ? `${JSON.stringify( + mainTemplate.getAssetPath(this.name, { hash, 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" ? 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(`${m.id}`)}__` + ); + + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = + externalWebpackNames.length > 0 + ? `var ${externalWebpackNames.join(", ")};` + : ""; + + // The system.register format requires an array of setter functions for externals. + const setters = + externalWebpackNames.length === 0 + ? "" + : Template.asString([ + "setters: [", + Template.indent( + externalWebpackNames + .map(external => + Template.asString([ + "function(module) {", + Template.indent(`${external} = module;`), + "}" + ]) + ) + .join(",\n") + ), + "]," + ]); + + return new ConcatSource( + Template.asString([ + `System.register(${name}${systemDependencies}, function(${dynamicExport}) {`, + Template.indent([ + externalVarDeclarations, + "return {", + Template.indent([ + setters, + "execute: function() {", + Template.indent(`${dynamicExport}(`) + ]) + ]) + ]) + "\n", + source, + "\n" + + Template.asString([ + Template.indent([ + Template.indent([Template.indent([");"]), "}"]), + "};" + ]), + "})" + ]) + ); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "SystemMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap( + "SystemMainTemplatePlugin", + paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + } + ); + + mainTemplate.hooks.hash.tap("SystemMainTemplatePlugin", hash => { + hash.update("exports system"); + if (this.name) { + hash.update(this.name); + } + }); + } +} + +module.exports = SystemMainTemplatePlugin; + + +/***/ }), + +/***/ 96066: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ + +const { ConcatSource } = __webpack_require__(53665); +const HotUpdateChunk = __webpack_require__(26782); + +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; + +/** @typedef {import("webpack-sources").Source} Source */ + +/** + * @typedef {Object} HasId + * @property {number | string} id + */ + +/** + * @typedef {function(Module, number): boolean} ModuleFilterPredicate + */ + +/** + * @param {HasId} a first id object to be sorted + * @param {HasId} b second id object to be sorted against + * @returns {-1|0|1} the sort value + */ +const stringifyIdSortPredicate = (a, b) => { + const aId = a.id + ""; + const bId = b.id + ""; + if (aId < bId) return -1; + if (aId > bId) return 1; + return 0; +}; + +class Template { + /** + * + * @param {Function} fn a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string + */ + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); + } + + /** + * @param {string} str the string converted to identifier + * @returns {string} created identifier + */ + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); + } + /** + * + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string + */ + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + } + + // map number to a single character a-z, A-Z or <_ + number> if number is too big + /** + * + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifer(n) { + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + + // upper case + if (n < DELTA_A_TO_Z * 2) { + return String.fromCharCode( + START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z + ); + } + + // use multiple letters + return ( + Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + + Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) + ); + } + + /** + * + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } else { + const str = s.trimRight(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } + } + + /** + * + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string + */ + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + } + + /** + * + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array + */ + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); + } + return str; + } + + /** + * @typedef {Object} WithId + * @property {string|number} id + */ + + /** + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id + */ + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + if (typeof module.id !== "number") return false; + if (maxId < module.id) maxId = /** @type {number} */ (module.id); + if (minId > module.id) minId = /** @type {number} */ (module.id); + } + if (minId < 16 + ("" + minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; + } + const objectOverhead = modules + .map(module => (module.id + "").length + 2) + .reduce((a, b) => a + b, -1); + const arrayOverhead = + minId === 0 ? maxId : 16 + ("" + minId).length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; + } + + /** + * @param {Chunk} chunk chunk whose modules will be rendered + * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules + * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies + * @param {string=} prefix applying prefix strings + * @returns {ConcatSource} rendered chunk modules in a Source object + */ + static renderChunkModules( + chunk, + filterFn, + moduleTemplate, + dependencyTemplates, + prefix = "" + ) { + const source = new ConcatSource(); + const modules = chunk.getModules().filter(filterFn); + let removedModules; + if (chunk instanceof HotUpdateChunk) { + removedModules = chunk.removedModules; + } + if ( + modules.length === 0 && + (!removedModules || removedModules.length === 0) + ) { + source.add("[]"); + return source; + } + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map(module => { + return { + id: module.id, + source: moduleTemplate.render(module, dependencyTemplates, { + chunk + }) + }; + }); + if (removedModules && removedModules.length > 0) { + for (const id of removedModules) { + allModules.push({ + id, + source: "false" + }); + } + } + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + /** @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"); + allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { + if (idx !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + }); + source.add(`\n\n${prefix}}`); + } + return source; + } +} + +module.exports = Template; + + +/***/ }), + +/***/ 76032: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jason Anderson @diurnalist +*/ + + +const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, + REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, + REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, + REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/gi, + REGEXP_NAME = /\[name\]/gi, + REGEXP_ID = /\[id\]/gi, + REGEXP_MODULEID = /\[moduleid\]/gi, + REGEXP_FILE = /\[file\]/gi, + REGEXP_QUERY = /\[query\]/gi, + REGEXP_FILEBASE = /\[filebase\]/gi, + REGEXP_URL = /\[url\]/gi; + +// Using global RegExp for .test is dangerous +// We use a normal RegExp instead of .test +const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), + REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), + REGEXP_CONTENTHASH_FOR_TEST = new RegExp(REGEXP_CONTENTHASH.source, "i"), + REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); + +const withHashLength = (replacer, handlerFn, assetInfo) => { + const fn = (match, hashLength, ...args) => { + if (assetInfo) assetInfo.immutable = true; + const length = hashLength && parseInt(hashLength, 10); + if (length && handlerFn) { + return handlerFn(length); + } + const hash = replacer(match, hashLength, ...args); + return length ? hash.slice(0, length) : hash; + }; + return fn; +}; + +const getReplacer = (value, allowEmpty) => { + const fn = (match, ...args) => { + // last argument in replacer is the entire input string + const input = args[args.length - 1]; + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); + } + return ""; + } else { + return `${escapePathVariables(value)}`; + } + }; + return fn; +}; + +const escapePathVariables = value => { + return typeof value === "string" + ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, "[\\$1\\]") + : value; +}; + +const replacePathVariables = (path, data, assetInfo) => { + const chunk = data.chunk; + const chunkId = chunk && chunk.id; + const chunkName = chunk && (chunk.name || chunk.id); + const chunkHash = chunk && (chunk.renderedHash || chunk.hash); + const chunkHashWithLength = chunk && chunk.hashWithLength; + const contentHashType = data.contentHashType; + const contentHash = + (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) || + data.contentHash; + const contentHashWithLength = + (chunk && + chunk.contentHashWithLength && + chunk.contentHashWithLength[contentHashType]) || + data.contentHashWithLength; + const module = data.module; + const moduleId = module && module.id; + const moduleHash = module && (module.renderedHash || module.hash); + const moduleHashWithLength = module && module.hashWithLength; + + if (typeof path === "function") { + path = path(data); + } + + if ( + data.noChunkHash && + (REGEXP_CHUNKHASH_FOR_TEST.test(path) || + REGEXP_CONTENTHASH_FOR_TEST.test(path)) + ) { + throw new Error( + `Cannot use [chunkhash] or [contenthash] for chunk in '${path}' (use [hash] instead)` + ); + } + + return ( + path + .replace( + REGEXP_HASH, + withHashLength(getReplacer(data.hash), data.hashWithLength, assetInfo) + ) + .replace( + REGEXP_CHUNKHASH, + withHashLength(getReplacer(chunkHash), chunkHashWithLength, assetInfo) + ) + .replace( + REGEXP_CONTENTHASH, + withHashLength( + getReplacer(contentHash), + contentHashWithLength, + assetInfo + ) + ) + .replace( + REGEXP_MODULEHASH, + withHashLength(getReplacer(moduleHash), moduleHashWithLength, assetInfo) + ) + .replace(REGEXP_ID, getReplacer(chunkId)) + .replace(REGEXP_MODULEID, getReplacer(moduleId)) + .replace(REGEXP_NAME, getReplacer(chunkName)) + .replace(REGEXP_FILE, getReplacer(data.filename)) + .replace(REGEXP_FILEBASE, getReplacer(data.basename)) + // query is optional, it's OK if it's in a path but there's nothing to replace it with + .replace(REGEXP_QUERY, getReplacer(data.query, true)) + // only available in sourceMappingURLComment + .replace(REGEXP_URL, getReplacer(data.url)) + .replace(/\[\\(\\*[\w:]+\\*)\\\]/gi, "[$1]") + ); +}; + +class TemplatedPathPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { + const mainTemplate = compilation.mainTemplate; + + mainTemplate.hooks.assetPath.tap( + "TemplatedPathPlugin", + replacePathVariables + ); + + mainTemplate.hooks.globalHash.tap( + "TemplatedPathPlugin", + (chunk, paths) => { + const outputOptions = mainTemplate.outputOptions; + const publicPath = outputOptions.publicPath || ""; + const filename = outputOptions.filename || ""; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if ( + REGEXP_HASH_FOR_TEST.test(publicPath) || + REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || + REGEXP_CONTENTHASH_FOR_TEST.test(publicPath) || + REGEXP_NAME_FOR_TEST.test(publicPath) + ) + return true; + if (REGEXP_HASH_FOR_TEST.test(filename)) return true; + if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; + if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; + } + ); + + mainTemplate.hooks.hashForChunk.tap( + "TemplatedPathPlugin", + (hash, chunk) => { + const outputOptions = mainTemplate.outputOptions; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); + } + if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { + hash.update( + JSON.stringify( + chunk.getChunkMaps(true).contentHash.javascript || {} + ) + ); + } + if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); + } + } + ); + }); + } +} + +module.exports = TemplatedPathPlugin; + + +/***/ }), + +/***/ 75374: +/***/ ((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__(53665); +const Template = __webpack_require__(96066); + +/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +/** + * @param {string=} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +/** @typedef {string | string[] | LibraryCustomUmdObject} UmdMainTemplatePluginName */ + +/** + * @typedef {Object} AuxiliaryCommentObject + * @property {string} root + * @property {string} commonjs + * @property {string} commonjs2 + * @property {string} amd + */ + +/** + * @typedef {Object} UmdMainTemplatePluginOption + * @property {boolean=} optionalAmdExternalAsGlobal + * @property {boolean} namedDefine + * @property {string | AuxiliaryCommentObject} auxiliaryComment + */ + +class UmdMainTemplatePlugin { + /** + * @param {UmdMainTemplatePluginName} name the name of the UMD library + * @param {UmdMainTemplatePluginOption} options the plugin option + */ + constructor(name, options) { + if (typeof name === "object" && !Array.isArray(name)) { + this.name = name.root || name.amd || name.commonjs; + this.names = name; + } else { + this.name = name; + this.names = { + commonjs: name, + root: name, + amd: name + }; + } + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; + this.namedDefine = options.namedDefine; + this.auxiliaryComment = options.auxiliaryComment; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + let externals = chunk + .getModules() + .filter( + m => + m.external && + (m.externalType === "umd" || m.externalType === "umd2") + ); + const optionalExternals = []; + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.optional) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; + } + + const replaceKeys = str => { + return mainTemplate.getAssetPath(str, { + hash, + chunk + }); + }; + + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) + ) + .join(", ") + )}]`; + }; + + const externalsRootArray = modules => { + return replaceKeys( + modules + .map(m => { + let request = m.request; + if (typeof request === "object") request = request.root; + return `root${accessorToObjectAccess([].concat(request))}`; + }) + .join(", ") + ); + }; + + const externalsRequireArray = type => { + return replaceKeys( + externals + .map(m => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = request[type]; + } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); + } + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; + } else { + expr = `require(${JSON.stringify(request)})`; + } + if (m.optional) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; + + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + }; + + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; + + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? externalsArguments(requiredExternals) + + ", " + + externalsRootArray(optionalExternals) + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; + } else { + amdFactory = "factory"; + } + + const auxiliaryComment = this.auxiliaryComment; + + const getAuxilaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; + + return new ConcatSource( + new OriginalSource( + "(function webpackUniversalModuleDefinition(root, factory) {\n" + + getAuxilaryComment("commonjs2") + + " if(typeof exports === 'object' && typeof module === 'object')\n" + + " module.exports = factory(" + + externalsRequireArray("commonjs2") + + ");\n" + + getAuxilaryComment("amd") + + " else if(typeof define === 'function' && define.amd)\n" + + (requiredExternals.length > 0 + ? this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", " + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : " define(" + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", [], " + + amdFactory + + ");\n" + : " define([], " + amdFactory + ");\n") + + (this.names.root || this.names.commonjs + ? getAuxilaryComment("commonjs") + + " else if(typeof exports === 'object')\n" + + " exports[" + + libraryName(this.names.commonjs || this.names.root) + + "] = factory(" + + externalsRequireArray("commonjs") + + ");\n" + + getAuxilaryComment("root") + + " else\n" + + " " + + replaceKeys( + accessorAccess("root", this.names.root || this.names.commonjs) + ) + + " = factory(" + + externalsRootArray(externals) + + ");\n" + : " else {\n" + + (externals.length > 0 + ? " var a = typeof exports === 'object' ? factory(" + + externalsRequireArray("commonjs") + + ") : factory(" + + externalsRootArray(externals) + + ");\n" + : " var a = factory();\n") + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n") + + `})(${ + runtimeTemplate.outputOptions.globalObject + }, function(${externalsArguments(externals)}) {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" + ); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "UmdMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap("UmdMainTemplatePlugin", paths => { + if (this.names.root) paths = paths.concat(this.names.root); + if (this.names.amd) paths = paths.concat(this.names.amd); + if (this.names.commonjs) paths = paths.concat(this.names.commonjs); + return paths; + }); + + mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", hash => { + hash.update("umd"); + hash.update(`${this.names.root}`); + hash.update(`${this.names.amd}`); + hash.update(`${this.names.commonjs}`); + }); + } +} + +module.exports = UmdMainTemplatePlugin; + + +/***/ }), + +/***/ 99953: +/***/ ((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__(97391); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class UnsupportedFeatureWarning extends WebpackError { + /** + * @param {Module} module module relevant to warning + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module + */ + constructor(module, message, loc) { + super(message); + + this.name = "UnsupportedFeatureWarning"; + this.module = module; + this.loc = loc; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = UnsupportedFeatureWarning; + + +/***/ }), + +/***/ 73554: +/***/ ((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__(71101); + +/** @typedef {import("./Compiler")} Compiler */ + +class UseStrictPlugin { + /** + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "UseStrictPlugin", + (compilation, { normalModuleFactory }) => { + const handler = parser => { + parser.hooks.program.tap("UseStrictPlugin", ast => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency("", firstNode.range); + dep.loc = firstNode.loc; + parser.state.current.addDependency(dep); + parser.state.module.buildInfo.strict = true; + } + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); + } + ); + } +} + +module.exports = UseStrictPlugin; + + +/***/ }), + +/***/ 40269: +/***/ ((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__(8335); + +class WarnCaseSensitiveModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "WarnCaseSensitiveModulesPlugin", + compilation => { + compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier().toLowerCase(); + const array = moduleWithoutCase.get(identifier); + if (array) { + array.push(module); + } else { + moduleWithoutCase.set(identifier, [module]); + } + } + for (const pair of moduleWithoutCase) { + const array = pair[1]; + if (array.length > 1) { + compilation.warnings.push(new CaseSensitiveModulesWarning(array)); + } + } + }); + } + ); + } +} + +module.exports = WarnCaseSensitiveModulesPlugin; + + +/***/ }), + +/***/ 71245: +/***/ ((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__(45759); + +class WarnNoModeSetPlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { + compilation.warnings.push(new NoModeWarning()); + }); + } +} + +module.exports = WarnNoModeSetPlugin; + + +/***/ }), + +/***/ 88015: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(97009); + +/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ + +class IgnoringWatchFileSystem { + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; + } + + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + const ignored = path => + this.paths.some(p => + p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 + ); + + const notIgnored = path => !ignored(path); + + const ignoredFiles = files.filter(ignored); + const ignoredDirs = dirs.filter(ignored); + + const watcher = this.wfs.watch( + files.filter(notIgnored), + dirs.filter(notIgnored), + missing, + startTime, + options, + ( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps, + removedFiles + ) => { + if (err) return callback(err); + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + + callback( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps, + removedFiles + ); + }, + callbackUndelayed + ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimestamps: () => { + const dirTimestamps = watcher.getContextTimestamps(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + return dirTimestamps; + }, + getFileTimestamps: () => { + const fileTimestamps = watcher.getFileTimestamps(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + return fileTimestamps; + } + }; + } +} + +class WatchIgnorePlugin { + /** + * @param {WatchIgnorePluginOptions} paths list of paths + */ + constructor(paths) { + validateOptions(schema, paths, "Watch Ignore Plugin"); + this.paths = paths; + } + + apply(compiler) { + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); + }); + } +} + +module.exports = WatchIgnorePlugin; + + +/***/ }), + +/***/ 29580: +/***/ ((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__(99977); + +class Watching { + constructor(compiler, watchOptions, handler) { + this.startTime = null; + this.invalid = false; + this.handler = handler; + this.callbacks = []; + this.closed = false; + this.suspended = false; + if (typeof watchOptions === "number") { + this.watchOptions = { + aggregateTimeout: watchOptions + }; + } else if (watchOptions && typeof watchOptions === "object") { + this.watchOptions = Object.assign({}, watchOptions); + } else { + this.watchOptions = {}; + } + this.watchOptions.aggregateTimeout = + this.watchOptions.aggregateTimeout || 200; + this.compiler = compiler; + this.running = true; + this.compiler.readRecords(err => { + if (err) return this._done(err); + + this._go(); + }); + } + + _go() { + this.startTime = Date.now(); + this.running = true; + this.invalid = false; + this.compiler.hooks.watchRun.callAsync(this.compiler, err => { + if (err) return this._done(err); + const onCompiled = (err, compilation) => { + if (err) return this._done(err); + if (this.invalid) return this._done(); + + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); + } + + this.compiler.emitAssets(compilation, err => { + if (err) return this._done(err); + if (this.invalid) return this._done(); + this.compiler.emitRecords(err => { + if (err) return this._done(err); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + const stats = new Stats(compilation); + stats.startTime = this.startTime; + stats.endTime = Date.now(); + this.compiler.hooks.done.callAsync(stats, err => { + if (err) return this._done(err); + + this.compiler.hooks.additionalPass.callAsync(err => { + if (err) return this._done(err); + this.compiler.compile(onCompiled); + }); + }); + return; + } + return this._done(null, compilation); + }); + }); + }; + this.compiler.compile(onCompiled); + }); + } + + _getStats(compilation) { + const stats = new Stats(compilation); + stats.startTime = this.startTime; + stats.endTime = Date.now(); + return stats; + } + + _done(err, compilation) { + this.running = false; + if (this.invalid) return this._go(); + + const stats = compilation ? this._getStats(compilation) : null; + if (err) { + this.compiler.hooks.failed.call(err); + this.handler(err, stats); + return; + } + this.compiler.hooks.done.callAsync(stats, () => { + this.handler(null, stats); + if (!this.closed) { + this.watch( + Array.from(compilation.fileDependencies), + Array.from(compilation.contextDependencies), + Array.from(compilation.missingDependencies) + ); + } + for (const cb of this.callbacks) cb(); + this.callbacks.length = 0; + }); + } + + watch(files, dirs, missing) { + this.pausedWatcher = null; + this.watcher = this.compiler.watchFileSystem.watch( + files, + dirs, + missing, + this.startTime, + this.watchOptions, + ( + err, + filesModified, + contextModified, + missingModified, + fileTimestamps, + contextTimestamps, + removedFiles + ) => { + this.pausedWatcher = this.watcher; + this.watcher = null; + if (err) { + return this.handler(err); + } + this.compiler.fileTimestamps = fileTimestamps; + this.compiler.contextTimestamps = contextTimestamps; + this.compiler.removedFiles = removedFiles; + if (!this.suspended) { + this._invalidate(); + } + }, + (fileName, changeTime) => { + this.compiler.hooks.invalid.call(fileName, changeTime); + } + ); + } + + invalidate(callback) { + if (callback) { + this.callbacks.push(callback); + } + if (this.watcher) { + this.compiler.fileTimestamps = this.watcher.getFileTimestamps(); + this.compiler.contextTimestamps = this.watcher.getContextTimestamps(); + } + return this._invalidate(); + } + + _invalidate() { + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.watcher.pause(); + this.watcher = null; + } + + if (this.running) { + this.invalid = true; + return false; + } else { + this._go(); + } + } + + suspend() { + this.suspended = true; + this.invalid = false; + } + + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } + } + + close(callback) { + const finalCallback = () => { + this.compiler.hooks.watchClose.call(); + this.compiler.running = false; + this.compiler.watchMode = false; + if (callback !== undefined) callback(); + }; + + this.closed = true; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.pausedWatcher) { + this.pausedWatcher.close(); + this.pausedWatcher = null; + } + if (this.running) { + this.invalid = true; + this._done = finalCallback; + } else { + finalCallback(); + } + } +} + +module.exports = Watching; + + +/***/ }), + +/***/ 97391: +/***/ ((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__(31669).inspect.custom; + +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); + + this.details = undefined; + this.missing = undefined; + this.origin = undefined; + this.dependencies = undefined; + this.module = undefined; + + Error.captureStackTrace(this, this.constructor); + } + + [inspect]() { + return this.stack + (this.details ? `\n${this.details}` : ""); + } +} + +module.exports = WebpackError; + + +/***/ }), + +/***/ 2779: +/***/ ((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__(4428); + +const JavascriptModulesPlugin = __webpack_require__(10339); +const JsonModulesPlugin = __webpack_require__(2859); +const WebAssemblyModulesPlugin = __webpack_require__(99510); + +const LoaderTargetPlugin = __webpack_require__(95154); +const FunctionModulePlugin = __webpack_require__(31221); +const EvalDevToolModulePlugin = __webpack_require__(65200); +const SourceMapDevToolPlugin = __webpack_require__(11851); +const EvalSourceMapDevToolPlugin = __webpack_require__(99994); + +const EntryOptionPlugin = __webpack_require__(14604); +const RecordIdsPlugin = __webpack_require__(40355); + +const APIPlugin = __webpack_require__(71118); +const ConstPlugin = __webpack_require__(84072); +const CommonJsStuffPlugin = __webpack_require__(85736); +const CompatibilityPlugin = __webpack_require__(85918); + +const TemplatedPathPlugin = __webpack_require__(76032); +const WarnCaseSensitiveModulesPlugin = __webpack_require__(40269); +const UseStrictPlugin = __webpack_require__(73554); + +const LoaderPlugin = __webpack_require__(31559); +const CommonJsPlugin = __webpack_require__(85358); +const HarmonyModulesPlugin = __webpack_require__(66792); +const SystemPlugin = __webpack_require__(68166); +const ImportPlugin = __webpack_require__(58839); +const RequireContextPlugin = __webpack_require__(89042); +const RequireEnsurePlugin = __webpack_require__(98655); +const RequireIncludePlugin = __webpack_require__(16522); + +const { cachedCleverMerge } = __webpack_require__(67916); + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} 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) { + let ExternalsPlugin; + compiler.outputPath = options.output.path; + compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; + compiler.recordsOutputPath = + options.recordsOutputPath || options.recordsPath; + compiler.name = options.name; + // TODO webpack 5 refactor this to MultiCompiler.setDependencies() with a WeakMap + // @ts-ignore TODO + compiler.dependencies = options.dependencies; + if (typeof options.target === "string") { + let JsonpTemplatePlugin; + let FetchCompileWasmTemplatePlugin; + let ReadFileCompileWasmTemplatePlugin; + let NodeSourcePlugin; + let NodeTargetPlugin; + let NodeTemplatePlugin; + + switch (options.target) { + case "web": + JsonpTemplatePlugin = __webpack_require__(92764); + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeSourcePlugin = __webpack_require__(9128); + new JsonpTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "webworker": { + let WebWorkerTemplatePlugin = __webpack_require__(21328); + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeSourcePlugin = __webpack_require__(9128); + new WebWorkerTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + } + case "node": + case "async-node": + NodeTemplatePlugin = __webpack_require__(90010); + ReadFileCompileWasmTemplatePlugin = __webpack_require__(73839); + NodeTargetPlugin = __webpack_require__(59743); + new NodeTemplatePlugin({ + asyncChunkLoading: options.target === "async-node" + }).apply(compiler); + new ReadFileCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new LoaderTargetPlugin("node").apply(compiler); + break; + case "node-webkit": + JsonpTemplatePlugin = __webpack_require__(92764); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + new JsonpTemplatePlugin().apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", "nw.gui").apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-main": + NodeTemplatePlugin = __webpack_require__(90010); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + new NodeTemplatePlugin({ + asyncChunkLoading: true + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "app", + "auto-updater", + "browser-window", + "clipboard", + "content-tracing", + "crash-reporter", + "dialog", + "electron", + "global-shortcut", + "ipc", + "ipc-main", + "menu", + "menu-item", + "native-image", + "original-fs", + "power-monitor", + "power-save-blocker", + "protocol", + "screen", + "session", + "shell", + "tray", + "web-contents" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-renderer": + case "electron-preload": + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + if (options.target === "electron-renderer") { + JsonpTemplatePlugin = __webpack_require__(92764); + new JsonpTemplatePlugin().apply(compiler); + } else if (options.target === "electron-preload") { + NodeTemplatePlugin = __webpack_require__(90010); + new NodeTemplatePlugin({ + asyncChunkLoading: true + }).apply(compiler); + } + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "clipboard", + "crash-reporter", + "desktop-capturer", + "electron", + "ipc", + "ipc-renderer", + "native-image", + "original-fs", + "remote", + "screen", + "shell", + "web-frame" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + default: + throw new Error("Unsupported target '" + options.target + "'."); + } + } + // @ts-ignore This is always true, which is good this way + else if (options.target !== false) { + options.target(compiler); + } else { + throw new Error("Unsupported target '" + options.target + "'."); + } + + if (options.output.library || options.output.libraryTarget !== "var") { + const LibraryTemplatePlugin = __webpack_require__(65237); + new LibraryTemplatePlugin( + options.output.library, + options.output.libraryTarget, + options.output.umdNamedDefine, + options.output.auxiliaryComment || "", + options.output.libraryExport + ).apply(compiler); + } + if (options.externals) { + ExternalsPlugin = __webpack_require__(75705); + new ExternalsPlugin( + options.output.libraryTarget, + options.externals + ).apply(compiler); + } + + let noSources; + let legacy; + let modern; + let comment; + if ( + options.devtool && + (options.devtool.includes("sourcemap") || + options.devtool.includes("source-map")) + ) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + noSources = options.devtool.includes("nosources"); + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n/*\n//@ source" + + "MappingURL=[url]\n//# source" + + "MappingURL=[url]\n*/" + : legacy + ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" + : modern + ? "\n//# source" + "MappingURL=[url]" + : null; + const Plugin = evalWrapped + ? EvalSourceMapDevToolPlugin + : SourceMapDevToolPlugin; + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : comment, + module: moduleMaps ? true : cheap ? false : true, + columns: cheap ? false : true, + lineToLine: options.output.devtoolLineToLine, + noSources: noSources, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } else if (options.devtool && options.devtool.includes("eval")) { + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" + : legacy + ? "\n//@ sourceURL=[url]" + : modern + ? "\n//# sourceURL=[url]" + : null; + new EvalDevToolModulePlugin({ + sourceUrlComment: comment, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } + + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call(options.context, options.entry); + + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin(options.module).apply(compiler); + if (options.amd !== false) { + const AMDPlugin = __webpack_require__(85812); + const RequireJsStuffPlugin = __webpack_require__(88226); + new AMDPlugin(options.module, options.amd || {}).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + } + new CommonJsPlugin(options.module).apply(compiler); + new LoaderPlugin().apply(compiler); + if (options.node !== false) { + const NodeStuffPlugin = __webpack_require__(28386); + new NodeStuffPlugin(options.node).apply(compiler); + } + new CommonJsStuffPlugin().apply(compiler); + new APIPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin( + options.resolve.modules, + options.resolve.extensions, + options.resolve.mainFiles + ).apply(compiler); + new ImportPlugin(options.module).apply(compiler); + new SystemPlugin(options.module).apply(compiler); + + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = __webpack_require__(71245); + new WarnNoModeSetPlugin().apply(compiler); + } + + const EnsureChunkConditionsPlugin = __webpack_require__(29720); + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + const RemoveParentModulesPlugin = __webpack_require__(58142); + new RemoveParentModulesPlugin().apply(compiler); + } + if (options.optimization.removeEmptyChunks) { + const RemoveEmptyChunksPlugin = __webpack_require__(78085); + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + const MergeDuplicateChunksPlugin = __webpack_require__(46214); + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + const FlagIncludedChunksPlugin = __webpack_require__(25850); + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + const SideEffectsFlagPlugin = __webpack_require__(83654); + new SideEffectsFlagPlugin().apply(compiler); + } + if (options.optimization.providedExports) { + const FlagDependencyExportsPlugin = __webpack_require__(73599); + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + const FlagDependencyUsagePlugin = __webpack_require__(33632); + new FlagDependencyUsagePlugin().apply(compiler); + } + if (options.optimization.concatenateModules) { + const ModuleConcatenationPlugin = __webpack_require__(45184); + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + const SplitChunksPlugin = __webpack_require__(60474); + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + const RuntimeChunkPlugin = __webpack_require__(76894); + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (options.optimization.noEmitOnErrors) { + const NoEmitOnErrorsPlugin = __webpack_require__(22615); + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.checkWasmTypes) { + const WasmFinalizeExportsPlugin = __webpack_require__(10557); + new WasmFinalizeExportsPlugin().apply(compiler); + } + let moduleIds = options.optimization.moduleIds; + if (moduleIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + moduleIds = "size"; + } + if (options.optimization.namedModules) { + moduleIds = "named"; + } + if (options.optimization.hashedModuleIds) { + moduleIds = "hashed"; + } + if (moduleIds === undefined) { + moduleIds = "natural"; + } + } + if (moduleIds) { + const NamedModulesPlugin = __webpack_require__(86707); + const HashedModuleIdsPlugin = __webpack_require__(50268); + const OccurrenceModuleOrderPlugin = __webpack_require__(62000); + switch (moduleIds) { + case "natural": + // TODO webpack 5: see hint in Compilation.sortModules + break; + case "named": + new NamedModulesPlugin().apply(compiler); + break; + case "hashed": + new HashedModuleIdsPlugin().apply(compiler); + break; + case "size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` + ); + } + } + let chunkIds = options.optimization.chunkIds; + if (chunkIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + // This looks weird but it's for backward-compat + // This bug already existed before adding this feature + chunkIds = "total-size"; + } + if (options.optimization.namedChunks) { + chunkIds = "named"; + } + if (chunkIds === undefined) { + chunkIds = "natural"; + } + } + if (chunkIds) { + const NaturalChunkOrderPlugin = __webpack_require__(68053); + const NamedChunksPlugin = __webpack_require__(70419); + const OccurrenceChunkOrderPlugin = __webpack_require__(83741); + switch (chunkIds) { + case "natural": + new NaturalChunkOrderPlugin().apply(compiler); + break; + case "named": + // TODO webapck 5: for backward-compat this need to have OccurrenceChunkOrderPlugin too + // The NamedChunksPlugin doesn't give every chunk a name + // This should be fixed, and the OccurrenceChunkOrderPlugin should be removed here. + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + new NamedChunksPlugin().apply(compiler); + break; + case "size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` + ); + } + } + if (options.optimization.nodeEnv) { + const DefinePlugin = __webpack_require__(97374); + 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 { + minimizer.apply(compiler); + } + } + } + + if (options.performance) { + const SizeLimitsPlugin = __webpack_require__(68310); + new SizeLimitsPlugin(options.performance).apply(compiler); + } + + new TemplatedPathPlugin().apply(compiler); + + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); + + new WarnCaseSensitiveModulesPlugin().apply(compiler); + + if (options.cache) { + const CachePlugin = __webpack_require__(6465); + new CachePlugin( + typeof options.cache === "object" ? options.cache : null + ).apply(compiler); + } + + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + cachedCleverMerge(options.resolve, resolveOptions) + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem, + resolveToContext: true + }, + cachedCleverMerge(options.resolve, resolveOptions) + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + cachedCleverMerge(options.resolveLoader, resolveOptions) + ); + }); + compiler.hooks.afterResolvers.call(compiler); + return options; + } +} + +module.exports = WebpackOptionsApply; + + +/***/ }), + +/***/ 60016: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); + +const OptionsDefaulter = __webpack_require__(3414); +const Template = __webpack_require__(96066); + +const isProductionLikeMode = options => { + return options.mode === "production" || !options.mode; +}; + +const isWebLikeTarget = options => { + return options.target === "web" || options.target === "webworker"; +}; + +const getDevtoolNamespace = library => { + // if options.output.library is a string + if (Array.isArray(library)) { + return library.join("."); + } else if (typeof library === "object") { + return getDevtoolNamespace(library.root); + } + return library || ""; +}; + +class WebpackOptionsDefaulter extends OptionsDefaulter { + constructor() { + super(); + + this.set("entry", "./src"); + + this.set("devtool", "make", options => + options.mode === "development" ? "eval" : false + ); + this.set("cache", "make", options => options.mode === "development"); + + this.set("context", process.cwd()); + this.set("target", "web"); + + this.set("module", "call", value => Object.assign({}, value)); + this.set("module.unknownContextRequest", "."); + this.set("module.unknownContextRegExp", false); + this.set("module.unknownContextRecursive", true); + this.set("module.unknownContextCritical", true); + this.set("module.exprContextRequest", "."); + this.set("module.exprContextRegExp", false); + this.set("module.exprContextRecursive", true); + this.set("module.exprContextCritical", true); + this.set("module.wrappedContextRegExp", /.*/); + this.set("module.wrappedContextRecursive", true); + this.set("module.wrappedContextCritical", false); + this.set("module.strictExportPresence", false); + this.set("module.strictThisContextOnImports", false); + this.set("module.unsafeCache", "make", options => !!options.cache); + this.set("module.rules", []); + this.set("module.defaultRules", "make", options => [ + { + type: "javascript/auto", + resolve: {} + }, + { + test: /\.mjs$/i, + type: "javascript/esm", + resolve: { + mainFields: + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ? ["browser", "main"] + : ["main"] + } + }, + { + test: /\.json$/i, + type: "json" + }, + { + test: /\.wasm$/i, + type: "webassembly/experimental" + } + ]); + + this.set("output", "call", (value, options) => { + if (typeof value === "string") { + return { + filename: value + }; + } else if (typeof value !== "object") { + return {}; + } else { + return Object.assign({}, value); + } + }); + + this.set("output.filename", "[name].js"); + this.set("output.chunkFilename", "make", options => { + const filename = options.output.filename; + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasName || hasId) return filename; + // Elsewise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); + } + return "[id].js"; + }); + this.set("output.webassemblyModuleFilename", "[modulehash].module.wasm"); + this.set("output.library", ""); + this.set("output.hotUpdateFunction", "make", options => { + return Template.toIdentifier( + "webpackHotUpdate" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.jsonpFunction", "make", options => { + return Template.toIdentifier( + "webpackJsonp" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.chunkCallbackName", "make", options => { + return Template.toIdentifier( + "webpackChunk" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.globalObject", "make", options => { + switch (options.target) { + case "web": + case "electron-renderer": + case "node-webkit": + return "window"; + case "webworker": + return "self"; + case "node": + case "async-node": + case "electron-main": + return "global"; + default: + return "self"; + } + }); + this.set("output.devtoolNamespace", "make", options => { + return getDevtoolNamespace(options.output.library); + }); + this.set("output.libraryTarget", "var"); + this.set("output.path", path.join(process.cwd(), "dist")); + this.set( + "output.pathinfo", + "make", + options => options.mode === "development" + ); + this.set("output.sourceMapFilename", "[file].map[query]"); + this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); + this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); + this.set("output.crossOriginLoading", false); + this.set("output.jsonpScriptType", false); + this.set("output.chunkLoadTimeout", 120000); + this.set("output.hashFunction", "md4"); + this.set("output.hashDigest", "hex"); + this.set("output.hashDigestLength", 20); + this.set("output.devtoolLineToLine", false); + this.set("output.strictModuleExceptionHandling", false); + + this.set("node", "call", value => { + if (typeof value === "boolean") { + return value; + } else { + return Object.assign({}, value); + } + }); + this.set("node.console", false); + this.set("node.process", true); + this.set("node.global", true); + this.set("node.Buffer", true); + this.set("node.setImmediate", true); + this.set("node.__filename", "mock"); + this.set("node.__dirname", "mock"); + + this.set("performance", "call", (value, options) => { + if (value === false) return false; + if ( + value === undefined && + (!isProductionLikeMode(options) || !isWebLikeTarget(options)) + ) + return false; + return Object.assign({}, value); + }); + this.set("performance.maxAssetSize", 250000); + this.set("performance.maxEntrypointSize", 250000); + this.set("performance.hints", "make", options => + isProductionLikeMode(options) ? "warning" : false + ); + + this.set("optimization", "call", value => Object.assign({}, value)); + // TODO webpack 5: Disable by default in a modes + this.set( + "optimization.removeAvailableModules", + "make", + options => options.mode !== "development" + ); + this.set("optimization.removeEmptyChunks", true); + this.set("optimization.mergeDuplicateChunks", true); + this.set("optimization.flagIncludedChunks", "make", options => + isProductionLikeMode(options) + ); + // TODO webpack 5 add `moduleIds: "named"` default for development + // TODO webpack 5 add `moduleIds: "size"` default for production + // TODO webpack 5 remove optimization.occurrenceOrder + this.set("optimization.occurrenceOrder", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.sideEffects", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.providedExports", true); + this.set("optimization.usedExports", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.concatenateModules", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.splitChunks", {}); + this.set("optimization.splitChunks.hidePathInfo", "make", options => { + return isProductionLikeMode(options); + }); + this.set("optimization.splitChunks.chunks", "async"); + this.set("optimization.splitChunks.minSize", "make", options => { + return isProductionLikeMode(options) ? 30000 : 10000; + }); + this.set("optimization.splitChunks.minChunks", 1); + this.set("optimization.splitChunks.maxAsyncRequests", "make", options => { + return isProductionLikeMode(options) ? 5 : Infinity; + }); + this.set("optimization.splitChunks.automaticNameDelimiter", "~"); + this.set("optimization.splitChunks.automaticNameMaxLength", 109); + this.set("optimization.splitChunks.maxInitialRequests", "make", options => { + return isProductionLikeMode(options) ? 3 : Infinity; + }); + this.set("optimization.splitChunks.name", true); + this.set("optimization.splitChunks.cacheGroups", {}); + this.set("optimization.splitChunks.cacheGroups.default", { + automaticNamePrefix: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + }); + this.set("optimization.splitChunks.cacheGroups.vendors", { + automaticNamePrefix: "vendors", + test: /[\\/]node_modules[\\/]/, + priority: -10 + }); + this.set("optimization.runtimeChunk", "call", value => { + if (value === "single") { + return { + name: "runtime" + }; + } + if (value === true || value === "multiple") { + return { + name: entrypoint => `runtime~${entrypoint.name}` + }; + } + return value; + }); + this.set("optimization.noEmitOnErrors", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.checkWasmTypes", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.mangleWasmImports", false); + // TODO webpack 5 remove optimization.namedModules + this.set( + "optimization.namedModules", + "make", + options => options.mode === "development" + ); + this.set("optimization.hashedModuleIds", false); + // TODO webpack 5 add `chunkIds: "named"` default for development + // TODO webpack 5 add `chunkIds: "size"` default for production + // TODO webpack 5 remove optimization.namedChunks + this.set( + "optimization.namedChunks", + "make", + options => options.mode === "development" + ); + this.set( + "optimization.portableRecords", + "make", + options => + !!( + options.recordsInputPath || + options.recordsOutputPath || + options.recordsPath + ) + ); + this.set("optimization.minimize", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.minimizer", "make", options => [ + { + apply: compiler => { + // Lazy load the Terser plugin + const TerserPlugin = __webpack_require__(89301); + const SourceMapDevToolPlugin = __webpack_require__(11851); + new TerserPlugin({ + cache: true, + parallel: true, + sourceMap: + (options.devtool && /source-?map/.test(options.devtool)) || + (options.plugins && + options.plugins.some(p => p instanceof SourceMapDevToolPlugin)) + }).apply(compiler); + } + } + ]); + this.set("optimization.nodeEnv", "make", options => { + // TODO: In webpack 5, it should return `false` when mode is `none` + return options.mode || "production"; + }); + + this.set("resolve", "call", value => Object.assign({}, value)); + this.set("resolve.unsafeCache", true); + this.set("resolve.modules", ["node_modules"]); + this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); + this.set("resolve.mainFiles", ["index"]); + this.set("resolve.aliasFields", "make", options => { + if ( + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ) { + return ["browser"]; + } else { + return []; + } + }); + this.set("resolve.mainFields", "make", options => { + if ( + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ) { + return ["browser", "module", "main"]; + } else { + return ["module", "main"]; + } + }); + this.set("resolve.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolve.plugins) && + options.resolve.plugins.length > 0 + ); + }); + + this.set("resolveLoader", "call", value => Object.assign({}, value)); + this.set("resolveLoader.unsafeCache", true); + this.set("resolveLoader.mainFields", ["loader", "main"]); + this.set("resolveLoader.extensions", [".js", ".json"]); + this.set("resolveLoader.mainFiles", ["index"]); + this.set("resolveLoader.roots", "make", options => [options.context]); + this.set("resolveLoader.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolveLoader.plugins) && + options.resolveLoader.plugins.length > 0 + ); + }); + + this.set("infrastructureLogging", "call", value => + Object.assign({}, value) + ); + this.set("infrastructureLogging.level", "info"); + this.set("infrastructureLogging.debug", false); + } +} + +module.exports = WebpackOptionsDefaulter; + + +/***/ }), + +/***/ 285: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ + + +const WebpackError = __webpack_require__(97391); +const webpackOptionsSchema = __webpack_require__(37863); + +const getSchemaPart = (path, parents, additionalPath) => { + parents = parents || 0; + path = path.split("/"); + path = path.slice(0, path.length - parents); + if (additionalPath) { + additionalPath = additionalPath.split("/"); + path = path.concat(additionalPath); + } + let schemaPart = webpackOptionsSchema; + for (let i = 1; i < path.length; i++) { + const inner = schemaPart[path[i]]; + if (inner) schemaPart = inner; + } + return schemaPart; +}; + +const getSchemaPartText = (schemaPart, additionalPath) => { + if (additionalPath) { + for (let i = 0; i < additionalPath.length; i++) { + const inner = schemaPart[additionalPath[i]]; + if (inner) schemaPart = inner; + } + } + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + return schemaText; +}; + +const getSchemaPartDescription = schemaPart => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + if (schemaPart.description) { + return `\n-> ${schemaPart.description}`; + } + return ""; +}; + +const SPECIFICITY = { + type: 1, + oneOf: 1, + anyOf: 1, + allOf: 1, + additionalProperties: 2, + enum: 1, + instanceof: 1, + required: 2, + minimum: 2, + uniqueItems: 2, + minLength: 2, + minItems: 2, + minProperties: 2, + absolutePath: 2 +}; + +const filterMax = (array, fn) => { + const max = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === max); +}; + +const filterChildren = children => { + children = filterMax(children, err => + err.dataPath ? err.dataPath.length : 0 + ); + children = filterMax(children, err => SPECIFICITY[err.keyword] || 2); + return children; +}; + +const indent = (str, prefix, firstLine) => { + if (firstLine) { + return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); + } else { + return str.replace(/\n(?!$)/g, `\n${prefix}`); + } +}; + +class WebpackOptionsValidationError extends WebpackError { + constructor(validationErrors) { + super( + "Invalid configuration object. " + + "Webpack has been initialised using a configuration object that does not match the API schema.\n" + + validationErrors + .map( + err => + " - " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n") + ); + + this.name = "WebpackOptionsValidationError"; + this.validationErrors = validationErrors; + + Error.captureStackTrace(this, this.constructor); + } + + static formatSchema(schema, prevSchemas) { + prevSchemas = prevSchemas || []; + + const formatInnerSchema = (innerSchema, addSelf) => { + if (!addSelf) { + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas + ); + } + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas.concat(schema) + ); + }; + + if (schema.type === "string") { + if (schema.minLength === 1) { + return "non-empty string"; + } + if (schema.minLength > 1) { + return `string (min length ${schema.minLength})`; + } + return "string"; + } + if (schema.type === "boolean") { + return "boolean"; + } + if (schema.type === "number") { + return "number"; + } + if (schema.type === "object") { + if (schema.properties) { + const required = schema.required || []; + return `object { ${Object.keys(schema.properties) + .map(property => { + if (!required.includes(property)) return property + "?"; + return property; + }) + .concat(schema.additionalProperties ? ["…"] : []) + .join(", ")} }`; + } + if (schema.additionalProperties) { + return `object { : ${formatInnerSchema( + schema.additionalProperties + )} }`; + } + return "object"; + } + if (schema.type === "array") { + return `[${formatInnerSchema(schema.items)}]`; + } + + switch (schema.instanceof) { + case "Function": + return "function"; + case "RegExp": + return "RegExp"; + } + + if (schema.enum) { + return schema.enum.map(item => JSON.stringify(item)).join(" | "); + } + + if (schema.$ref) { + return formatInnerSchema(getSchemaPart(schema.$ref), true); + } + if (schema.allOf) { + return schema.allOf.map(formatInnerSchema).join(" & "); + } + if (schema.oneOf) { + return schema.oneOf.map(formatInnerSchema).join(" | "); + } + if (schema.anyOf) { + return schema.anyOf.map(formatInnerSchema).join(" | "); + } + return JSON.stringify(schema, null, 2); + } + + static formatValidationError(err) { + const dataPath = `configuration${err.dataPath}`; + if (err.keyword === "additionalProperties") { + const baseMessage = `${dataPath} has an unknown property '${ + err.params.additionalProperty + }'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; + if (!err.dataPath) { + switch (err.params.additionalProperty) { + case "debug": + return ( + `${baseMessage}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" + ); + } + return ( + `${baseMessage}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${err.params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); + } + return baseMessage; + } else if (err.keyword === "oneOf" || err.keyword === "anyOf") { + if (err.children && err.children.length > 0) { + if (err.schema.length === 1) { + const lastChild = err.children[err.children.length - 1]; + const remainingChildren = err.children.slice( + 0, + err.children.length - 1 + ); + return WebpackOptionsValidationError.formatValidationError( + Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign( + {}, + err.parentSchema, + lastChild.parentSchema + ) + }) + ); + } + const children = filterChildren(err.children); + if (children.length === 1) { + return WebpackOptionsValidationError.formatValidationError( + children[0] + ); + } + return ( + `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}\n` + + `Details:\n${children + .map( + err => + " * " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n")}` + ); + } + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "enum") { + if ( + err.parentSchema && + err.parentSchema.enum && + err.parentSchema.enum.length === 1 + ) { + return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; + } + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "allOf") { + return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; + } else if (err.keyword === "type") { + switch (err.params.type) { + case "object": + return `${dataPath} should be an object.${getSchemaPartDescription( + err.parentSchema + )}`; + case "string": + return `${dataPath} should be a string.${getSchemaPartDescription( + err.parentSchema + )}`; + case "boolean": + return `${dataPath} should be a boolean.${getSchemaPartDescription( + err.parentSchema + )}`; + case "number": + return `${dataPath} should be a number.${getSchemaPartDescription( + err.parentSchema + )}`; + case "array": + return `${dataPath} should be an array:\n${getSchemaPartText( + err.parentSchema + )}`; + } + return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "instanceof") { + return `${dataPath} should be an instance of ${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "required") { + const missingProperty = err.params.missingProperty.replace(/^\./, ""); + return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText( + err.parentSchema, + ["properties", missingProperty] + )}`; + } else if (err.keyword === "minimum") { + return `${dataPath} ${err.message}.${getSchemaPartDescription( + err.parentSchema + )}`; + } else if (err.keyword === "uniqueItems") { + return `${dataPath} should not contain the item '${ + err.data[err.params.i] + }' twice.${getSchemaPartDescription(err.parentSchema)}`; + } else if ( + err.keyword === "minLength" || + err.keyword === "minItems" || + err.keyword === "minProperties" + ) { + if (err.params.limit === 1) { + switch (err.keyword) { + case "minLength": + return `${dataPath} should be an non-empty string.${getSchemaPartDescription( + err.parentSchema + )}`; + case "minItems": + return `${dataPath} should be an non-empty array.${getSchemaPartDescription( + err.parentSchema + )}`; + case "minProperties": + return `${dataPath} should be an non-empty object.${getSchemaPartDescription( + err.parentSchema + )}`; + } + return `${dataPath} should be not empty.${getSchemaPartDescription( + err.parentSchema + )}`; + } else { + return `${dataPath} ${err.message}${getSchemaPartDescription( + err.parentSchema + )}`; + } + } else if (err.keyword === "not") { + return `${dataPath} should not be ${getSchemaPartText( + err.schema + )}\n${getSchemaPartText(err.parentSchema)}`; + } else if (err.keyword === "absolutePath") { + const baseMessage = `${dataPath}: ${ + err.message + }${getSchemaPartDescription(err.parentSchema)}`; + if (dataPath === "configuration.output.filename") { + return ( + `${baseMessage}\n` + + "Please use output.path to specify absolute path and output.filename for the file name." + ); + } + return baseMessage; + } else { + return `${dataPath} ${err.message} (${JSON.stringify( + err, + null, + 2 + )}).\n${getSchemaPartText(err.parentSchema)}`; + } + } +} + +module.exports = WebpackOptionsValidationError; + + +/***/ }), + +/***/ 52337: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const AsyncDependencyToInitialChunkError = __webpack_require__(67089); +const GraphHelpers = __webpack_require__(32973); + +/** @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 {Object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + */ + +/** + * @typedef {Object} ChunkGroupInfo + * @property {ChunkGroup} chunkGroup the chunk group + * @property {Set} minAvailableModules current minimal set of modules available at this point + * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified + * @property {Set[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules + * @property {QueueItem[]} skippedItems queue items that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) + * @property {Set} 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 + */ + +/** + * @typedef {Object} ChunkGroupDep + * @property {AsyncDependenciesBlock} block referencing block + * @property {ChunkGroup} chunkGroup referenced chunk group + */ + +/** + * @template T + * @param {Set} a first set + * @param {Set} b second set + * @returns {number} cmp + */ +const bySetSize = (a, b) => { + return b.size - a.size; +}; + +/** + * Extracts simplified info from the modules and their dependencies + * @param {Compilation} compilation the compilation + * @returns {Map, blocks: AsyncDependenciesBlock[]}>} the mapping block to modules and inner blocks + */ +const extraceBlockInfoMap = compilation => { + /** @type {Map, blocks: AsyncDependenciesBlock[]}>} */ + const blockInfoMap = new Map(); + + /** + * @param {Dependency} d dependency to iterate over + * @returns {void} + */ + const iteratorDependency = d => { + // We skip Dependencies without Reference + const ref = compilation.getDependencyReference(currentModule, d); + if (!ref) { + return; + } + // We skip Dependencies without Module pointer + const refModule = ref.module; + if (!refModule) { + return; + } + // We skip weak Dependencies + if (ref.weak) { + return; + } + + blockInfoModules.add(refModule); + }; + + /** + * @param {AsyncDependenciesBlock} b blocks to prepare + * @returns {void} + */ + const iteratorBlockPrepare = b => { + blockInfoBlocks.push(b); + blockQueue.push(b); + }; + + /** @type {Module} */ + let currentModule; + /** @type {DependenciesBlock} */ + let block; + /** @type {DependenciesBlock[]} */ + let blockQueue; + /** @type {Set} */ + let blockInfoModules; + /** @type {AsyncDependenciesBlock[]} */ + let blockInfoBlocks; + + for (const module of compilation.modules) { + blockQueue = [module]; + currentModule = module; + while (blockQueue.length > 0) { + block = blockQueue.pop(); + blockInfoModules = new Set(); + blockInfoBlocks = []; + + if (block.variables) { + for (const variable of block.variables) { + for (const dep of variable.dependencies) iteratorDependency(dep); + } + } + + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); + } + + if (block.blocks) { + for (const b of block.blocks) iteratorBlockPrepare(b); + } + + const blockInfo = { + modules: blockInfoModules, + blocks: blockInfoBlocks + }; + blockInfoMap.set(block, blockInfo); + } + } + + return blockInfoMap; +}; + +/** + * + * @param {Compilation} compilation the compilation + * @param {Entrypoint[]} inputChunkGroups input groups + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + * @param {Map} chunkDependencies dependencies for chunk groups + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + */ +const visitModules = ( + compilation, + inputChunkGroups, + chunkGroupInfoMap, + chunkDependencies, + blocksWithNestedBlocks, + allCreatedChunkGroups +) => { + const logger = compilation.getLogger("webpack.buildChunkGraph.visitModules"); + const { namedChunkGroups } = compilation; + + logger.time("prepare"); + const blockInfoMap = extraceBlockInfoMap(compilation); + + /** @type {Map} */ + const chunkGroupCounters = new Map(); + for (const chunkGroup of inputChunkGroups) { + chunkGroupCounters.set(chunkGroup, { + index: 0, + index2: 0 + }); + } + + let nextFreeModuleIndex = 0; + let nextFreeModuleIndex2 = 0; + + /** @type {Map} */ + const blockChunkGroups = new Map(); + + const ADD_AND_ENTER_MODULE = 0; + const ENTER_MODULE = 1; + const PROCESS_BLOCK = 2; + const LEAVE_MODULE = 3; + + /** + * @param {QueueItem[]} queue the queue array (will be mutated) + * @param {ChunkGroup} chunkGroup chunk group + * @returns {QueueItem[]} the queue array again + */ + const reduceChunkGroupToQueueItem = (queue, chunkGroup) => { + for (const chunk of chunkGroup.chunks) { + const module = chunk.entryModule; + queue.push({ + action: ENTER_MODULE, + block: module, + module, + chunk, + chunkGroup + }); + } + chunkGroupInfoMap.set(chunkGroup, { + chunkGroup, + minAvailableModules: new Set(), + minAvailableModulesOwned: true, + availableModulesToBeMerged: [], + skippedItems: [], + resultingAvailableModules: undefined, + children: undefined + }); + return queue; + }; + + // Start with the provided modules/chunks + /** @type {QueueItem[]} */ + let queue = inputChunkGroups + .reduce(reduceChunkGroupToQueueItem, []) + .reverse(); + /** @type {Map>} */ + const queueConnect = new Map(); + /** @type {Set} */ + const outdatedChunkGroupInfo = new Set(); + /** @type {QueueItem[]} */ + let queueDelayed = []; + + logger.timeEnd("prepare"); + + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + /** @type {DependenciesBlock} */ + let block; + /** @type {Set} */ + let minAvailableModules; + /** @type {QueueItem[]} */ + let skippedItems; + + // For each async Block in graph + /** + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock + * @returns {void} + */ + const iteratorBlock = b => { + // 1. We create a chunk for this Block + // but only once (blockChunkGroups map) + let c = blockChunkGroups.get(b); + if (c === undefined) { + c = namedChunkGroups.get(b.chunkName); + if (c && c.isInitial()) { + compilation.errors.push( + new AsyncDependencyToInitialChunkError(b.chunkName, module, b.loc) + ); + c = chunkGroup; + } else { + c = compilation.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + b.loc, + b.request + ); + chunkGroupCounters.set(c, { index: 0, index2: 0 }); + blockChunkGroups.set(b, c); + allCreatedChunkGroups.add(c); + } + } else { + // TODO webpack 5 remove addOptions check + if (c.addOptions) c.addOptions(b.groupOptions); + c.addOrigin(module, b.loc, b.request); + } + + // 2. We store the Block+Chunk mapping as dependency for the chunk + let deps = chunkDependencies.get(chunkGroup); + if (!deps) chunkDependencies.set(chunkGroup, (deps = [])); + deps.push({ + block: b, + chunkGroup: c + }); + + // 3. We create/update the chunk group info + let connectList = queueConnect.get(chunkGroup); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroup, connectList); + } + connectList.add(c); + + // 4. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c + }); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length) { + logger.time("visiting"); + while (queue.length) { + const queueItem = queue.pop(); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + if (chunkGroup !== queueItem.chunkGroup) { + chunkGroup = queueItem.chunkGroup; + const chunkGroupInfo = chunkGroupInfoMap.get(chunkGroup); + minAvailableModules = chunkGroupInfo.minAvailableModules; + skippedItems = chunkGroupInfo.skippedItems; + } + + switch (queueItem.action) { + case ADD_AND_ENTER_MODULE: { + if (minAvailableModules.has(module)) { + // already in parent chunks + // skip it for now, but enqueue for rechecking when minAvailableModules shrinks + skippedItems.push(queueItem); + break; + } + // We connect Module and Chunk when not already done + if (chunk.addModule(module)) { + module.addChunk(chunk); + } else { + // already connected, skip it + break; + } + } + // fallthrough + case ENTER_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex(module); + if (index === undefined) { + chunkGroup.setModuleIndex( + module, + chunkGroupCounters.get(chunkGroup).index++ + ); + } + } + + if (module.index === null) { + module.index = nextFreeModuleIndex++; + } + + queue.push({ + action: LEAVE_MODULE, + block, + module, + chunk, + chunkGroup + }); + } + // fallthrough + case PROCESS_BLOCK: { + // get prepared block info + const blockInfo = blockInfoMap.get(block); + + // Buffer items because order need to be reverse to get indicies correct + const skipBuffer = []; + const queueBuffer = []; + // Traverse all referenced modules + for (const refModule of blockInfo.modules) { + if (chunk.containsModule(refModule)) { + // skip early if already connected + continue; + } + if (minAvailableModules.has(refModule)) { + // already in parent chunks, skip it for now + skipBuffer.push({ + action: ADD_AND_ENTER_MODULE, + block: refModule, + module: refModule, + chunk, + chunkGroup + }); + continue; + } + // enqueue the add and enter to enter in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: ADD_AND_ENTER_MODULE, + block: refModule, + module: refModule, + chunk, + chunkGroup + }); + } + // Add buffered items in reversed order + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.push(skipBuffer[i]); + } + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + + // Traverse all Blocks + for (const block of blockInfo.blocks) iteratorBlock(block); + + if (blockInfo.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + break; + } + case LEAVE_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex2(module); + if (index === undefined) { + chunkGroup.setModuleIndex2( + module, + chunkGroupCounters.get(chunkGroup).index2++ + ); + } + } + + if (module.index2 === null) { + module.index2 = nextFreeModuleIndex2++; + } + break; + } + } + } + logger.timeEnd("visiting"); + + while (queueConnect.size > 0) { + logger.time("calculating available modules"); + + // Figure out new parents for chunk groups + // to get new available modules for these children + for (const [chunkGroup, targets] of queueConnect) { + const info = chunkGroupInfoMap.get(chunkGroup); + let minAvailableModules = info.minAvailableModules; + + // 1. Create a new Set of available modules at this points + const resultingAvailableModules = new Set(minAvailableModules); + for (const chunk of chunkGroup.chunks) { + for (const m of chunk.modulesIterable) { + resultingAvailableModules.add(m); + } + } + info.resultingAvailableModules = resultingAvailableModules; + if (info.children === undefined) { + info.children = targets; + } else { + for (const target of targets) { + info.children.add(target); + } + } + + // 2. Update chunk group info + for (const target of targets) { + let chunkGroupInfo = chunkGroupInfoMap.get(target); + if (chunkGroupInfo === undefined) { + chunkGroupInfo = { + chunkGroup: target, + minAvailableModules: undefined, + minAvailableModulesOwned: undefined, + availableModulesToBeMerged: [], + skippedItems: [], + resultingAvailableModules: undefined, + children: undefined + }; + chunkGroupInfoMap.set(target, chunkGroupInfo); + } + chunkGroupInfo.availableModulesToBeMerged.push( + resultingAvailableModules + ); + outdatedChunkGroupInfo.add(chunkGroupInfo); + } + } + queueConnect.clear(); + logger.timeEnd("calculating available modules"); + + if (outdatedChunkGroupInfo.size > 0) { + logger.time("merging available modules"); + // Execute the merge + for (const info of outdatedChunkGroupInfo) { + const availableModulesToBeMerged = info.availableModulesToBeMerged; + let cachedMinAvailableModules = info.minAvailableModules; + + // 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; + 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 + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + } else { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + /** @type {Set} */ + const newSet = new Set(); + const iterator = cachedMinAvailableModules[ + Symbol.iterator + ](); + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + while (!(it = iterator.next()).done) { + const module = it.value; + if (availableModules.has(module)) { + newSet.add(module); + } + } + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + + // Update the cache from the first queue + // if the chunkGroup is currently cached + if (chunkGroup === info.chunkGroup) { + minAvailableModules = cachedMinAvailableModules; + } + + changed = true; + break; + } + } + } + } + } + availableModulesToBeMerged.length = 0; + if (!changed) continue; + + // 2. Reconsider skipped items + for (const queueItem of info.skippedItems) { + queue.push(queueItem); + } + info.skippedItems.length = 0; + + // 3. Reconsider children chunk groups + if (info.children !== undefined) { + const chunkGroup = info.chunkGroup; + for (const c of info.children) { + let connectList = queueConnect.get(chunkGroup); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroup, connectList); + } + connectList.add(c); + } + } + } + outdatedChunkGroupInfo.clear(); + logger.timeEnd("merging available modules"); + } + } + + // Run queueDelayed when all items of the queue are processed + // This is important to get the global indicing correct + // Async blocks should be processed after all sync blocks are processed + if (queue.length === 0) { + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; + } + } +}; + +/** + * + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Map} chunkDependencies dependencies for chunk groups + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + */ +const connectChunkGroups = ( + blocksWithNestedBlocks, + chunkDependencies, + chunkGroupInfoMap +) => { + /** @type {Set} */ + let resultingAvailableModules; + + /** + * Helper function to check if all modules of a chunk are available + * + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {Set} availableModules the comparitor set + * @returns {boolean} return true if all modules of a chunk are available + */ + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + for (const module of chunk.modulesIterable) { + if (!availableModules.has(module)) return false; + } + } + return true; + }; + + // For each edge in the basic chunk graph + /** + * @param {ChunkGroupDep} dep the dependency used for filtering + * @returns {boolean} used to filter "edges" (aka Dependencies) that were pointing + * to modules that are already available. Also filters circular dependencies in the chunks graph + */ + const filterFn = dep => { + const depChunkGroup = dep.chunkGroup; + // TODO is this needed? + if (blocksWithNestedBlocks.has(dep.block)) return true; + if (areModulesAvailable(depChunkGroup, resultingAvailableModules)) { + return false; // break all modules are already available + } + return true; + }; + + // For all deps, check if chunk groups need to be connected + for (const [chunkGroup, deps] of chunkDependencies) { + if (deps.length === 0) continue; + + // 1. Get info from chunk group info map + const info = chunkGroupInfoMap.get(chunkGroup); + resultingAvailableModules = info.resultingAvailableModules; + + // 2. Foreach edge + for (let i = 0; i < deps.length; i++) { + const dep = deps[i]; + + // Filter inline, rather than creating a new array from `.filter()` + // TODO check if inlining filterFn makes sense here + if (!filterFn(dep)) { + continue; + } + const depChunkGroup = dep.chunkGroup; + const depBlock = dep.block; + + // 5. Connect block with chunk + GraphHelpers.connectDependenciesBlockAndChunkGroup( + depBlock, + depChunkGroup + ); + + // 6. Connect chunk with parent + GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); + } + } +}; + +/** + * Remove all unconnected chunk groups + * @param {Compilation} compilation the compilation + * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before + */ +const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + const idx = compilation.chunks.indexOf(chunk); + if (idx >= 0) compilation.chunks.splice(idx, 1); + chunk.remove("unconnected"); + } + chunkGroup.remove("unconnected"); + } + } +}; + +/** + * This method creates the Chunk graph from the Module graph + * @param {Compilation} compilation the compilation + * @param {Entrypoint[]} inputChunkGroups chunk groups which are processed + * @returns {void} + */ +const buildChunkGraph = (compilation, inputChunkGroups) => { + // SHARED STATE + + /** @type {Map} */ + const chunkDependencies = new Map(); + + /** @type {Set} */ + const allCreatedChunkGroups = new Set(); + + /** @type {Map} */ + const chunkGroupInfoMap = new Map(); + + /** @type {Set} */ + const blocksWithNestedBlocks = new Set(); + + // PART ONE + + visitModules( + compilation, + inputChunkGroups, + chunkGroupInfoMap, + chunkDependencies, + blocksWithNestedBlocks, + allCreatedChunkGroups + ); + + // PART TWO + + connectChunkGroups( + blocksWithNestedBlocks, + chunkDependencies, + chunkGroupInfoMap + ); + + // Cleaup work + + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); +}; + +module.exports = buildChunkGraph; + + +/***/ }), + +/***/ 22562: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +// TODO webpack 5 remove string type from a and b +/** + * Compare two locations + * @param {string|DependencyLocation} a A location node + * @param {string|DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value + */ +module.exports = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + if (a < b) return -1; + if (a > b) return 1; + return 0; + } else if (typeof b === "object") { + return 1; + } else { + return 0; + } + } else if (typeof a === "object") { + if (typeof b === "string") { + return -1; + } else if (typeof b === "object") { + if ("start" in a && "start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } + if ("name" in a && "name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } + if ("index" in a && "index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } + return 0; + } else { + return 0; + } + } +}; + + +/***/ }), + +/***/ 72890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const mkdirp = __webpack_require__(94327); +const { Tracer } = __webpack_require__(92430); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(49049); + +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ + +let inspector = undefined; + +try { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + inspector = __webpack_require__(57012); +} catch (e) { + console.log("Unable to CPU profile in < node 8.0"); +} + +class Profiler { + constructor(inspector) { + this.session = undefined; + this.inspector = inspector; + } + + 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(); + } + + 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(); + } + + return Promise.resolve(); + } + + stopProfiling() { + return this.sendCommand("Profiler.stop"); + } +} + +/** + * 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 {string} outputPath The location where to write the log. + * @returns {Trace} The trace object + */ +const createTrace = outputPath => { + const trace = new Tracer({ + noStream: true + }); + const profiler = new Profiler(inspector); + if (/\/|\\/.test(outputPath)) { + const dirPath = path.dirname(outputPath); + mkdirp.sync(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: "" + } + ] + } + } + }); + + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" + } + } + }); + + return { + trace, + counter, + profiler, + end: callback => { + // Wait until the write stream finishes. + fsStream.on("finish", () => { + callback(); + }); + // Tear down the readable trace stream. + trace.push(null); + } + }; +}; + +const pluginName = "ProfilingPlugin"; + +class ProfilingPlugin { + /** + * @param {ProfilingPluginOptions=} opts options object + */ + constructor(opts) { + validateOptions(schema, opts || {}, "Profiling plugin"); + opts = opts || {}; + this.outputPath = opts.outputPath || "events.json"; + } + + apply(compiler) { + const tracer = createTrace(this.outputPath); + tracer.profiler.startProfiling(); + + // Compiler Hooks + Object.keys(compiler.hooks).forEach(hookName => { + compiler.hooks[hookName].intercept( + makeInterceptorFor("Compiler", tracer)(hookName) + ); + }); + + Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { + compiler.resolverFactory.hooks[hookName].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); + interceptTemplateInstancesFrom(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) => { + tracer.profiler.stopProfiling().then(parsedResults => { + if (parsedResults === undefined) { + tracer.profiler.destroy(); + tracer.trace.flush(); + tracer.end(callback); + return; + } + + 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" + } + } + }); + + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile + } + } + }); + + tracer.profiler.destroy(); + tracer.trace.flush(); + tracer.end(callback); + }); + } + ); + } +} + +const interceptTemplateInstancesFrom = (compilation, tracer) => { + const { + mainTemplate, + chunkTemplate, + hotUpdateChunkTemplate, + moduleTemplates + } = compilation; + + const { javascript, webassembly } = moduleTemplates; + + [ + { + instance: mainTemplate, + name: "MainTemplate" + }, + { + instance: chunkTemplate, + name: "ChunkTemplate" + }, + { + instance: hotUpdateChunkTemplate, + name: "HotUpdateChunkTemplate" + }, + { + instance: javascript, + name: "JavaScriptModuleTemplate" + }, + { + instance: webassembly, + name: "WebAssemblyModuleTemplate" + } + ].forEach(templateObject => { + Object.keys(templateObject.instance.hooks).forEach(hookName => { + templateObject.instance.hooks[hookName].intercept( + makeInterceptorFor(templateObject.name, tracer)(hookName) + ); + }); + }); +}; + +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + Object.keys(instance.hooks).forEach(hookName => { + instance.hooks[hookName].intercept( + makeInterceptorFor(logLabel, tracer)(hookName) + ); + }); + } +}; + +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + "javascript/auto", + "javascript/dynamic", + "javascript/esm", + "json", + "webassembly/experimental" + ]; + + moduleTypes.forEach(moduleType => { + moduleFactory.hooks.parser + .for(moduleType) + .tap("ProfilingPlugin", (parser, parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + }); +}; + +const makeInterceptorFor = (instance, tracer) => hookName => ({ + register: ({ name, type, context, fn }) => { + const newFn = makeNewProfiledTapFn(hookName, tracer, { + name, + type, + fn + }); + return { + name, + type, + context, + fn: newFn + }; + } +}); + +// 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); + } + + 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 = ProfilingPlugin; +module.exports.Profiler = Profiler; + + +/***/ }), + +/***/ 67045: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class AMDDefineDependency extends NullDependency { + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; + } + + get type() { + return "amd define"; + } +} + +AMDDefineDependency.Template = class AMDDefineDependencyTemplate { + get definitions() { + return { + f: [ + "var __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + o: ["", "!(module.exports = #)"], + of: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + af: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + ao: ["", "!(#, module.exports = #)"], + aof: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + lf: [ + "var XXX, XXXmodule;", + "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" + ], + lo: ["var XXX;", "!(XXX = #)"], + lof: [ + "var XXX, XXXfactory, XXXmodule;", + "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" + ], + laf: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" + ], + lao: ["var XXX;", "!(#, XXX = #)"], + laof: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` + ] + }; + } + + apply(dependency, source) { + const branch = this.branch(dependency); + const defAndText = this.definitions[branch]; + const definitions = defAndText[0]; + const text = defAndText[1]; + this.replace(dependency, source, definitions, text); + } + + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); + } + + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } + + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); + } + + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } + + const texts = text.split("#"); + + if (definition) source.insert(0, definition); + + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); + current = dependency.arrayRange[1]; + } + + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; + } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); + } +}; + +module.exports = AMDDefineDependency; + + +/***/ }), + +/***/ 27057: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireContextDependency = __webpack_require__(99890); +const ConstDependency = __webpack_require__(71101); +const AMDDefineDependency = __webpack_require__(67045); +const AMDRequireArrayDependency = __webpack_require__(63960); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); + +const isBoundFunctionExpression = expr => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; +}; + +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; + +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; + +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); + } + + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + param.items.forEach((param, idx) => { + if ( + param.isString() && + ["require", "module", "exports"].includes(param.string) + ) + identifiers[idx] = param.string; + const result = this.processItem(parser, expr, param, namedModule); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isConstArray()) { + const deps = []; + param.array.forEach((request, idx) => { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + }); + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + param.options.forEach(param => { + const result = this.processItem(parser, expr, param); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.range); + } else if (["require", "exports", "module"].includes(param.string)) { + dep = new ConstDependency(param.string, param.range); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string, + namedModule + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + {}, + 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; + } + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { + fnParams = fn.callee.object.params; + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } + } + } + let fnRenames = parser.scope.renames.createChild(); + if (array) { + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; + } + return true; + }); + } + } + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(fnParams, () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.body.type === "BlockStatement") { + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope( + fn.callee.object.params.filter( + i => !["require", "module", "exports"].includes(i.name) + ), + () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.callee.object.body.type === "BlockStatement") { + parser.walkStatement(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } + } else if (fn || obj) { + parser.walkExpression(fn || obj); + } + + const dep = this.newDefineDependency( + expr.range, + array ? array.range : null, + fn ? fn.range : null, + obj ? obj.range : null, + namedModule ? namedModule : null + ); + dep.loc = expr.loc; + if (namedModule) { + dep.localModule = LocalModulesHelpers.addLocalModule( + parser.state, + namedModule + ); + } + parser.state.current.addDependency(dep); + return true; + } + + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} +module.exports = AMDDefineDependencyParserPlugin; + + +/***/ }), + +/***/ 85812: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const AMDRequireDependency = __webpack_require__(73985); +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireArrayDependency = __webpack_require__(63960); +const AMDRequireContextDependency = __webpack_require__(99890); +const AMDDefineDependency = __webpack_require__(67045); +const UnsupportedDependency = __webpack_require__(15826); +const LocalModuleDependency = __webpack_require__(56570); + +const NullFactory = __webpack_require__(40438); + +const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(9994); +const AMDDefineDependencyParserPlugin = __webpack_require__(27057); + +const AliasPlugin = __webpack_require__(15005); + +const ParserHelpers = __webpack_require__(23999); + +class AMDPlugin { + constructor(options, amdOptions) { + this.amdOptions = amdOptions; + this.options = options; + } + + apply(compiler) { + const options = this.options; + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + "AMDPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + AMDRequireDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireArrayDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDDefineDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); + + compilation.dependencyFactories.set( + UnsupportedDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() + ); + + compilation.dependencyFactories.set( + LocalModuleDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; + + const setExpressionToModule = (outerExpr, module) => { + parser.hooks.expression.for(outerExpr).tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency(module, expr.range); + dep.userRequest = outerExpr; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + }; + + new AMDRequireDependenciesBlockParserPlugin(options).apply(parser); + new AMDDefineDependencyParserPlugin(options).apply(parser); + + setExpressionToModule("require.amd", "!!webpack amd options"); + setExpressionToModule("define.amd", "!!webpack amd options"); + setExpressionToModule("define", "!!webpack amd define"); + + parser.hooks.expression + .for("__webpack_amd_options__") + .tap("AMDPlugin", () => + parser.state.current.addVariable( + "__webpack_amd_options__", + JSON.stringify(amdOptions) + ) + ); + parser.hooks.evaluateTypeof + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateTypeof + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateIdentifier + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("define.amd", true) + ); + parser.hooks.evaluateIdentifier + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("require.amd", true) + ); + parser.hooks.typeof + .for("define") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.canRename + .for("define") + .tap("AMDPlugin", ParserHelpers.approve); + parser.hooks.rename.for("define").tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency( + "!!webpack amd define", + expr.range + ); + dep.userRequest = "define"; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("AMDPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("AMDPlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("AMDPlugin", () => { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("AMDPlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: "amdefine", + alias: __webpack_require__.ab + "amd-define.js" + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd options", + alias: __webpack_require__.ab + "amd-options.js" + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd define", + alias: __webpack_require__.ab + "amd-define.js" + }, + "resolve" + ).apply(resolver); + }); + }); + } +} +module.exports = AMDPlugin; + + +/***/ }), + +/***/ 63960: +/***/ ((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__(57282); + +class AMDRequireArrayDependency extends Dependency { + constructor(depsArray, range) { + super(); + this.depsArray = depsArray; + this.range = range; + } + + get type() { + return "amd require array"; + } +} + +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate { + apply(dep, source, runtime) { + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, runtime) { + const requires = dep.depsArray.map(dependency => { + return this.contentForDependency(dependency, runtime); + }); + return `[${requires.join(", ")}]`; + } + + contentForDependency(dep, runtime) { + if (typeof dep === "string") { + return dep; + } + + if (dep.localModule) { + return dep.localModule.variableName(); + } else { + return runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + } + } +}; + +module.exports = AMDRequireArrayDependency; + + +/***/ }), + +/***/ 99890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ContextDependency = __webpack_require__(11583); +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } +} +AMDRequireContextDependency.Template = __webpack_require__(54380); +module.exports = AMDRequireContextDependency; + + +/***/ }), + +/***/ 32894: +/***/ ((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__(22814); +const AMDRequireDependency = __webpack_require__(73985); + +module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + super(null, module, loc, request); + this.expr = expr; + this.outerRange = expr.range; + this.arrayRange = arrayRange; + this.functionBindThis = false; + this.functionRange = functionRange; + this.errorCallbackBindThis = false; + this.errorCallbackRange = errorCallbackRange; + this.bindThis = true; + if (arrayRange && functionRange && errorCallbackRange) { + this.range = [arrayRange[0], errorCallbackRange[1]]; + } else if (arrayRange && functionRange) { + this.range = [arrayRange[0], functionRange[1]]; + } else if (arrayRange) { + this.range = arrayRange; + } else if (functionRange) { + this.range = functionRange; + } else { + this.range = expr.range; + } + const dep = this.newRequireDependency(); + dep.loc = loc; + this.addDependency(dep); + } + + newRequireDependency() { + return new AMDRequireDependency(this); + } +}; + + +/***/ }), + +/***/ 9994: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireArrayDependency = __webpack_require__(63960); +const AMDRequireContextDependency = __webpack_require__(99890); +const AMDRequireDependenciesBlock = __webpack_require__(32894); +const UnsupportedDependency = __webpack_require__(15826); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); +const ConstDependency = __webpack_require__(71101); +const getFunctionExpression = __webpack_require__(64197); +const UnsupportedFeatureWarning = __webpack_require__(99953); + +class AMDRequireDependenciesBlockParserPlugin { + constructor(options) { + this.options = options; + } + + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter(i => { + return !["require", "module", "exports"].includes(i.name); + }), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); + } + } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; + } + } else { + parser.walkExpression(expression); + } + return bindThis; + } + + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); + } + + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of param.items) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isConstArray()) { + const deps = []; + for (const request of param.array) { + let dep, localModule; + if (request === "require") { + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of param.options) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.string); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.buildInfo.moduleArgument, + param.range + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.buildInfo.exportsArgument, + param.range + ); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + {}, + 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 dep; + let result; + + const old = parser.state.current; + + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression(expr.arguments[0]); + dep = this.newRequireDependenciesBlock( + expr, + param.range, + expr.arguments.length > 1 ? expr.arguments[1].range : null, + expr.arguments.length > 2 ? expr.arguments[2].range : null, + parser.state.module, + expr.loc, + this.processArrayForRequestString(param) + ); + parser.state.current = dep; + } + + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock(dep); + return true; + } + + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + if (!result) { + dep = new UnsupportedDependency("unsupported", expr.range); + old.addDependency(dep); + if (parser.state.module) { + parser.state.module.errors.push( + new UnsupportedFeatureWarning( + parser.state.module, + "Cannot statically analyse 'require(…, …)' in line " + + expr.loc.start.line, + expr.loc + ) + ); + } + dep = null; + return true; + } + dep.functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + dep.errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (dep) parser.state.current.addBlock(dep); + } + return true; + } + } + + newRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + return new AMDRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} +module.exports = AMDRequireDependenciesBlockParserPlugin; + + +/***/ }), + +/***/ 73985: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class AMDRequireDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } +} + +AMDRequireDependency.Template = class AMDRequireDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "AMD require" + }); + + // has array range but no function range + if (depBlock.arrayRange && !depBlock.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;}).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.replace( + depBlock.arrayRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has function range but no array range + if (depBlock.functionRange && !depBlock.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, __webpack_require__, exports, module)).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.functionRange[0] - 1, + startBlock + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has array range, function range, and errorCallbackRange + if ( + depBlock.arrayRange && + depBlock.functionRange && + depBlock.errorCallbackRange + ) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(`; + const endBlock = `${ + depBlock.errorCallbackBindThis ? ".bind(this)" : "" + })`; + + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.errorCallbackRange[0] - 1, + errorRangeBlock + ); + source.replace( + depBlock.errorCallbackRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has array range, function range, but no errorCallbackRange + if (depBlock.arrayRange && depBlock.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + } + } +}; + +module.exports = AMDRequireDependency; + + +/***/ }), + +/***/ 34345: +/***/ ((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__(90865); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); + +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "amd require"; + } +} + +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; + + +/***/ }), + +/***/ 85358: +/***/ ((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__(71101); +const CommonJsRequireDependency = __webpack_require__(37504); +const CommonJsRequireContextDependency = __webpack_require__(26791); +const RequireResolveDependency = __webpack_require__(43519); +const RequireResolveContextDependency = __webpack_require__(83309); +const RequireResolveHeaderDependency = __webpack_require__(69647); +const RequireHeaderDependency = __webpack_require__(22928); + +const NullFactory = __webpack_require__(40438); + +const RequireResolveDependencyParserPlugin = __webpack_require__(68349); +const CommonJsRequireDependencyParserPlugin = __webpack_require__(37278); + +const ParserHelpers = __webpack_require__(23999); + +class CommonJsPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "CommonJsPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + CommonJsRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + return; + + const requireExpressions = [ + "require", + "require.resolve", + "require.resolveWeak" + ]; + for (let expression of requireExpressions) { + parser.hooks.typeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToIdentifier(expression, true) + ); + } + + parser.hooks.evaluateTypeof + .for("module") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + parser.scope.definitions.add("require"); + return true; + }); + parser.hooks.canRename + .for("require") + .tap("CommonJsPlugin", () => true); + parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { + // define the require variable. It's still undefined, but not "not defined". + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true); + parser.hooks.evaluateTypeof + .for("exports") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + + new CommonJsRequireDependencyParserPlugin(options).apply(parser); + new RequireResolveDependencyParserPlugin(options).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsPlugin", handler); + } + ); + } +} +module.exports = CommonJsPlugin; + + +/***/ }), + +/***/ 26791: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); + +class CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "cjs require context"; + } +} + +CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; + + +/***/ }), + +/***/ 37504: +/***/ ((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__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); + +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "cjs require"; + } +} + +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = CommonJsRequireDependency; + + +/***/ }), + +/***/ 37278: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const CommonJsRequireDependency = __webpack_require__(37504); +const CommonJsRequireContextDependency = __webpack_require__(26791); +const RequireHeaderDependency = __webpack_require__(22928); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); +const ParserHelpers = __webpack_require__(23999); + +class CommonJsRequireDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + const options = this.options; + + const processItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + expr.range, + param, + expr, + options, + {}, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.expression + .for("require.cache") + .tap( + "CommonJsRequireDependencyParserPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c" + ) + ); + parser.hooks.expression + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", expr => { + const dep = new CommonJsRequireContextDependency( + { + request: options.unknownContextRequest, + recursive: options.unknownContextRecursive, + regExp: options.unknownContextRegExp, + mode: "sync" + }, + expr.range + ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }); + + const createHandler = callNew => expr => { + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + const prevLength = parser.state.current.dependencies.length; + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + for (const p of param.options) { + const result = processItem(expr, p); + if (result === undefined) { + isExpression = true; + } + } + if (isExpression) { + parser.state.current.dependencies.length = prevLength; + } else { + return true; + } + } + if ( + param.isString() && + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) + ) { + const dep = new LocalModuleDependency(localModule, expr.range, callNew); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } else { + const result = processItem(expr, param); + if (result === undefined) { + processContext(expr, param); + } else { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } + return true; + } + }; + parser.hooks.call + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + parser.hooks.call + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + } +} +module.exports = CommonJsRequireDependencyParserPlugin; + + +/***/ }), + +/***/ 71101: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class ConstDependency extends NullDependency { + constructor(expression, range, requireWebpackRequire) { + super(); + this.expression = expression; + this.range = range; + this.requireWebpackRequire = requireWebpackRequire; + } + + updateHash(hash) { + hash.update(this.range + ""); + hash.update(this.expression + ""); + } +} + +ConstDependency.Template = class ConstDependencyTemplate { + apply(dep, source) { + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + } +}; + +module.exports = ConstDependency; + + +/***/ }), + +/***/ 11583: +/***/ ((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__(57282); +const CriticalDependencyWarning = __webpack_require__(54983); + +const regExpToString = r => (r ? r + "" : ""); + +class ContextDependency extends Dependency { + // options: { request, recursive, regExp, include, exclude, mode, chunkName, groupOptions } + constructor(options) { + super(); + this.options = options; + this.userRequest = this.options.request; + /** @type {false | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; + if (this.options.regExp.global || this.options.regExp.sticky) { + this.options.regExp = null; + this.hadGlobalOrStickyRegExp = true; + } + } + + getResourceIdentifier() { + return ( + `context${this.options.request} ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + ); + } + + getWarnings() { + let warnings = super.getWarnings() || []; + if (this.critical) { + warnings.push(new CriticalDependencyWarning(this.critical)); + } + if (this.hadGlobalOrStickyRegExp) { + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } + return warnings; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(ContextDependency.prototype, "async", { + configurable: false, + get() { + throw new Error( + "ContextDependency.async was removed. Use ContextDependency.options.mode instead." + ); + }, + set() { + throw new Error( + "ContextDependency.async was removed. Pass options.mode to constructor instead" + ); + } +}); + +module.exports = ContextDependency; + + +/***/ }), + +/***/ 5594: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ContextDependencyHelpers = exports; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quotemeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; + } + return { + context, + prefix + }; +}; + +const splitQueryFromPostfix = postfix => { + const idx = postfix.indexOf("?"); + let query = ""; + if (idx >= 0) { + query = postfix.substr(idx); + postfix = postfix.substr(0, idx); + } + return { + postfix, + query + }; +}; + +ContextDependencyHelpers.create = ( + Dep, + range, + param, + expr, + options, + contextOptions, + // when parser is not passed in, expressions won't be walked + parser = null +) => { + 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 { postfix, query } = splitQueryFromPostfix(postfixRaw); + + // 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` + // context: "./context" + // prefix: "./pre" + // innerQuasis: [BEE("inner"), BEE("inner2")] + // (BEE = BasicEvaluatedExpression) + // postfix: "post" + // query: "?query" + // regExp: /^\.\/pre.*inner.*inner2.*post$/ + const regExp = new RegExp( + `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + + 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 + if (parser) { + parser.walkExpression(part.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 { postfix, query } = splitQueryFromPostfix(postfixRaw); + const regExp = new RegExp( + `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( + postfix + )}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange) { + 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( + Object.assign( + { + request: options.exprContextRequest, + recursive: options.exprContextRecursive, + regExp: options.exprContextRegExp, + mode: "sync" + }, + contextOptions + ), + range, + param.range + ); + dep.loc = expr.loc; + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; + + if (parser) { + parser.walkExpression(param.expression); + } + + return dep; + } +}; + + +/***/ }), + +/***/ 6174: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ContextDependencyTemplateAsId { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` + ); + } else { + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` + ); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsId; + + +/***/ }), + +/***/ 54380: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ContextDependencyTemplateAsRequireCall { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsRequireCall; + + +/***/ }), + +/***/ 89079: +/***/ ((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__(90865); + +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest) { + super(request); + if (userRequest) { + this.userRequest = userRequest; + } + } + + get type() { + return "context element"; + } +} + +module.exports = ContextElementDependency; + + +/***/ }), + +/***/ 54983: +/***/ ((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__(97391); + +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); + + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = CriticalDependencyWarning; + + +/***/ }), + +/***/ 53104: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const NullDependency = __webpack_require__(5088); + +class DelegatedExportsDependency extends NullDependency { + constructor(originModule, exports) { + super(); + this.originModule = originModule; + this.exports = exports; + } + + get type() { + return "delegated exports"; + } + + getReference() { + return new DependencyReference(this.originModule, true, false); + } + + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; + } +} + +module.exports = DelegatedExportsDependency; + + +/***/ }), + +/***/ 25930: +/***/ ((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__(90865); + +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "delegated source"; + } +} + +module.exports = DelegatedSourceDependency; + + +/***/ }), + +/***/ 71722: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + + +/** @typedef {import("../Module")} Module */ + +class DependencyReference { + // TODO webpack 5: module must be dynamic, you must pass a function returning a module + // This is needed to remove the hack in ConcatenatedModule + // The problem is that the `module` in Dependency could be replaced i. e. because of Scope Hoisting + /** + * + * @param {Module} module the referenced module + * @param {string[] | boolean} importedNames imported named from the module + * @param {boolean=} weak if this is a weak reference + * @param {number} order the order information or NaN if don't care + */ + constructor(module, importedNames, weak = false, order = NaN) { + // TODO webpack 5: make it a getter + this.module = module; + // true: full object + // false: only sideeffects/no export + // array of strings: the exports with this names + this.importedNames = importedNames; + this.weak = !!weak; + this.order = order; + } + + /** + * @param {DependencyReference[]} array an array (will be modified) + * @returns {DependencyReference[]} the array again + */ + static sort(array) { + /** @type {WeakMap} */ + const originalOrder = new WeakMap(); + let i = 0; + for (const ref of array) { + originalOrder.set(ref, i++); + } + return array.sort((a, b) => { + const aOrder = a.order; + const bOrder = b.order; + if (isNaN(aOrder)) { + if (!isNaN(bOrder)) { + return 1; + } + } else { + if (isNaN(bOrder)) { + return -1; + } + if (aOrder !== bOrder) { + return aOrder - bOrder; + } + } + const aOrg = originalOrder.get(a); + const bOrg = originalOrder.get(b); + return aOrg - bOrg; + }); + } +} + +module.exports = DependencyReference; + + +/***/ }), + +/***/ 66279: +/***/ ((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__(57282); + +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } + + get type() { + return "dll entry"; + } +} + +module.exports = DllEntryDependency; + + +/***/ }), + +/***/ 75159: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const NullDependency = __webpack_require__(5088); +const HarmonyImportDependency = __webpack_require__(81599); + +class HarmonyAcceptDependency extends NullDependency { + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; + } + + get type() { + return "accepted harmony modules"; + } +} + +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate { + apply(dep, source, runtime) { + const content = dep.dependencies + .filter(dependency => + HarmonyImportDependency.Template.isImportEmitted(dependency, source) + ) + .map(dependency => dependency.getImportStatement(true, runtime)) + .join(""); + + if (dep.hasCallback) { + source.insert( + dep.range[0], + `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + ); + source.insert( + dep.range[1], + ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + ); + return; + } + + source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); + } +}; + +module.exports = HarmonyAcceptDependency; + + +/***/ }), + +/***/ 66136: +/***/ ((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__(81599); + +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request, originModule, parserScope) { + super(request, originModule, NaN, parserScope); + this.weak = true; + } + + get type() { + return "harmony accept"; + } +} + +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) {} +}; + +module.exports = HarmonyAcceptImportDependency; + + +/***/ }), + +/***/ 1533: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class HarmonyCompatibilityDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } + + get type() { + return "harmony export header"; + } +} + +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source, runtime) { + const usedExports = dep.originModule.usedExports; + if (usedExports !== false && !Array.isArray(usedExports)) { + const content = runtime.defineEsModuleFlagStatement({ + exportsArgument: dep.originModule.exportsArgument + }); + source.insert(-10, content); + } + } +}; + +module.exports = HarmonyCompatibilityDependency; + + +/***/ }), + +/***/ 59310: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const HarmonyInitDependency = __webpack_require__(27204); + +module.exports = class HarmonyDetectionParserPlugin { + apply(parser) { + parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { + const isStrictHarmony = parser.state.module.type === "javascript/esm"; + const isHarmony = + isStrictHarmony || + ast.body.some( + statement => + statement.type === "ImportDeclaration" || + statement.type === "ExportDefaultDeclaration" || + statement.type === "ExportNamedDeclaration" || + statement.type === "ExportAllDeclaration" + ); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(module); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addDependency(compatDep); + const initDep = new HarmonyInitDependency(module); + initDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -2 + }; + module.addDependency(initDep); + parser.state.harmonyParserScope = parser.state.harmonyParserScope || {}; + parser.scope.isStrict = true; + module.buildMeta.exportsType = "namespace"; + module.buildInfo.strict = true; + module.buildInfo.exportsArgument = "__webpack_exports__"; + if (isStrictHarmony) { + module.buildMeta.strictHarmonyModule = true; + module.buildInfo.moduleArgument = "__webpack_module__"; + } + } + }); + + const skipInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return true; + } + }; + + const nullInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return null; + } + }; + + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifer of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.typeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.evaluate + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.expression + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.call + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + } + } +}; + + +/***/ }), + +/***/ 49180: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyExportHeaderDependency = __webpack_require__(21320); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const ConstDependency = __webpack_require__(71101); + +module.exports = class HarmonyExportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + } + + apply(parser) { + parser.hooks.export.tap( + "HarmonyExportDependencyParserPlugin", + statement => { + const dep = new HarmonyExportHeaderDependency( + statement.declaration && statement.declaration.range, + statement.range + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImport.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = Object.create(statement.loc); + clearDep.loc.index = -1; + parser.state.current.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = Object.create(statement.loc); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.exportExpression.tap( + "HarmonyExportDependencyParserPlugin", + (statement, expr) => { + const comments = parser.getComments([ + statement.range[0], + expr.range[0] + ]); + const dep = new HarmonyExportExpressionDependency( + parser.state.module, + expr.range, + statement.range, + comments + .map(c => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join("") + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportDeclaration.tap( + "HarmonyExportDependencyParserPlugin", + statement => {} + ); + parser.hooks.exportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, id, name, idx) => { + const rename = parser.scope.renames.get(id); + let dep; + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + if (rename === "imported var") { + const settings = parser.state.harmonySpecifier.get(id); + dep = new HarmonyExportImportedSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + harmonyNamedExports, + null, + this.strictExportPresence + ); + } else { + dep = new HarmonyExportSpecifierDependency( + parser.state.module, + id, + name + ); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || []; + } + const dep = new HarmonyExportImportedSpecifierDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope, + id, + name, + harmonyNamedExports, + harmonyStarExports && harmonyStarExports.slice(), + this.strictExportPresence + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + } +}; + + +/***/ }), + +/***/ 84245: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class HarmonyExportExpressionDependency extends NullDependency { + constructor(originModule, range, rangeStatement, prefix) { + super(); + this.originModule = originModule; + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + } + + get type() { + return "harmony export expression"; + } + + getExports() { + return { + exports: ["default"], + dependencies: undefined + }; + } +} + +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const used = dep.originModule.isUsed("default"); + const content = this.getContent(dep.originModule, used); + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } + + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + } + + getContent(module, used) { + const exportsName = module.exportsArgument; + if (used) { + return `/* harmony default export */ ${exportsName}[${JSON.stringify( + used + )}] = `; + } + return "/* unused harmony default export */ var _unused_webpack_default_export = "; + } +}; + +module.exports = HarmonyExportExpressionDependency; + + +/***/ }), + +/***/ 21320: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + } + + get type() { + return "harmony export header"; + } +} + +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); + } +}; + +module.exports = HarmonyExportHeaderDependency; + + +/***/ }), + +/***/ 22864: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const Template = __webpack_require__(96066); +const HarmonyLinkingError = __webpack_require__(30327); + +/** @typedef {import("../Module")} Module */ + +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ + +/** @type {Map} */ +const EMPTY_MAP = new Map(); + +class ExportMode { + /** + * @param {ExportModeType} type type of the mode + */ + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; + /** @type {string|null} */ + this.name = null; + /** @type {Map} */ + this.map = EMPTY_MAP; + /** @type {Set|null} */ + this.ignored = null; + /** @type {Module|null} */ + this.module = null; + /** @type {string|null} */ + this.userRequest = null; + } +} + +const EMPTY_STAR_MODE = new ExportMode("empty-star"); + +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + activeExports, + otherStarExports, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id; + this.redirectedId = undefined; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.strictExportPresence = strictExportPresence; + } + + get type() { + return "harmony export imported specifier"; + } + + get _id() { + return this.redirectedId || this.id; + } + + getMode(ignoreUnused) { + const name = this.name; + const id = this._id; + const used = this.originModule.isUsed(name); + const importedModule = this._module; + + if (!importedModule) { + const mode = new ExportMode("missing"); + mode.userRequest = this.userRequest; + return mode; + } + + if ( + !ignoreUnused && + (name ? !used : this.originModule.usedExports === false) + ) { + const mode = new ExportMode("unused"); + mode.name = name || "*"; + return mode; + } + + const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; + if (name && id === "default" && importedModule.buildMeta) { + if (!importedModule.buildMeta.exportsType) { + const mode = new ExportMode( + strictHarmonyModule + ? "reexport-non-harmony-default-strict" + : "reexport-non-harmony-default" + ); + mode.name = name; + mode.module = importedModule; + return mode; + } else if (importedModule.buildMeta.exportsType === "named") { + const mode = new ExportMode("reexport-named-default"); + mode.name = name; + mode.module = importedModule; + return mode; + } + } + + const isNotAHarmonyModule = + importedModule.buildMeta && !importedModule.buildMeta.exportsType; + if (name) { + let mode; + if (id) { + // export { name as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("rexport-non-harmony-undefined"); + mode.name = name; + } else { + mode = new ExportMode("safe-reexport"); + mode.map = new Map([[name, id]]); + } + } else { + // export { * as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + } else { + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; + } + } + mode.module = importedModule; + return mode; + } + + const hasUsedExports = Array.isArray(this.originModule.usedExports); + const hasProvidedExports = Array.isArray( + importedModule.buildMeta.providedExports + ); + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); + + // export * + if (hasUsedExports) { + // reexport * with known used exports + if (hasProvidedExports) { + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + if (!importedModule.buildMeta.providedExports.includes(id)) + return false; + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("checked-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + if (hasProvidedExports) { + const map = new Map( + importedModule.buildMeta.providedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + const mode = new ExportMode("dynamic-reexport"); + mode.module = importedModule; + mode.ignored = new Set([ + "default", + ...this.activeExports, + ...activeFromOtherStarExports + ]); + return mode; + } + + getReference() { + const mode = this.getMode(false); + + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + return null; + + case "reexport-non-harmony-default": + case "reexport-named-default": + return new DependencyReference( + mode.module, + ["default"], + false, + this.sourceOrder + ); + + case "reexport-namespace-object": + case "reexport-non-harmony-default-strict": + case "reexport-fake-namespace-object": + case "rexport-non-harmony-undefined": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder + ); + + case "safe-reexport": + case "checked-reexport": + return new DependencyReference( + mode.module, + Array.from(mode.map.values()), + false, + this.sourceOrder + ); + + case "dynamic-reexport": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder + ); + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + _discoverActiveExportsFromOtherStartExports() { + if (!this.otherStarExports) return new Set(); + const result = new Set(); + // try to learn impossible exports from other star exports with provided exports + for (const otherStarExport of this.otherStarExports) { + const otherImportedModule = otherStarExport._module; + if ( + otherImportedModule && + Array.isArray(otherImportedModule.buildMeta.providedExports) + ) { + for (const exportName of otherImportedModule.buildMeta + .providedExports) { + result.add(exportName); + } + } + } + return result; + } + + getExports() { + if (this.name) { + return { + exports: [this.name], + dependencies: undefined + }; + } + + const importedModule = this._module; + + if (!importedModule) { + // no imported module available + return { + exports: null, + dependencies: undefined + }; + } + + if (Array.isArray(importedModule.buildMeta.providedExports)) { + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); + return { + exports: importedModule.buildMeta.providedExports.filter( + id => + id !== "default" && + !activeFromOtherStarExports.has(id) && + !this.activeExports.has(id) + ), + dependencies: [importedModule] + }; + } + + if (importedModule.buildMeta.providedExports) { + return { + exports: true, + dependencies: undefined + }; + } + + return { + exports: null, + dependencies: [importedModule] + }; + } + + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } + + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; + } + + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } + + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module + if ( + this.originModule.buildMeta.strictHarmonyModule && + this._id && + this._id !== "default" + ) { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't reexport the named export '${this._id}' from non EcmaScript module (only default export is available)` + ) + ]; + } + return; + } + + if (!this._id) { + return; + } + + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } + + // We are sure that it's not provided + const idIsNotNameMessage = + this._id !== this.name ? ` (reexported as '${this.name}')` : ""; + const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } + + updateHash(hash) { + super.updateHash(hash); + const hashValue = this.getHashValue(this._module); + hash.update(hashValue); + } + + getHashValue(importedModule) { + if (!importedModule) { + return ""; + } + + const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); + const stringifiedProvidedExport = JSON.stringify( + importedModule.buildMeta.providedExports + ); + return ( + importedModule.used + stringifiedUsedExport + stringifiedProvidedExport + ); + } + + disconnect() { + super.disconnect(); + this.redirectedId = undefined; + } +} + +module.exports = HarmonyExportImportedSpecifierDependency; + +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + harmonyInit(dep, source, runtime, dependencyTemplates) { + super.harmonyInit(dep, source, runtime, dependencyTemplates); + const content = this.getContent(dep); + source.insert(-1, content); + } + + getHarmonyInitOrder(dep) { + if (dep.name) { + const used = dep.originModule.isUsed(dep.name); + if (!used) return NaN; + } else { + const importedModule = dep._module; + + const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); + + if (Array.isArray(dep.originModule.usedExports)) { + // we know which exports are used + + const unused = dep.originModule.usedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (importedModule.isProvided(id) === false) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } else if ( + dep.originModule.usedExports && + importedModule && + Array.isArray(importedModule.buildMeta.providedExports) + ) { + // not sure which exports are used, but we know which are provided + + const unused = importedModule.buildMeta.providedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } + } + return super.getHarmonyInitOrder(dep); + } + + getContent(dep) { + const mode = dep.getMode(false); + const module = dep.originModule; + const importedModule = dep._module; + const importVar = dep.getImportVar(); + + switch (mode.type) { + case "missing": + return `throw new Error(${JSON.stringify( + `Cannot find module '${mode.userRequest}'` + )});\n`; + + case "unused": + return `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`; + + case "reexport-non-harmony-default": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + null + ) + ); + + case "reexport-named-default": + return ( + "/* harmony reexport (default from named exports) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "reexport-fake-namespace-object": + return ( + "/* harmony reexport (fake namespace object from non-harmony) */ " + + this.getReexportFakeNamespaceObjectStatement( + module, + module.isUsed(mode.name), + importVar + ) + ); + + case "rexport-non-harmony-undefined": + return ( + "/* harmony reexport (non default export from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + "undefined", + "" + ) + ); + + case "reexport-non-harmony-default-strict": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "reexport-namespace-object": + return ( + "/* harmony reexport (module object) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "empty-star": + return "/* empty/unused harmony star reexport */"; + + case "safe-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (safe) */ " + + this.getReexportStatement( + module, + module.isUsed(item[0]), + importVar, + importedModule.isUsed(item[1]) + ) + + "\n" + ); + }) + .join(""); + + case "checked-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (checked) */ " + + this.getConditionalReexportStatement( + module, + item[0], + importVar, + item[1] + ) + + "\n" + ); + }) + .join(""); + + case "dynamic-reexport": { + const ignoredExports = mode.ignored; + let content = + "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + + importVar + + ") "; + + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (ignoredExports.size > 0) { + content += + "if(" + + JSON.stringify(Array.from(ignoredExports)) + + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; + } else { + content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; + } + const exportsName = dep.originModule.exportsArgument; + return ( + content + + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${importVar}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n` + ); + } + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + getReexportStatement(module, key, name, valueKey) { + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; + } + + getReexportFakeNamespaceObjectStatement(module, key, name) { + const exportsName = module.exportsArgument; + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return __webpack_require__.t(${name}); });\n`; + } + + getConditionalReexportStatement(module, key, name, valueKey) { + if (valueKey === false) { + return "/* unused export */\n"; + } + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `if(__webpack_require__.o(${name}, ${JSON.stringify( + valueKey + )})) __webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; + } + + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } + if (valueKey === "") { + return name; + } + if (valueKey === false) { + return "/* unused export */ undefined"; + } + + return `${name}[${JSON.stringify(valueKey)}]`; + } +}; + + +/***/ }), + +/***/ 34834: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(originModule, id, name) { + super(); + this.originModule = originModule; + this.id = id; + this.name = name; + } + + get type() { + return "harmony export specifier"; + } + + getExports() { + return { + exports: [this.name], + dependencies: undefined + }; + } +} + +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { + apply(dep, source) {} + + getHarmonyInitOrder(dep) { + return 0; + } + + harmonyInit(dep, source, runtime) { + const content = this.getContent(dep); + source.insert(-1, content); + } + + getContent(dep) { + const used = dep.originModule.isUsed(dep.name); + if (!used) { + return `/* unused harmony export ${dep.name || "namespace"} */\n`; + } + + const exportsName = dep.originModule.exportsArgument; + + return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( + used + )}, function() { return ${dep.id}; });\n`; + } +}; + +module.exports = HarmonyExportSpecifierDependency; + + +/***/ }), + +/***/ 81599: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const Template = __webpack_require__(96066); + +class HarmonyImportDependency extends ModuleDependency { + constructor(request, originModule, sourceOrder, parserScope) { + super(request); + this.redirectedModule = undefined; + this.originModule = originModule; + this.sourceOrder = sourceOrder; + this.parserScope = parserScope; + } + + get _module() { + return this.redirectedModule || this.module; + } + + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + false, + this.weak, + this.sourceOrder + ); + } + + getImportVar() { + let importVarMap = this.parserScope.importVarMap; + if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map(); + let importVar = importVarMap.get(this._module); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set(this._module, importVar); + return importVar; + } + + getImportStatement(update, runtime) { + return runtime.importStatement({ + update, + module: this._module, + importVar: this.getImportVar(), + request: this.request, + originModule: this.originModule + }); + } + + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update((importedModule && importedModule.id) + ""); + } + + disconnect() { + super.disconnect(); + this.redirectedModule = undefined; + } +} + +module.exports = HarmonyImportDependency; + +const importEmittedMap = new WeakMap(); + +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { + apply(dep, source, runtime) { + // no-op + } + + getHarmonyInitOrder(dep) { + return dep.sourceOrder; + } + + static isImportEmitted(dep, source) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) return false; + const key = dep._module || dep.request; + return key && sourceInfo.emittedImports.get(key); + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) { + importEmittedMap.set( + source, + (sourceInfo = { + emittedImports: new Map() + }) + ); + } + const key = dep._module || dep.request; + if (key && sourceInfo.emittedImports.get(key)) return; + sourceInfo.emittedImports.set(key, true); + const content = dep.getImportStatement(false, runtime); + source.insert(-1, content); + } +}; + + +/***/ }), + +/***/ 99433: +/***/ ((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__(92402); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyAcceptImportDependency = __webpack_require__(66136); +const HarmonyAcceptDependency = __webpack_require__(75159); +const ConstDependency = __webpack_require__(71101); + +module.exports = class HarmonyImportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; + } + + apply(parser) { + parser.hooks.import.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = statement.loc; + parser.state.module.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = statement.loc; + parser.state.module.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.importSpecifier.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source, id, name) => { + parser.scope.definitions.delete(name); + parser.scope.renames.set(name, "imported var"); + if (!parser.state.harmonySpecifier) { + parser.state.harmonySpecifier = new Map(); + } + parser.state.harmonySpecifier.set(name, { + source, + id, + sourceOrder: parser.state.lastHarmonyImportOrder + }); + return true; + } + ); + parser.hooks.expression + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.expressionAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.property.name || expr.property.value, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + if (this.strictThisContextOnImports) { + // only in case when we strictly follow the spec we need a special case here + parser.hooks.callAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + if (expr.callee.type !== "MemberExpression") return; + if (expr.callee.object.type !== "Identifier") return; + const name = expr.callee.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.callee.property.name || expr.callee.property.value, + name, + expr.callee.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.namespaceObjectAsContext = true; + dep.loc = expr.callee.loc; + parser.state.module.addDependency(dep); + if (expr.arguments) parser.walkExpressions(expr.arguments); + return true; + }); + } + parser.hooks.call + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const args = expr.arguments; + const fullExpr = expr; + expr = expr.callee; + if (expr.type !== "Identifier") return; + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.directImport = true; + dep.callArgs = args; + dep.call = fullExpr; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + return true; + }); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.hotAcceptCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const harmonyParserScope = parser.state.harmonyParserScope; + if (!harmonyParserScope) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + true + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + parser.hooks.hotAcceptWithoutCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + parser.state.harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + false + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + } +}; + + +/***/ }), + +/***/ 79171: +/***/ ((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__(81599); + +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + constructor(request, originModule, sourceOrder, parserScope) { + super(request, originModule, sourceOrder, parserScope); + } + + getReference() { + if (this._module && this._module.factoryMeta.sideEffectFree) return null; + + return super.getReference(); + } + + get type() { + return "harmony side effect evaluation"; + } +} + +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { + getHarmonyInitOrder(dep) { + if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; + return super.getHarmonyInitOrder(dep); + } +}; + +module.exports = HarmonyImportSideEffectDependency; + + +/***/ }), + +/***/ 95966: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const HarmonyLinkingError = __webpack_require__(30327); + +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + range, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id === null ? null : `${id}`; + this.redirectedId = undefined; + this.name = name; + this.range = range; + this.strictExportPresence = strictExportPresence; + this.namespaceObjectAsContext = false; + this.callArgs = undefined; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; + } + + get type() { + return "harmony import specifier"; + } + + get _id() { + return this.redirectedId || this.id; + } + + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + this._id && !this.namespaceObjectAsContext ? [this._id] : true, + false, + this.sourceOrder + ); + } + + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } + + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; + } + + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } + + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module + if ( + this.originModule.buildMeta.strictHarmonyModule && + this._id && + this._id !== "default" + ) { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't import the named export '${this._id}' from non EcmaScript module (only default export is available)` + ) + ]; + } + return; + } + + if (!this._id) { + return; + } + + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } + + // We are sure that it's not provided + const idIsNotNameMessage = + this._id !== this.name ? ` (imported as '${this.name}')` : ""; + const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } + + // implement this method to allow the occurrence order plugin to count correctly + getNumberOfIdOccurrences() { + return 0; + } + + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update((importedModule && this._id) + ""); + hash.update( + (importedModule && this._id && importedModule.isUsed(this._id)) + "" + ); + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update( + (importedModule && + importedModule.used + JSON.stringify(importedModule.usedExports)) + "" + ); + } + + disconnect() { + super.disconnect(); + this.redirectedId = undefined; + } +} + +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) { + super.apply(dep, source, runtime); + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, runtime) { + const exportExpr = runtime.exportFromImport({ + module: dep._module, + request: dep.request, + exportName: dep._id, + originModule: dep.originModule, + asiSafe: dep.shorthand, + isCall: dep.call, + callContext: !dep.directImport, + importVar: dep.getImportVar() + }); + return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr; + } +}; + +module.exports = HarmonyImportSpecifierDependency; + + +/***/ }), + +/***/ 27204: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const NullDependency = __webpack_require__(5088); + +class HarmonyInitDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } + + get type() { + return "harmony init"; + } +} + +module.exports = HarmonyInitDependency; + +HarmonyInitDependency.Template = class HarmonyInitDependencyTemplate { + apply(dep, source, runtime, dependencyTemplates) { + const module = dep.originModule; + const list = []; + for (const dependency of module.dependencies) { + const template = dependencyTemplates.get(dependency.constructor); + if ( + template && + typeof template.harmonyInit === "function" && + typeof template.getHarmonyInitOrder === "function" + ) { + const order = template.getHarmonyInitOrder(dependency); + if (!isNaN(order)) { + list.push({ + order, + listOrder: list.length, + dependency, + template + }); + } + } + } + + list.sort((a, b) => { + const x = a.order - b.order; + if (x) return x; + return a.listOrder - b.listOrder; + }); + + for (const item of list) { + item.template.harmonyInit( + item.dependency, + source, + runtime, + dependencyTemplates + ); + } + } +}; + + +/***/ }), + +/***/ 66792: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const HarmonyInitDependency = __webpack_require__(27204); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyExportHeaderDependency = __webpack_require__(21320); +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyAcceptDependency = __webpack_require__(75159); +const HarmonyAcceptImportDependency = __webpack_require__(66136); + +const NullFactory = __webpack_require__(40438); + +const HarmonyDetectionParserPlugin = __webpack_require__(59310); +const HarmonyImportDependencyParserPlugin = __webpack_require__(99433); +const HarmonyExportDependencyParserPlugin = __webpack_require__(49180); +const HarmonyTopLevelThisParserPlugin = __webpack_require__(58215); + +class HarmonyModulesPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + HarmonyCompatibilityDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyInitDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyInitDependency, + new HarmonyInitDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportExpressionDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportSpecifierDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.harmony !== undefined && !parserOptions.harmony) + return; + + new HarmonyDetectionParserPlugin().apply(parser); + new HarmonyImportDependencyParserPlugin(this.options).apply(parser); + new HarmonyExportDependencyParserPlugin(this.options).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HarmonyModulesPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("HarmonyModulesPlugin", handler); + } + ); + } +} +module.exports = HarmonyModulesPlugin; + + +/***/ }), + +/***/ 58215: +/***/ ((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__(71101); + +class HarmonyTopLevelThisParserPlugin { + apply(parser) { + parser.hooks.expression + .for("this") + .tap("HarmonyTopLevelThisParserPlugin", node => { + if (!parser.scope.topLevelScope) return; + const module = parser.state.module; + const isHarmony = !!(module.buildMeta && module.buildMeta.exportsType); + if (isHarmony) { + const dep = new ConstDependency("undefined", node.range, false); + dep.loc = node.loc; + parser.state.current.addDependency(dep); + } + }); + } +} + +module.exports = HarmonyTopLevelThisParserPlugin; + + +/***/ }), + +/***/ 20417: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); + +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return `import() context ${this.options.mode}`; + } +} + +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = ImportContextDependency; + + +/***/ }), + +/***/ 38875: +/***/ ((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__(22814); +const ImportDependency = __webpack_require__(50883); + +module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { + // TODO webpack 5 reorganize arguments + constructor(request, range, groupOptions, module, loc, originModule) { + super(groupOptions, module, loc, request); + this.range = range; + const dep = new ImportDependency(request, originModule, this); + dep.loc = loc; + this.addDependency(dep); + } +}; + + +/***/ }), + +/***/ 50883: +/***/ ((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__(90865); + +class ImportDependency extends ModuleDependency { + constructor(request, originModule, block) { + super(request); + this.originModule = originModule; + this.block = block; + } + + get type() { + return "import()"; + } +} + +ImportDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + block: dep.block, + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import()" + }); + + source.replace(dep.block.range[0], dep.block.range[1] - 1, content); + } +}; + +module.exports = ImportDependency; + + +/***/ }), + +/***/ 25552: +/***/ ((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__(90865); + +class ImportEagerDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; + } + + get type() { + return "import() eager"; + } +} + +ImportEagerDependency.Template = class ImportEagerDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() eager" + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportEagerDependency; + + +/***/ }), + +/***/ 93382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ImportContextDependency = __webpack_require__(20417); +const ImportWeakDependency = __webpack_require__(86817); +const ImportDependenciesBlock = __webpack_require__(38875); +const ImportEagerDependency = __webpack_require__(25552); +const ContextDependencyHelpers = __webpack_require__(5594); +const UnsupportedFeatureWarning = __webpack_require__(99953); +const CommentCompilationWarning = __webpack_require__(51760); + +class ImportParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + parser.hooks.importCall.tap("ImportParserPlugin", expr => { + if (expr.arguments.length !== 1) { + throw new Error( + "Incorrect number of arguments provided to 'import(module: string) -> Promise'." + ); + } + + const param = parser.evaluateExpression(expr.arguments[0]); + + let chunkName = null; + let mode = "lazy"; + let include = null; + let exclude = null; + const groupOptions = {}; + + const { + options: importOptions, + errors: commentErrors + } = parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.warnings.push( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + parser.state.module, + comment.loc + ) + ); + } + } + + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + // Do not instrument `import()` if `webpackIgnore` is `true` + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) + ); + } else { + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, + expr.loc + ) + ); + } else { + mode = importOptions.webpackMode; + } + } + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + importOptions.webpackInclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + expr.loc + ) + ); + } else { + include = new RegExp(importOptions.webpackInclude); + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + importOptions.webpackExclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + expr.loc + ) + ); + } else { + exclude = new RegExp(importOptions.webpackExclude); + } + } + } + + if (param.isString()) { + if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + } + + if (mode === "eager") { + const dep = new ImportEagerDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new ImportDependenciesBlock( + param.string, + expr.range, + Object.assign(groupOptions, { + name: chunkName + }), + parser.state.module, + expr.loc, + parser.state.module + ); + parser.state.current.addBlock(depBlock); + } + return true; + } else { + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + mode = "lazy"; + } + + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + expr.range, + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: parser.state.module.buildMeta.strictHarmonyModule + ? "strict" + : true + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }); + } +} + +module.exports = ImportParserPlugin; + + +/***/ }), + +/***/ 58839: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ImportDependency = __webpack_require__(50883); +const ImportEagerDependency = __webpack_require__(25552); +const ImportWeakDependency = __webpack_require__(86817); +const ImportContextDependency = __webpack_require__(20417); +const ImportParserPlugin = __webpack_require__(93382); + +class ImportPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "ImportPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportDependency, + new ImportDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportEagerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportEagerDependency, + new ImportEagerDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportWeakDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportWeakDependency, + new ImportWeakDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportContextDependency, + new ImportContextDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.import !== undefined && !parserOptions.import) + return; + + new ImportParserPlugin(options).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportPlugin", handler); + } + ); + } +} +module.exports = ImportPlugin; + + +/***/ }), + +/***/ 86817: +/***/ ((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__(90865); + +class ImportWeakDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; + this.weak = true; + } + + get type() { + return "import() weak"; + } +} + +ImportWeakDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() weak", + weak: true + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportWeakDependency; + + +/***/ }), + +/***/ 54396: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class JsonExportsDependency extends NullDependency { + constructor(exports) { + super(); + this.exports = exports; + } + + get type() { + return "json exports"; + } + + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; + } +} + +module.exports = JsonExportsDependency; + + +/***/ }), + +/***/ 1129: +/***/ ((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__(90865); + +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } + + get type() { + return "loader"; + } +} + +module.exports = LoaderDependency; + + +/***/ }), + +/***/ 31559: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const LoaderDependency = __webpack_require__(1129); +const NormalModule = __webpack_require__(25963); + +/** @typedef {import("../Module")} Module */ + +/** + * @callback LoadModuleCallback + * @param {Error=} err error object + * @param {string=} source source code + * @param {object=} map source map + * @param {Module=} module loaded module if successful + */ + +class LoaderPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "LoaderPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.compilation.tap("LoaderPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderPlugin", + (loaderContext, module) => { + /** + * @param {string} request the request string to load the module from + * @param {LoadModuleCallback} callback callback returning the loaded module or error + * @returns {void} + */ + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + dep.constructor + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + compilation.semaphore.release(); + compilation.addModuleDependencies( + module, + [ + { + factory, + dependencies: [dep] + } + ], + true, + "lm", + true, + err => { + compilation.semaphore.acquire(() => { + if (err) { + return callback(err); + } + if (!dep.module) { + return callback(new Error("Cannot load the module")); + } + // TODO consider removing this in webpack 5 + if (dep.module instanceof NormalModule && dep.module.error) { + return callback(dep.module.error); + } + if (!dep.module._source) { + throw new Error( + "The module created for a LoaderDependency must have a property _source" + ); + } + let source, map; + const moduleSource = dep.module._source; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + if (dep.module.buildInfo.fileDependencies) { + for (const d of dep.module.buildInfo.fileDependencies) { + loaderContext.addDependency(d); + } + } + if (dep.module.buildInfo.contextDependencies) { + for (const d of dep.module.buildInfo.contextDependencies) { + loaderContext.addContextDependency(d); + } + } + return callback(null, source, map, dep.module); + }); + } + ); + }; + } + ); + }); + } +} +module.exports = LoaderPlugin; + + +/***/ }), + +/***/ 17356: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class LocalModule { + constructor(module, name, idx) { + this.module = module; + this.name = name; + this.idx = idx; + this.used = false; + } + + flagUsed() { + this.used = true; + } + + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } +} +module.exports = LocalModule; + + +/***/ }), + +/***/ 56570: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { + super(); + localModule.flagUsed(); + this.localModule = localModule; + this.range = range; + this.callNew = callNew; + } +} + +LocalModuleDependency.Template = class LocalModuleDependencyTemplate { + apply(dep, source) { + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); + } +}; + +module.exports = LocalModuleDependency; + + +/***/ }), + +/***/ 39658: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const LocalModule = __webpack_require__(17356); +const LocalModulesHelpers = exports; + +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + var path = parent.split("/"); + var segs = mod.split("/"); + path.pop(); + + for (let i = 0; i < segs.length; i++) { + const seg = segs[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); + } + } + + return path.join("/"); +}; + +LocalModulesHelpers.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; + } + const m = new LocalModule(state.module, name, state.localModules.length); + state.localModules.push(m); + return m; +}; + +LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; + } + } + return null; +}; + +module.exports = LocalModulesHelpers; + + +/***/ }), + +/***/ 90865: +/***/ ((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__(57282); + +class ModuleDependency extends Dependency { + /** + * @param {string} request request path which needs resolving + */ + constructor(request) { + super(); + this.request = request; + this.userRequest = request; + } + + getResourceIdentifier() { + return `module${this.request}`; + } +} + +module.exports = ModuleDependency; + + +/***/ }), + +/***/ 63708: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ModuleDependencyTemplateAsId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleId({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsId; + + +/***/ }), + +/***/ 60441: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ModuleDependencyTemplateAsRequireId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsRequireId; + + +/***/ }), + +/***/ 29018: +/***/ ((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__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); + +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.accept"; + } +} + +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotAcceptDependency; + + +/***/ }), + +/***/ 60482: +/***/ ((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__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); + +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.decline"; + } +} + +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotDeclineDependency; + + +/***/ }), + +/***/ 7791: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ +const Dependency = __webpack_require__(57282); + +class MultiEntryDependency extends Dependency { + /** + * @param {SingleEntryDependency[]} dependencies an array of SingleEntryDependencies + * @param {string} name entry name + */ + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } + + get type() { + return "multi entry"; + } +} + +module.exports = MultiEntryDependency; + + +/***/ }), + +/***/ 5088: +/***/ ((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__(57282); + +class NullDependency extends Dependency { + get type() { + return "null"; + } + + updateHash() {} +} + +NullDependency.Template = class NullDependencyTemplate { + apply() {} +}; + +module.exports = NullDependency; + + +/***/ }), + +/***/ 14237: +/***/ ((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__(90865); + +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "prefetch"; + } +} + +module.exports = PrefetchDependency; + + +/***/ }), + +/***/ 79142: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ContextDependency = __webpack_require__(11583); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); + +class RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); + this.range = range; + } + + get type() { + return "require.context"; + } +} + +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = RequireContextDependency; + + +/***/ }), + +/***/ 10566: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireContextDependency = __webpack_require__(79142); + +module.exports = class RequireContextDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.context") + .tap("RequireContextDependencyParserPlugin", expr => { + let regExp = /^\.\/.*$/; + let recursive = true; + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = modeExpr.string; + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: requestExpr.string, + recursive, + regExp, + mode + }, + expr.range + ); + dep.loc = expr.loc; + dep.optional = parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + }); + } +}; + + +/***/ }), + +/***/ 89042: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireContextDependency = __webpack_require__(79142); +const ContextElementDependency = __webpack_require__(89079); + +const RequireContextDependencyParserPlugin = __webpack_require__(10566); + +class RequireContextPlugin { + constructor(modulesDirectories, extensions, mainFiles) { + if (!Array.isArray(modulesDirectories)) { + throw new Error("modulesDirectories must be an array"); + } + if (!Array.isArray(extensions)) { + throw new Error("extensions must be an array"); + } + this.modulesDirectories = modulesDirectories; + this.extensions = extensions; + this.mainFiles = mainFiles; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) + return; + + new RequireContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.extensions + .filter(ext => { + const l = obj.request.length; + return ( + l > ext.length && + obj.request.substr(l - ext.length, l) === ext + ); + }) + .map(ext => { + const l = obj.request.length; + return { + context: obj.context, + request: obj.request.substr(0, l - ext.length) + }; + }) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } + ); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.mainFiles + .filter(mainFile => { + const l = obj.request.length; + return ( + l > mainFile.length + 1 && + obj.request.substr(l - mainFile.length - 1, l) === + "/" + mainFile + ); + }) + .map(mainFile => { + const l = obj.request.length; + return [ + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length) + }, + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length - 1) + } + ]; + }) + .reduce((a, b) => a.concat(b), []) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } + ); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items.map(obj => { + for (let i = 0; i < this.modulesDirectories.length; i++) { + const dir = this.modulesDirectories[i]; + const idx = obj.request.indexOf("./" + dir + "/"); + if (idx === 0) { + obj.request = obj.request.slice(dir.length + 3); + break; + } + } + return obj; + }); + } + ); + } + ); + } +} +module.exports = RequireContextPlugin; + + +/***/ }), + +/***/ 49105: +/***/ ((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__(22814); +const RequireEnsureDependency = __webpack_require__(75830); + +module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + successExpression, + errorExpression, + chunkName, + chunkNameRange, + module, + loc + ) { + super(chunkName, module, loc, null); + this.expr = expr; + const successBodyRange = + successExpression && + successExpression.body && + successExpression.body.range; + if (successBodyRange) { + this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1]; + } + this.chunkNameRange = chunkNameRange; + const dep = new RequireEnsureDependency(this); + dep.loc = loc; + this.addDependency(dep); + } +}; + + +/***/ }), + +/***/ 24620: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireEnsureDependenciesBlock = __webpack_require__(49105); +const RequireEnsureItemDependency = __webpack_require__(5511); +const getFunctionExpression = __webpack_require__(64197); + +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.ensure") + .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { + let chunkName = null; + let chunkNameRange = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); + + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression( + expr.arguments[2] + ); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression( + expr.arguments[0] + ); + const dependenciesItems = dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr]; + const successExpressionArg = expr.arguments[1]; + const successExpression = getFunctionExpression( + successExpressionArg + ); + + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } + + const dep = new RequireEnsureDependenciesBlock( + expr, + successExpression ? successExpression.fn : successExpressionArg, + errorExpression ? errorExpression.fn : errorExpressionArg, + chunkName, + chunkNameRange, + parser.state.module, + expr.loc + ); + const old = parser.state.current; + parser.state.current = dep; + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const edep = new RequireEnsureItemDependency(ee.string); + edep.loc = dep.loc; + dep.addDependency(edep); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(dep); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } + } + }); + } +}; + + +/***/ }), + +/***/ 75830: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class RequireEnsureDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } + + get type() { + return "require.ensure"; + } +} + +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "require.ensure" + }); + const errorCallbackExists = + depBlock.expr.arguments.length === 4 || + (!depBlock.chunkName && depBlock.expr.arguments.length === 3); + const startBlock = `${promise}.then((`; + const middleBlock = ").bind(null, __webpack_require__)).catch("; + const endBlock = `).bind(null, __webpack_require__)).catch(${runtime.onError()})`; + source.replace( + depBlock.expr.range[0], + depBlock.expr.arguments[1].range[0] - 1, + startBlock + ); + if (errorCallbackExists) { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.arguments[2].range[0] - 1, + middleBlock + ); + source.replace( + depBlock.expr.arguments[2].range[1], + depBlock.expr.range[1] - 1, + ")" + ); + } else { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.range[1] - 1, + endBlock + ); + } + } +}; + +module.exports = RequireEnsureDependency; + + +/***/ }), + +/***/ 5511: +/***/ ((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__(90865); +const NullDependency = __webpack_require__(5088); + +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "require.ensure item"; + } +} + +RequireEnsureItemDependency.Template = NullDependency.Template; + +module.exports = RequireEnsureItemDependency; + + +/***/ }), + +/***/ 98655: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireEnsureItemDependency = __webpack_require__(5511); +const RequireEnsureDependency = __webpack_require__(75830); + +const NullFactory = __webpack_require__(40438); + +const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(24620); + +const ParserHelpers = __webpack_require__(23999); + +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireEnsureDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) + return; + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireEnsurePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireEnsurePlugin", handler); + } + ); + } +} +module.exports = RequireEnsurePlugin; + + +/***/ }), + +/***/ 22928: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class RequireHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } +} + +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); + } + + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "require"); + } +}; + +module.exports = RequireHeaderDependency; + + +/***/ }), + +/***/ 58045: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const Template = __webpack_require__(96066); + +class RequireIncludeDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + getReference() { + if (!this.module) return null; + // This doesn't use any export + return new DependencyReference(this.module, [], false); + } + + get type() { + return "require.include"; + } +} + +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { + apply(dep, source, runtime) { + const comment = runtime.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtime.requestShortener.shorten(dep.request)}` + ) + : ""; + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + } +}; + +module.exports = RequireIncludeDependency; + + +/***/ }), + +/***/ 36330: +/***/ ((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__(58045); + +module.exports = class RequireIncludeDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.include") + .tap("RequireIncludeDependencyParserPlugin", expr => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + const dep = new RequireIncludeDependency(param.string, expr.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + } +}; + + +/***/ }), + +/***/ 16522: +/***/ ((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__(58045); +const RequireIncludeDependencyParserPlugin = __webpack_require__(36330); + +const ParserHelpers = __webpack_require__(23999); + +class RequireIncludePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireIncludePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireIncludeDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireInclude !== undefined && + !parserOptions.requireInclude + ) + return; + + new RequireIncludeDependencyParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireIncludePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireIncludePlugin", handler); + } + ); + } +} +module.exports = RequireIncludePlugin; + + +/***/ }), + +/***/ 83309: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsId = __webpack_require__(6174); + +class RequireResolveContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } +} + +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; + +module.exports = RequireResolveContextDependency; + + +/***/ }), + +/***/ 43519: +/***/ ((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__(90865); +const ModuleDependencyAsId = __webpack_require__(63708); + +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "require.resolve"; + } +} + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; + + +/***/ }), + +/***/ 68349: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireResolveDependency = __webpack_require__(43519); +const RequireResolveContextDependency = __webpack_require__(83309); +const RequireResolveHeaderDependency = __webpack_require__(69647); +const ContextDependencyHelpers = __webpack_require__(5594); + +class RequireResolveDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + const options = this.options; + + const process = (expr, weak) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of param.options) { + const result = processItem(expr, option, weak); + if (result === undefined) { + processContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } else { + const result = processItem(expr, param, weak); + if (result === undefined) { + processContext(expr, param, weak); + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } + }; + const processItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + param.range, + param, + expr, + options, + { + mode: weak ? "weak" : "sync" + }, + 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 process(expr, false); + }); + parser.hooks.call + .for("require.resolveWeak") + .tap("RequireResolveDependencyParserPlugin", expr => { + return process(expr, true); + }); + } +} +module.exports = RequireResolveDependencyParserPlugin; + + +/***/ }), + +/***/ 69647: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class RequireResolveHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } +} + +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } + + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } +}; + +module.exports = RequireResolveHeaderDependency; + + +/***/ }), + +/***/ 84828: +/***/ ((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__(90865); + +class SingleEntryDependency extends ModuleDependency { + /** + * @param {string} request request path for entry + */ + constructor(request) { + super(request); + } + + get type() { + return "single entry"; + } +} + +module.exports = SingleEntryDependency; + + +/***/ }), + +/***/ 68166: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ParserHelpers = __webpack_require__(23999); +const WebpackError = __webpack_require__(97391); + +class SystemPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "SystemPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.system !== undefined && !parserOptions.system) + return; + + const shouldWarn = parserOptions.system === undefined; + + const setNotSupported = name => { + parser.hooks.evaluateTypeof + .for(name) + .tap("SystemPlugin", ParserHelpers.evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + "SystemPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + name + " is not supported by webpack." + ) + ); + }; + + parser.hooks.typeof + .for("System.import") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("System.import") + .tap("SystemPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") + ) + ); + parser.hooks.evaluateTypeof + .for("System") + .tap("SystemPlugin", ParserHelpers.evaluateToString("object")); + + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); + + parser.hooks.expression.for("System").tap("SystemPlugin", () => { + const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + __webpack_require__.ab + "system.js" + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "System", + systemPolyfillRequire + ); + }); + + parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { + if (shouldWarn) { + parser.state.module.warnings.push( + new SystemImportDeprecationWarning( + parser.state.module, + expr.loc + ) + ); + } + + return parser.hooks.importCall.call(expr); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("SystemPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("SystemPlugin", handler); + } + ); + } +} + +class SystemImportDeprecationWarning extends WebpackError { + constructor(module, loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "SystemImportDeprecationWarning"; + + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = SystemPlugin; + + +/***/ }), + +/***/ 15826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); +const webpackMissingModule = __webpack_require__(75386).module; + +class UnsupportedDependency extends NullDependency { + constructor(request, range) { + super(); + this.request = request; + this.range = range; + } +} + +UnsupportedDependency.Template = class UnsupportedDependencyTemplate { + apply(dep, source, runtime) { + source.replace( + dep.range[0], + dep.range[1], + webpackMissingModule(dep.request) + ); + } +}; + +module.exports = UnsupportedDependency; + + +/***/ }), + +/***/ 18925: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); + +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; + } + + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, [this.name], false); + } + + get type() { + return "wasm export import"; + } +} + +module.exports = WebAssemblyExportImportedDependency; + + +/***/ }), + +/***/ 52959: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); + +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ + +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; + } + + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, [this.name], false); + } + + getErrors() { + if ( + this.onlyDirectImport && + this.module && + !this.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` + ) + ]; + } + } + + get type() { + return "wasm import"; + } +} + +module.exports = WebAssemblyImportDependency; + + +/***/ }), + +/***/ 75386: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const toErrorCode = err => + `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; + +exports.module = request => + `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; + +exports.promise = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; +}; + +exports.moduleCode = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `${errorCode} throw e;`; +}; + + +/***/ }), + +/***/ 64197: +/***/ ((module) => { + +/* + 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 + }; + } +}; + + +/***/ }), + +/***/ 49: +/***/ ((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 */ + +// TODO webpack 5: pos must be SourcePosition +/** + * @param {SourcePosition|DependencyLocation|string} pos position + * @returns {string} formatted position + */ +const formatPosition = pos => { + if (pos === null) return ""; + // TODO webpack 5: Simplify this + if (typeof pos === "string") return pos; + if (typeof pos === "number") return `${pos}`; + if (typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; + } else if ("index" in pos) { + // TODO webpack 5 remove this case + return `+${pos.index}`; + } else { + return ""; + } + } + return ""; +}; + +// TODO webpack 5: loc must be DependencyLocation +/** + * @param {DependencyLocation|SourcePosition|string} loc location + * @returns {string} formatted location + */ +const formatLocation = loc => { + if (loc === null) return ""; + // TODO webpack 5: Simplify this + if (typeof loc === "string") return loc; + if (typeof loc === "number") return `${loc}`; + if (typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else { + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } + } + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; + } + return formatPosition(loc); + } + return ""; +}; + +module.exports = formatLocation; + + +/***/ }), + +/***/ 47194: +/***/ ((__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"); + +class WebpackLogger { + /** + * @param {function(LogTypeEnum, any[]=): void} log log function + */ + constructor(log) { + this[LOG_SYMBOL] = log; + } + + 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]); + } +} + +exports.Logger = WebpackLogger; + + +/***/ }), + +/***/ 88838: +/***/ ((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__(47194); + +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ + +/** @typedef {function(string): boolean} FilterFunction */ + +/** + * @typedef {Object} LoggerOptions + * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel + * @property {FilterTypes|boolean} debug filter for debug logging + * @property {Console & { status?: Function, logTime?: Function }} console the console to log to + */ + +/** + * @param {FilterItemTypes} item an input item + * @returns {FilterFunction} filter funtion + */ +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; +}; + + +/***/ }), + +/***/ 62299: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + + +/** + * @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 < lengths.reduce((s, i) => s + Math.min(i, 6), 0)) { + // remove args + if (args.length > 1) + return truncateArgs(args.slice(0, args.length - 1), maxLength); + return []; + } + + let currentLength = lengths.reduce((a, b) => a + b, 0); + + // 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; + + +/***/ }), + +/***/ 45249: +/***/ ((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__(53665); + +class NodeChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "NodeChunkTemplatePlugin", + (modules, chunk) => { + const source = new ConcatSource(); + source.add( + `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = ` + ); + source.add(modules); + source.add(";"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { + hash.update("node"); + hash.update("3"); + }); + } +} + +module.exports = NodeChunkTemplatePlugin; + + +/***/ }), + +/***/ 52520: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const NodeWatchFileSystem = __webpack_require__(71610); +const NodeOutputFileSystem = __webpack_require__(31836); +const NodeJsInputFileSystem = __webpack_require__(13445); +const CachedInputFileSystem = __webpack_require__(75544); +const createConsoleLogger = __webpack_require__(88838); +const nodeConsole = __webpack_require__(7886); + +class NodeEnvironmentPlugin { + constructor(options) { + this.options = options || {}; + } + + apply(compiler) { + compiler.infrastructureLogger = createConsoleLogger( + Object.assign( + { + level: "info", + debug: false, + console: nodeConsole + }, + this.options.infrastructureLogging + ) + ); + compiler.inputFileSystem = new CachedInputFileSystem( + new NodeJsInputFileSystem(), + 60000 + ); + const inputFileSystem = compiler.inputFileSystem; + compiler.outputFileSystem = new NodeOutputFileSystem(); + compiler.watchFileSystem = new NodeWatchFileSystem( + compiler.inputFileSystem + ); + compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { + if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); + }); + } +} +module.exports = NodeEnvironmentPlugin; + + +/***/ }), + +/***/ 95909: +/***/ ((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__(53665); + +class NodeHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "NodeHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const source = new ConcatSource(); + source.add( + "exports.id = " + JSON.stringify(id) + ";\nexports.modules = " + ); + source.add(modulesSource); + source.add(";"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "NodeHotUpdateChunkTemplatePlugin", + hash => { + hash.update("NodeHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.library + ""); + } + ); + } +} +module.exports = NodeHotUpdateChunkTemplatePlugin; + + +/***/ }), + +/***/ 33514: +/***/ ((module) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var $hotChunkFilename$ = undefined; +var hotAddUpdateChunk = undefined; +var installedChunks = undefined; +var $hotMainFilename$ = undefined; + +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var chunk = require("./" + $hotChunkFilename$); + hotAddUpdateChunk(chunk.id, chunk.modules); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + try { + var update = require("./" + $hotMainFilename$); + } catch (e) { + return Promise.resolve(); + } + return Promise.resolve(update); + } + + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; + + +/***/ }), + +/***/ 51433: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var $hotChunkFilename$ = undefined; +var $require$ = undefined; +var hotAddUpdateChunk = undefined; +var $hotMainFilename$ = undefined; +var installedChunks = undefined; + +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var filename = __webpack_require__(85622).join(__dirname, $hotChunkFilename$); + __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { + if (err) { + if ($require$.onError) return $require$.oe(err); + throw err; + } + var chunk = {}; + __webpack_require__(92184).runInThisContext( + "(function(exports) {" + content + "\n})", + { filename: filename } + )(chunk); + hotAddUpdateChunk(chunk.id, chunk.modules); + }); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + var filename = __webpack_require__(85622).join(__dirname, $hotMainFilename$); + return new Promise(function(resolve, reject) { + __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { + if (err) return resolve(); + try { + var update = JSON.parse(content); + } catch (e) { + return reject(e); + } + resolve(update); + }); + }); + } + + // eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; + + +/***/ }), + +/***/ 78597: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); + +module.exports = class NodeMainTemplatePlugin { + constructor(asyncChunkLoading) { + this.asyncChunkLoading = asyncChunkLoading; + } + + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + const asyncChunkLoading = this.asyncChunkLoading; + mainTemplate.hooks.localVars.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "0" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireExtensions.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// uncaught error handler for webpack runtime", + `${mainTemplate.requireFn}.oe = function(err) {`, + Template.indent([ + "process.nextTick(function() {", + Template.indent( + "throw err; // catch this error by using import().catch()" + ), + "});" + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + const insertMoreModules = [ + "var moreModules = chunk.modules, chunkIds = chunk.ids;", + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}" + ]; + if (asyncChunkLoading) { + return Template.asString([ + source, + "", + "// ReadFile + VM.run chunk loading for javascript", + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + "var filename = require('path').join(__dirname, " + + mainTemplate.getAssetPath( + JSON.stringify(`/${chunkFilename}`), + { + hash: `" + ${mainTemplate.renderCurrentHashCode( + hash + )} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify( + chunkMaps.hash + )}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = + chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + } + ) + + ");", + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent( + [ + "if(err) return reject(err);", + "var chunk = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(chunk, require, require('path').dirname(filename), filename);" + ] + .concat(insertMoreModules) + .concat([ + "var callbacks = [];", + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]])", + Template.indent([ + "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" + ]), + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + "for(i = 0; i < callbacks.length; i++)", + Template.indent("callbacks[i]();") + ]) + ), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + "}" + ]), + "}" + ]); + } else { + const request = mainTemplate.getAssetPath( + JSON.stringify(`./${chunkFilename}`), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + } + ); + return Template.asString([ + source, + "", + "// require() chunk loading for javascript", + "", + '// "0" is the signal for "already loaded"', + "if(installedChunks[chunkId] !== 0) {", + Template.indent( + [`var chunk = require(${request});`] + .concat(insertMoreModules) + .concat([ + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 0;") + ]) + ), + "}" + ]); + } + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const chunkMaps = chunk.getChunkMaps(); + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + return Template.getFunctionContent( + asyncChunkLoading + ? __webpack_require__(51433) + : __webpack_require__(33514) + ) + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); + } + ); + mainTemplate.hooks.hash.tap("NodeMainTemplatePlugin", hash => { + hash.update("node"); + hash.update("4"); + }); + } +}; + + +/***/ }), + +/***/ 31836: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const mkdirp = __webpack_require__(94327); + +class NodeOutputFileSystem { + constructor() { + this.mkdirp = mkdirp; + this.mkdir = fs.mkdir.bind(fs); + this.rmdir = fs.rmdir.bind(fs); + this.unlink = fs.unlink.bind(fs); + this.writeFile = fs.writeFile.bind(fs); + this.join = path.join.bind(path); + } +} + +module.exports = NodeOutputFileSystem; + + +/***/ }), + +/***/ 9128: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const AliasPlugin = __webpack_require__(15005); +const ParserHelpers = __webpack_require__(23999); +const nodeLibsBrowser = __webpack_require__(5884); + +module.exports = class NodeSourcePlugin { + constructor(options) { + this.options = options; + } + apply(compiler) { + const options = this.options; + if (options === false) { + // allow single kill switch to turn off this plugin + return; + } + + const getPathToModule = (module, type) => { + if (type === true || (type === undefined && nodeLibsBrowser[module])) { + if (!nodeLibsBrowser[module]) { + throw new Error( + `No browser version for node.js core module ${module} available` + ); + } + return nodeLibsBrowser[module]; + } else if (type === "mock") { + return require.resolve(`node-libs-browser/mock/${module}`); + } else if (type === "empty") { + return __webpack_require__.ab + "empty.js"; + } else { + return module; + } + }; + + const addExpression = (parser, name, module, type, suffix) => { + suffix = suffix || ""; + parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { + if ( + parser.state.module && + parser.state.module.resource === getPathToModule(module, type) + ) + return; + const mockModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + getPathToModule(module, type) + ); + return ParserHelpers.addParsedVariableToModule( + parser, + name, + mockModule + suffix + ); + }); + }; + + compiler.hooks.compilation.tap( + "NodeSourcePlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; + + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } + if (localOptions.global) { + parser.hooks.expression + .for("global") + .tap("NodeSourcePlugin", () => { + const retrieveGlobalModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + __webpack_require__.ab + "global.js" + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "global", + retrieveGlobalModule + ); + }); + } + if (localOptions.process) { + const processType = localOptions.process; + addExpression(parser, "process", "process", processType); + } + if (localOptions.console) { + const consoleType = localOptions.console; + addExpression(parser, "console", "console", consoleType); + } + const bufferType = localOptions.Buffer; + if (bufferType) { + addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); + } + if (localOptions.setImmediate) { + const setImmediateType = localOptions.setImmediate; + addExpression( + parser, + "setImmediate", + "timers", + setImmediateType, + ".setImmediate" + ); + addExpression( + parser, + "clearImmediate", + "timers", + setImmediateType, + ".clearImmediate" + ); + } + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeSourcePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeSourcePlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { + for (const lib of Object.keys(nodeLibsBrowser)) { + if (options[lib] !== false) { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("NodeSourcePlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: lib, + onlyModule: true, + alias: getPathToModule(lib, options[lib]) + }, + "resolve" + ).apply(resolver); + }); + } + } + }); + } +}; + + +/***/ }), + +/***/ 59743: +/***/ ((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__(75705); + +const builtins = + // eslint-disable-next-line node/no-unsupported-features/node-builtins,node/no-deprecated-api + __webpack_require__(32282).builtinModules || Object.keys(process.binding("natives")); + +class NodeTargetPlugin { + apply(compiler) { + new ExternalsPlugin("commonjs", builtins).apply(compiler); + } +} + +module.exports = NodeTargetPlugin; + + +/***/ }), + +/***/ 90010: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const NodeMainTemplatePlugin = __webpack_require__(78597); +const NodeChunkTemplatePlugin = __webpack_require__(45249); +const NodeHotUpdateChunkTemplatePlugin = __webpack_require__(95909); + +class NodeTemplatePlugin { + constructor(options) { + options = options || {}; + this.asyncChunkLoading = options.asyncChunkLoading; + } + + apply(compiler) { + compiler.hooks.thisCompilation.tap("NodeTemplatePlugin", compilation => { + new NodeMainTemplatePlugin(this.asyncChunkLoading).apply( + compilation.mainTemplate + ); + new NodeChunkTemplatePlugin().apply(compilation.chunkTemplate); + new NodeHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + }); + } +} + +module.exports = NodeTemplatePlugin; + + +/***/ }), + +/***/ 71610: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Watchpack = __webpack_require__(77056); +const objectToMap = __webpack_require__(1111); + +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); + } + + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + if (!Array.isArray(files)) { + throw new Error("Invalid arguments: 'files'"); + } + if (!Array.isArray(dirs)) { + throw new Error("Invalid arguments: 'dirs'"); + } + if (!Array.isArray(missing)) { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); + + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + const cachedFiles = files; + const cachedDirs = dirs; + this.watcher.once("aggregated", (changes, removals) => { + changes = changes.concat(removals); + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(changes); + } + const times = objectToMap(this.watcher.getTimes()); + files = new Set(files); + dirs = new Set(dirs); + missing = new Set(missing); + removals = new Set(removals.filter(file => files.has(file))); + callback( + null, + changes.filter(file => files.has(file)).sort(), + changes.filter(file => dirs.has(file)).sort(), + changes.filter(file => missing.has(file)).sort(), + times, + times, + removals + ); + }); + + this.watcher.watch( + cachedFiles.concat(missing), + cachedDirs.concat(missing), + startTime + ); + + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getFileTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + }, + getContextTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + } + }; + } +} + +module.exports = NodeWatchFileSystem; + + +/***/ }), + +/***/ 73839: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); +const WasmMainTemplatePlugin = __webpack_require__(65331); + +class ReadFileCompileWasmTemplatePlugin { + constructor(options) { + this.options = options || {}; + } + + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileWasmTemplatePlugin", + compilation => { + 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 Promise.resolve(buffer); }" + ]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + const plugin = new WasmMainTemplatePlugin( + Object.assign( + { + generateLoadBinaryCode, + supportsStreaming: false + }, + this.options + ) + ); + plugin.apply(compilation.mainTemplate); + } + ); + } +} + +module.exports = ReadFileCompileWasmTemplatePlugin; + + +/***/ }), + +/***/ 7886: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const truncateArgs = __webpack_require__(62299); +const util = __webpack_require__(31669); + +const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; + +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 (tty) { + 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) { + process.stderr.write("\x1b[2K\r"); + hasStatusMessage = false; + } +}; + +const writeStatusMessage = () => { + if (!currentStatusMessage) return; + const l = process.stderr.columns; + const args = l + ? truncateArgs(currentStatusMessage, l - 1) + : currentStatusMessage; + const str = args.join(" "); + const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; + process.stderr.write(`\x1b[2K\r${coloredStr}`); + hasStatusMessage = true; +}; + +const writeColored = (prefix, colorPrefix, colorSuffix) => { + return (...args) => { + if (currentCollapsed > 0) return; + clearStatusMessage(); + // @ts-ignore + const str = indent(util.format(...args), prefix, colorPrefix, colorSuffix); + process.stderr.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" +); + +module.exports = { + 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: + tty && + // 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: tty + ? (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(); + } + } + : writeColored(" ", "", "") +}; + + +/***/ }), + +/***/ 88197: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class AggressiveMergingPlugin { + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; + } + + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; + + compiler.hooks.thisCompilation.tap( + "AggressiveMergingPlugin", + compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveMergingPlugin", + chunks => { + let combinations = []; + chunks.forEach((a, idx) => { + if (a.canBeInitial()) return; + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + if (b.canBeInitial()) continue; + combinations.push({ + a, + b, + improvement: undefined + }); + } + }); + + for (const pair of combinations) { + const a = pair.b.size({ + chunkOverhead: 0 + }); + const b = pair.a.size({ + chunkOverhead: 0 + }); + const ab = pair.b.integratedSize(pair.a, { + chunkOverhead: 0 + }); + let newSize; + if (ab === false) { + pair.improvement = false; + return; + } else { + newSize = ab; + } + + pair.improvement = (a + b) / newSize; + } + combinations = combinations.filter(pair => { + return pair.improvement !== false; + }); + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); + + const pair = combinations[0]; + + if (!pair) return; + if (pair.improvement < minSizeReduce) return; + + if (pair.b.integrate(pair.a, "aggressive-merge")) { + chunks.splice(chunks.indexOf(pair.a), 1); + return true; + } + } + ); + } + ); + } +} + +module.exports = AggressiveMergingPlugin; + + +/***/ }), + +/***/ 26688: +/***/ ((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__(94658); +const { intersect } = __webpack_require__(54262); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(71884); + +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ + +const moveModuleBetween = (oldChunk, newChunk) => { + return module => { + oldChunk.moveModule(module, newChunk); + }; +}; + +const isNotAEntryModule = entryModule => { + return module => { + return entryModule !== module; + }; +}; + +class AggressiveSplittingPlugin { + /** + * @param {AggressiveSplittingPluginOptions=} options options object + */ + constructor(options) { + if (!options) options = {}; + + validateOptions(schema, options, "Aggressive Splitting Plugin"); + + this.options = options; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } + } + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "AggressiveSplittingPlugin", + compilation => { + let needAdditionalSeal = false; + let newSplits; + let fromAggressiveSplittingSet; + let chunkSplitDataMap; + compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveSplittingPlugin", + chunks => { + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + for (const m of compilation.modules) { + const name = identifierUtils.makePathsRelative( + compiler.context, + m.identifier(), + compilation.cache + ); + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); + } + + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } + + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; + + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; + + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) + ); + + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; + + // Check if size matches (faster than waiting for hash) + const size = selectedModules.reduce( + (sum, m) => sum + m.size(), + 0 + ); + if (size !== splitData.size) return false; + + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map(m => new Set(m.chunksIterable)) + ); + + // No relevant chunks found + if (selectedChunks.size === 0) return false; + + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + Array.from(selectedChunks)[0].getNumberOfModules() === + selectedModules.length + ) { + const chunk = Array.from(selectedChunks)[0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } + + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + selectedModules.forEach(moveModuleBetween(chunk, newChunk)); + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); + + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + } + return true; + }; + + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; + } + + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const sortedChunks = chunks.slice().sort((a, b) => { + const diff1 = b.modulesSize() - a.modulesSize(); + if (diff1) return diff1; + const diff2 = a.getNumberOfModules() - b.getNumberOfModules(); + if (diff2) return diff2; + const modulesA = Array.from(a.modulesIterable); + const modulesB = Array.from(b.modulesIterable); + modulesA.sort(); + modulesB.sort(); + const aI = modulesA[Symbol.iterator](); + const bI = modulesB[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) return 0; + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier > bModuleIdentifier) return -1; + if (aModuleIdentifier < bModuleIdentifier) return 1; + } + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunk.modulesSize(); + if (size > maxSize && chunk.getNumberOfModules() > 1) { + const modules = chunk + .getModules() + .filter(isNotAEntryModule(chunk.entryModule)) + .sort((a, b) => { + a = a.identifier(); + b = b.identifier(); + if (a > b) return 1; + if (a < b) return -1; + return 0; + }); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + const splitData = { + modules: selectedModules + .map(m => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; + + if (applySplit(splitData)) { + newSplits = (newSplits || []).concat(splitData); + changed = true; + } + } + } + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap( + "AggressiveSplittingPlugin", + records => { + // 4. save made splittings to records + const allSplits = new Set(); + const invalidSplits = new Set(); + + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + if (splitData.hash && chunk.hash !== splitData.hash) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } + } + + if (invalidSplits.size > 0) { + records.aggressiveSplits = records.aggressiveSplits.filter( + splitData => !invalidSplits.has(splitData) + ); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = chunk.hash; + splitData.id = chunk.id; + allSplits.add(splitData); + // set flag for stats + chunk.recorded = true; + } + } + + // Also add all unused historial splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } + } + + // record all splits + records.aggressiveSplits = Array.from(allSplits); + + needAdditionalSeal = false; + } + } + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); + } + ); + } +} +module.exports = AggressiveSplittingPlugin; + + +/***/ }), + +/***/ 30346: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const sortByIndex = (a, b) => { + return a.index - b.index; +}; + +const sortByIndex2 = (a, b) => { + return a.index2 - b.index2; +}; + +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { + compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { + const chunk = compilation.chunks.find( + chunk => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` + ); + } + + let chunkModules; + if (options.order) { + chunkModules = Array.from(chunk.modulesIterable); + switch (options.order) { + case "index": + chunkModules.sort(sortByIndex); + break; + case "index2": + chunkModules.sort(sortByIndex2); + break; + default: + throw new Error( + "ChunkModuleIdRangePlugin: unexpected value of order" + ); + } + } else { + chunkModules = modules.filter(m => { + return m.chunksIterable.has(chunk); + }); + } + + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.id === null) { + m.id = currentId++; + } + if (options.end && currentId > options.end) break; + } + }); + }); + } +} +module.exports = ChunkModuleIdRangePlugin; + + +/***/ }), + +/***/ 16953: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Module = __webpack_require__(75993); +const Template = __webpack_require__(96066); +const Parser = __webpack_require__(70558); +const eslintScope = __webpack_require__(41632); +const { ConcatSource, ReplaceSource } = __webpack_require__(53665); +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const createHash = __webpack_require__(15660); + +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../util/createHash").Hash} Hash */ +/** @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; +}; + +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + */ + +const ensureNsObjSource = ( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule +) => { + if (!info.hasNamespaceObject) { + info.hasNamespaceObject = true; + const name = info.exportMap.get(true); + const nsObj = [`var ${name} = {};`, `__webpack_require__.r(${name});`]; + for (const exportName of info.module.buildMeta.providedExports) { + const finalName = getFinalName( + info, + exportName, + moduleToInfoMap, + requestShortener, + false, + strictHarmonyModule + ); + nsObj.push( + `__webpack_require__.d(${name}, ${JSON.stringify( + exportName + )}, function() { return ${finalName}; });` + ); + } + info.namespaceObjectSource = nsObj.join("\n") + "\n"; + } +}; + +const getExternalImport = ( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule +) => { + const used = importedModule.isUsed(exportName); + if (!used) return "/* unused reexport */undefined"; + const comment = + used !== exportName ? ` ${Template.toNormalComment(exportName)}` : ""; + switch (importedModule.buildMeta.exportsType) { + case "named": + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + break; + } + case "namespace": + if (exportName === true) { + return info.name; + } else { + break; + } + default: + if (strictHarmonyModule) { + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + return "/* non-default import from non-esm module */undefined"; + } + } else { + if (exportName === "default") { + info.interopDefaultAccessUsed = true; + return asCall + ? `${info.interopDefaultAccessName}()` + : `${info.interopDefaultAccessName}.a`; + } else if (exportName === true) { + return info.name; + } else { + break; + } + } + } + const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; + if (asCall) return `Object(${reference})`; + return reference; +}; + +const getFinalName = ( + info, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited = new Set() +) => { + switch (info.type) { + case "concatenated": { + const directExport = info.exportMap.get(exportName); + if (directExport) { + if (exportName === true) { + ensureNsObjSource( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule + ); + } else if (!info.module.isUsed(exportName)) { + return "/* unused export */ undefined"; + } + if (info.globalExports.has(directExport)) { + return directExport; + } + const name = info.internalNames.get(directExport); + if (!name) { + throw new Error( + `The export "${directExport}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name` + ); + } + return name; + } + const reexport = info.reexportMap.get(exportName); + if (reexport) { + if (alreadyVisited.has(reexport)) { + throw new Error( + `Circular reexports ${Array.from( + alreadyVisited, + e => + `"${e.module.readableIdentifier(requestShortener)}".${ + e.exportName + }` + ).join( + " --> " + )} -(circular)-> "${reexport.module.readableIdentifier( + requestShortener + )}".${reexport.exportName}` + ); + } + alreadyVisited.add(reexport); + const refInfo = moduleToInfoMap.get(reexport.module); + if (refInfo) { + // module is in the concatenation + return getFinalName( + refInfo, + reexport.exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited + ); + } + } + const problem = + `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( + requestShortener + )}"` + + ` (known exports: ${Array.from(info.exportMap.keys()) + .filter(name => name !== true) + .join(" ")}, ` + + `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; + return `${Template.toNormalComment(problem)} undefined`; + } + case "external": { + const importedModule = info.module; + return getExternalImport( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule + ); + } + } +}; + +const addScopeSymbols1 = (s, nameSet, scopeSet) => { + let scope = s; + while (scope) { + if (scopeSet.has(scope)) break; + scopeSet.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const addScopeSymbols2 = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const getAllReferences = variable => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some(id => identifiers.has(id))) { + set = set.concat(innerVar.references); + break; + } + } + } + return set; +}; + +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } + + const nr = node.range; + + const enterNode = n => { + if (!n) return undefined; + const r = n.range; + if (r) { + if (r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } + } + return undefined; + }; + + var i; + if (Array.isArray(ast)) { + for (i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = Object.keys(ast); + for (i = 0; i < keys.length; i++) { + const value = ast[keys[i]]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } + } +}; + +const getHarmonyExportImportedSpecifierDependencyExports = dep => { + const importModule = dep._module; + if (!importModule) return []; + if (dep._id) { + // export { named } from "module" + return [ + { + name: dep.name, + id: dep._id, + module: importModule + } + ]; + } + if (dep.name) { + // export * as abc from "module" + return [ + { + name: dep.name, + id: true, + module: importModule + } + ]; + } + // export * from "module" + return importModule.buildMeta.providedExports + .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) + .map(exp => { + return { + name: exp, + id: exp, + module: importModule + }; + }); +}; + +class ConcatenatedModule extends Module { + constructor(rootModule, modules, concatenationList) { + super("javascript/esm", null); + super.setChunks(rootModule._chunks); + + // Info from Factory + this.rootModule = rootModule; + this.factoryMeta = rootModule.factoryMeta; + + // Info from Compilation + this.index = rootModule.index; + this.index2 = rootModule.index2; + this.depth = rootModule.depth; + + // Info from Optimization + this.used = rootModule.used; + this.usedExports = rootModule.usedExports; + + // Info from Build + this.buildInfo = { + strict: true, + cacheable: modules.every(m => m.buildInfo.cacheable), + moduleArgument: rootModule.buildInfo.moduleArgument, + exportsArgument: rootModule.buildInfo.exportsArgument, + fileDependencies: new Set(), + contextDependencies: new Set(), + assets: undefined + }; + this.built = modules.some(m => m.built); + this.buildMeta = rootModule.buildMeta; + + // Caching + this._numberOfConcatenatedModules = modules.length; + + // Graph + const modulesSet = new Set(modules); + this.reasons = rootModule.reasons.filter( + reason => + !(reason.dependency instanceof HarmonyImportDependency) || + !modulesSet.has(reason.module) + ); + + this.dependencies = []; + this.blocks = []; + + this.warnings = []; + this.errors = []; + this._orderedConcatenationList = + concatenationList || + ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null); + for (const info of this._orderedConcatenationList) { + if (info.type === "concatenated") { + const m = info.module; + + // populate dependencies + for (const d of m.dependencies.filter( + dep => + !(dep instanceof HarmonyImportDependency) || + !modulesSet.has(dep._module) + )) { + this.dependencies.push(d); + } + // populate blocks + for (const d of m.blocks) { + this.blocks.push(d); + } + // populate file dependencies + if (m.buildInfo.fileDependencies) { + for (const file of m.buildInfo.fileDependencies) { + this.buildInfo.fileDependencies.add(file); + } + } + // populate context dependencies + if (m.buildInfo.contextDependencies) { + for (const context of m.buildInfo.contextDependencies) { + this.buildInfo.contextDependencies.add(context); + } + } + // populate warnings + for (const warning of m.warnings) { + this.warnings.push(warning); + } + // populate errors + for (const error of m.errors) { + this.errors.push(error); + } + + if (m.buildInfo.assets) { + if (this.buildInfo.assets === undefined) { + this.buildInfo.assets = Object.create(null); + } + Object.assign(this.buildInfo.assets, m.buildInfo.assets); + } + 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); + } + } + } + } + this._identifier = this._createIdentifier(); + } + + get modules() { + return this._orderedConcatenationList + .filter(info => info.type === "concatenated") + .map(info => info.module); + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._numberOfConcatenatedModules - 1} modules` + ); + } + + libIdent(options) { + return this.rootModule.libIdent(options); + } + + nameForCondition() { + return this.rootModule.nameForCondition(); + } + + build(options, compilation, resolver, fs, callback) { + throw new Error("Cannot build this module. It should be already built."); + } + + size() { + // Guess size from embedded modules + return this._orderedConcatenationList.reduce((sum, info) => { + switch (info.type) { + case "concatenated": + return sum + info.module.size(); + case "external": + return sum + 5; + } + return sum; + }, 0); + } + + /** + * @param {Module} rootModule the root of the concatenation + * @param {Set} modulesSet a set of modules which should be concatenated + * @param {Compilation} compilation the compilation context + * @returns {ConcatenationEntry[]} concatenation list + */ + static createConcatenationList(rootModule, modulesSet, compilation) { + const list = []; + const set = new Set(); + + /** + * @param {Module} module a module + * @returns {(function(): Module)[]} imported modules in order + */ + const getConcatenatedImports = module => { + /** @type {WeakMap} */ + const map = new WeakMap(); + const references = module.dependencies + .filter(dep => dep instanceof HarmonyImportDependency) + .map(dep => { + const ref = compilation.getDependencyReference(module, dep); + if (ref) map.set(ref, dep); + return ref; + }) + .filter(ref => ref); + DependencyReference.sort(references); + // TODO webpack 5: remove this hack, see also DependencyReference + return references.map(ref => { + const dep = map.get(ref); + return () => compilation.getDependencyReference(module, dep).module; + }); + }; + + const enterModule = getModule => { + const module = getModule(); + if (!module) return; + if (set.has(module)) return; + set.add(module); + if (modulesSet.has(module)) { + const imports = getConcatenatedImports(module); + imports.forEach(enterModule); + list.push({ + type: "concatenated", + module + }); + } else { + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return getModule(); + } + }); + } + }; + + enterModule(() => rootModule); + + return list; + } + + _createIdentifier() { + let orderedConcatenationListIdentifiers = ""; + for (let i = 0; i < this._orderedConcatenationList.length; i++) { + if (this._orderedConcatenationList[i].type === "concatenated") { + orderedConcatenationListIdentifiers += this._orderedConcatenationList[ + i + ].module.identifier(); + orderedConcatenationListIdentifiers += " "; + } + } + const hash = createHash("md4"); + hash.update(orderedConcatenationListIdentifiers); + return this.rootModule.identifier() + " " + hash.digest("hex"); + } + + source(dependencyTemplates, runtimeTemplate) { + const requestShortener = runtimeTemplate.requestShortener; + // Metainfo for each module + const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => { + switch (info.type) { + case "concatenated": { + const exportMap = new Map(); + const reexportMap = new Map(); + for (const dep of info.module.dependencies) { + if (dep instanceof HarmonyExportSpecifierDependency) { + if (!exportMap.has(dep.name)) { + exportMap.set(dep.name, dep.id); + } + } else if (dep instanceof HarmonyExportExpressionDependency) { + if (!exportMap.has("default")) { + exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); + } + } else if ( + dep instanceof HarmonyExportImportedSpecifierDependency + ) { + const exportName = dep.name; + const importName = dep._id; + const importedModule = dep._module; + if (exportName && importName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: importName, + dependency: dep + }); + } + } else if (exportName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: true, + dependency: dep + }); + } + } else if (importedModule) { + for (const name of importedModule.buildMeta.providedExports) { + if (dep.activeExports.has(name) || name === "default") { + continue; + } + if (!reexportMap.has(name)) { + reexportMap.set(name, { + module: importedModule, + exportName: name, + dependency: dep + }); + } + } + } + } + } + return { + type: "concatenated", + module: info.module, + index: idx, + ast: undefined, + internalSource: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + globalExports: new Set(), + exportMap: exportMap, + reexportMap: reexportMap, + hasNamespaceObject: false, + namespaceObjectSource: null + }; + } + case "external": + return { + type: "external", + module: info.module, + index: idx, + name: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + }); + + // Create mapping from module to info + const moduleToInfoMap = new Map(); + for (const m of modulesWithInfo) { + moduleToInfoMap.set(m.module, m); + } + + // Configure template decorators for dependencies + const innerDependencyTemplates = new Map(dependencyTemplates); + + innerDependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSpecifierDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSideEffectDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyExportSpecifierDependency, + new NullTemplate() + ); + innerDependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyExportExpressionDependency), + this.rootModule + ) + ); + innerDependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new NullTemplate() + ); + innerDependencyTemplates.set( + HarmonyCompatibilityDependency, + new NullTemplate() + ); + + // Must use full identifier in our cache here to ensure that the source + // is updated should our dependencies list change. + // TODO webpack 5 refactor + innerDependencyTemplates.set( + "hash", + innerDependencyTemplates.get("hash") + this.identifier() + ); + + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const m = info.module; + const source = m.source(innerDependencyTemplates, runtimeTemplate); + const code = source.source(); + let ast; + try { + ast = Parser.parse(code, { + sourceType: "module" + }); + } catch (err) { + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += + "\n| " + + lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| "); + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = scopeManager.acquire(ast); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + } + } + + // List of all used names to avoid conflicts + const allUsedNames = new Set([ + "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name + + "abstract", + "arguments", + "async", + "await", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "let", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with", + "yield", + + "module", + "__dirname", + "__filename", + "exports", + + "Array", + "Date", + "eval", + "function", + "hasOwnProperty", + "Infinity", + "isFinite", + "isNaN", + "isPrototypeOf", + "length", + "Math", + "NaN", + "name", + "Number", + "Object", + "prototype", + "String", + "toString", + "undefined", + "valueOf", + + "alert", + "all", + "anchor", + "anchors", + "area", + "assign", + "blur", + "button", + "checkbox", + "clearInterval", + "clearTimeout", + "clientInformation", + "close", + "closed", + "confirm", + "constructor", + "crypto", + "decodeURI", + "decodeURIComponent", + "defaultStatus", + "document", + "element", + "elements", + "embed", + "embeds", + "encodeURI", + "encodeURIComponent", + "escape", + "event", + "fileUpload", + "focus", + "form", + "forms", + "frame", + "innerHeight", + "innerWidth", + "layer", + "layers", + "link", + "location", + "mimeTypes", + "navigate", + "navigator", + "frames", + "frameRate", + "hidden", + "history", + "image", + "images", + "offscreenBuffering", + "open", + "opener", + "option", + "outerHeight", + "outerWidth", + "packages", + "pageXOffset", + "pageYOffset", + "parent", + "parseFloat", + "parseInt", + "password", + "pkcs11", + "plugin", + "prompt", + "propertyIsEnum", + "radio", + "reset", + "screenX", + "screenY", + "scroll", + "secure", + "select", + "self", + "setInterval", + "setTimeout", + "status", + "submit", + "taint", + "text", + "textarea", + "top", + "unescape", + "untaint", + "window", + + "onblur", + "onclick", + "onerror", + "onfocus", + "onkeydown", + "onkeypress", + "onkeyup", + "onmouseover", + "onload", + "onmouseup", + "onmousedown", + "onsubmit" + ]); + + // Set of already checked scopes + const alreadyCheckedScopes = new Set(); + + // get all global names + for (const info of modulesWithInfo) { + const superClassExpressions = []; + + // ignore symbols from moduleScope + if (info.moduleScope) { + alreadyCheckedScopes.add(info.moduleScope); + + // The super class expression in class scopes behaves weird + // We store ranges of all super class expressions to make + // renaming to work correctly + for (const childScope of info.moduleScope.childScopes) { + if (childScope.type !== "class") continue; + if (!childScope.block.superClass) continue; + superClassExpressions.push({ + range: childScope.block.superClass.range, + variables: childScope.variables + }); + } + } + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if ( + /^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?(_strict)?__$/.test( + name + ) + ) { + for (const expr of superClassExpressions) { + if ( + expr.range[0] <= reference.identifier.range[0] && + expr.range[1] >= reference.identifier.range[1] + ) { + for (const variable of expr.variables) { + allUsedNames.add(variable.name); + } + } + } + addScopeSymbols1( + reference.from, + allUsedNames, + alreadyCheckedScopes + ); + } else { + allUsedNames.add(name); + } + } + } + + // add exported globals + if (info.type === "concatenated") { + const variables = new Set(); + for (const variable of info.moduleScope.variables) { + variables.add(variable.name); + } + for (const [, variable] of info.exportMap) { + if (!variables.has(variable)) { + info.globalExports.add(variable); + } + } + } + } + + // generate names for symbols + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": { + const namespaceObjectName = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); + info.internalNames.set(namespaceObjectName, namespaceObjectName); + info.exportMap.set(true, namespaceObjectName); + for (const variable of info.moduleScope.variables) { + const name = variable.name; + if (allUsedNames.has(name)) { + const references = getAllReferences(variable); + const symbolsInReferences = new Set(); + const alreadyCheckedInnerScopes = new Set(); + for (const ref of references) { + addScopeSymbols2( + ref.from, + symbolsInReferences, + alreadyCheckedInnerScopes, + alreadyCheckedScopes + ); + } + const newName = this.findNewName( + name, + allUsedNames, + symbolsInReferences, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + const source = info.source; + const allIdentifiers = new Set( + references.map(r => r.identifier).concat(variable.identifiers) + ); + for (const identifier of allIdentifiers) { + const r = identifier.range; + const path = getPathInAst(info.ast, identifier); + if ( + path && + path.length > 1 && + path[1].type === "Property" && + path[1].shorthand + ) { + source.insert(r[1], `: ${newName}`); + } else { + source.replace(r[0], r[1] - 1, newName); + } + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); + } + } + break; + } + case "external": { + const externalName = this.findNewName( + "", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + if ( + info.module.buildMeta.exportsType === "named" || + !info.module.buildMeta.exportsType + ) { + const externalNameInterop = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; + } + if (!info.module.buildMeta.exportsType) { + const externalNameInterop = this.findNewName( + "default", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; + } + break; + } + } + } + + // Find and replace referenced to modules + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_strict)?__$/.exec( + name + ); + if (match) { + const referencedModule = modulesWithInfo[+match[1]]; + let exportName; + if (match[2] === "ns") { + exportName = true; + } else { + const exportData = match[2]; + exportName = Buffer.from(exportData, "hex").toString("utf-8"); + } + const asCall = !!match[3]; + const strictHarmonyModule = !!match[4]; + const finalName = getFinalName( + referencedModule, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule + ); + const r = reference.identifier.range; + const source = info.source; + source.replace(r[0], r[1] - 1, finalName); + } + } + } + } + + // 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(); + + for (const dep of this.rootModule.dependencies) { + if (dep instanceof HarmonyExportSpecifierDependency) { + const used = this.rootModule.isUsed(dep.name); + if (used) { + const info = moduleToInfoMap.get(this.rootModule); + if (!exportsMap.has(used)) { + exportsMap.set( + used, + () => `/* binding */ ${info.internalNames.get(dep.id)}` + ); + } + } else { + unusedExports.add(dep.name || "namespace"); + } + } else if (dep instanceof HarmonyExportImportedSpecifierDependency) { + const exportDefs = getHarmonyExportImportedSpecifierDependencyExports( + dep + ); + for (const def of exportDefs) { + const info = moduleToInfoMap.get(def.module); + const used = dep.originModule.isUsed(def.name); + if (used) { + if (!exportsMap.has(used)) { + exportsMap.set(used, requestShortener => { + const finalName = getFinalName( + info, + def.id, + moduleToInfoMap, + requestShortener, + false, + this.rootModule.buildMeta.strictHarmonyModule + ); + return `/* reexport */ ${finalName}`; + }); + } + } else { + unusedExports.add(def.name); + } + } + } + } + + const result = new ConcatSource(); + + // add harmony compatibility flag (must be first because of possible circular dependencies) + const usedExports = this.rootModule.usedExports; + if (usedExports === true || usedExports === null) { + result.add(`// ESM COMPAT FLAG\n`); + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument + }) + ); + } + + // define exports + if (exportsMap.size > 0) { + result.add(`\n// EXPORTS\n`); + for (const [key, value] of exportsMap) { + result.add( + `__webpack_require__.d(${this.exportsArgument}, ${JSON.stringify( + key + )}, function() { return ${value(requestShortener)}; });\n` + ); + } + } + + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } + + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.namespaceObjectSource) { + result.add( + `\n// NAMESPACE OBJECT: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.namespaceObjectSource); + } + } + + // evaluate modules in order + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": + result.add( + `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.source); + break; + case "external": + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add( + `var ${info.name} = __webpack_require__(${JSON.stringify( + info.module.id + )});\n` + ); + if (info.interopNamespaceObjectUsed) { + if (info.module.buildMeta.exportsType === "named") { + result.add( + `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name}, 2);\n` + ); + } else if (!info.module.buildMeta.exportsType) { + result.add( + `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name});\n` + ); + } + } + if (info.interopDefaultAccessUsed) { + result.add( + `var ${info.interopDefaultAccessName} = /*#__PURE__*/__webpack_require__.n(${info.name});\n` + ); + } + break; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + } + + return result; + } + + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; + + if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; + + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? "_" + name : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) + return nameIdent; + } + + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + (usedNamed2 && usedNamed2.has(nameWithNumber)) + ) { + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); + } + return nameWithNumber; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + for (const info of this._orderedConcatenationList) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash); + break; + case "external": + hash.update(`${info.module.id}`); + break; + } + } + super.updateHash(hash); + } +} + +class HarmonyImportSpecifierDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtimeTemplate, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } + let content; + const callFlag = dep.call ? "_call" : ""; + const strictFlag = dep.originModule.buildMeta.strictHarmonyModule + ? "_strict" + : ""; + if (dep._id === null) { + content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`; + } else if (dep.namespaceObjectAsContext) { + content = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`; + } else { + const exportData = Buffer.from(dep._id, "utf-8").toString("hex"); + content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${strictFlag}__`; + } + if (dep.shorthand) { + content = dep.name + ": " + content; + } + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} + +class HarmonyImportSideEffectDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtime, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } + } +} + +class HarmonyExportExpressionDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + } + + apply(dep, source, runtime, dependencyTemplates) { + let content = + "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = "; + if (dep.originModule === this.rootModule) { + const used = dep.originModule.isUsed("default"); + const exportsName = dep.originModule.exportsArgument; + if (used) content += `${exportsName}[${JSON.stringify(used)}] = `; + } + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } + + source.replace( + dep.rangeStatement[0], + dep.rangeStatement[1] - 1, + content + dep.prefix + ); + } +} + +class NullTemplate { + apply() {} +} + +module.exports = ConcatenatedModule; + + +/***/ }), + +/***/ 29720: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const GraphHelpers = __webpack_require__(32973); + +class EnsureChunkConditionsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "EnsureChunkConditionsPlugin", + compilation => { + const handler = chunks => { + let changed = false; + for (const module of compilation.modules) { + if (!module.chunkCondition) continue; + const sourceChunks = new Set(); + const chunkGroups = new Set(); + for (const chunk of module.chunksIterable) { + if (!module.chunkCondition(chunk)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + "Cannot fullfil chunk condition of " + module.identifier() + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + GraphHelpers.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + GraphHelpers.connectChunkAndModule(targetChunk, module); + } + } + if (changed) return true; + }; + compilation.hooks.optimizeChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler + ); + } + ); + } +} +module.exports = EnsureChunkConditionsPlugin; + + +/***/ }), + +/***/ 25850: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class FlagIncludedChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { + compilation.hooks.optimizeChunkIds.tap( + "FlagIncludedChunksPlugin", + chunks => { + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.length; + + // precalculate the modulo values for each bit + const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); + const modulos = Array.from( + { length: 31 }, + (x, i) => Math.pow(modulo, i) | 0 + ); + + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + + // interate all chunks to generate bitmaps + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunk.modulesIterable) { + hash |= moduleBits.get(module); + } + chunkModulesHash.set(chunk, hash); + } + + for (const chunkA of chunks) { + const chunkAHash = chunkModulesHash.get(chunkA); + const chunkAModulesCount = chunkA.getNumberOfModules(); + if (chunkAModulesCount === 0) continue; + let bestModule = undefined; + for (const module of chunkA.modulesIterable) { + if ( + bestModule === undefined || + bestModule.getNumberOfChunks() > module.getNumberOfChunks() + ) + bestModule = module; + } + loopB: for (const chunkB of bestModule.chunksIterable) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; + + const chunkBModulesCount = chunkB.getNumberOfModules(); + + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; + + // is chunkA in chunkB? + + // we do a cheap check for the hash value + const chunkBHash = chunkModulesHash.get(chunkB); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + + // compare all modules + for (const m of chunkA.modulesIterable) { + if (!chunkB.containsModule(m)) continue loopB; + } + chunkB.ids.push(chunkA.id); + } + } + } + ); + }); + } +} +module.exports = FlagIncludedChunksPlugin; + + +/***/ }), + +/***/ 3846: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(27993); +const LazyBucketSortedSet = __webpack_require__(52315); + +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @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) { + if (!options) options = {}; + + validateOptions(schema, options, "Limit Chunk Count Plugin"); + 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.optimizeChunksAdvanced.tap( + "LimitChunkCountPlugin", + chunks => { + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (chunks.length <= maxChunks) return; + + let remainingChunksToMerge = chunks.length - maxChunks; + + // order chunks in a deterministic way + const orderedChunks = chunks.slice().sort((a, b) => a.compareTo(b)); + + // 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 mappng 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]; + const integratedSize = a.integratedSize(b, options); + + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + if (integratedSize === false) continue; + + const aSize = a.size(options); + const bSize = b.size(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 + // futher 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 (a.integrate(b, "limit")) { + chunks.splice(chunks.indexOf(b), 1); + + // 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(b)) { + 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(a)) { + if (combination.deleted) continue; + if (combination.a === a) { + // Update size + const newIntegratedSize = a.integratedSize( + combination.b, + options + ); + if (newIntegratedSize === false) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + const finishUpdate = combinations.startUpdate(combination); + combination.integratedSize = newIntegratedSize; + combination.aSize = integratedSize; + combination.sizeDiff = + combination.bSize + integratedSize - newIntegratedSize; + finishUpdate(); + } else if (combination.b === a) { + // Update size + const newIntegratedSize = combination.a.integratedSize( + a, + options + ); + if (newIntegratedSize === false) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + const finishUpdate = combinations.startUpdate(combination); + combination.integratedSize = newIntegratedSize; + combination.bSize = integratedSize; + combination.sizeDiff = + integratedSize + combination.aSize - newIntegratedSize; + finishUpdate(); + } + } + } + } + if (changed) return true; + } + ); + }); + } +} +module.exports = LimitChunkCountPlugin; + + +/***/ }), + +/***/ 46214: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class MergeDuplicateChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "MergeDuplicateChunksPlugin", + compilation => { + compilation.hooks.optimizeChunksBasic.tap( + "MergeDuplicateChunksPlugin", + chunks => { + // remember already tested chunks for performance + const notDuplicates = new Set(); + + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunk.modulesIterable) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of module.chunksIterable) { + if ( + dup !== chunk && + chunk.getNumberOfModules() === dup.getNumberOfModules() && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!dup.containsModule(module)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } + + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + // merge them + if (chunk.integrate(otherChunk, "duplicate")) { + chunks.splice(chunks.indexOf(otherChunk), 1); + } + } + } + + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + } + ); + } +} +module.exports = MergeDuplicateChunksPlugin; + + +/***/ }), + +/***/ 55607: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(8670); + +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ + +class MinChunkSizePlugin { + /** + * @param {MinChunkSizePluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options, "Min Chunk Size Plugin"); + this.options = options; + } + + apply(compiler) { + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "MinChunkSizePlugin", + chunks => { + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; + + const sortedSizeFilteredExtendedPairCombinations = chunks + .reduce((combinations, a, idx) => { + // create combination pairs + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + combinations.push([b, a]); + } + return combinations; + }, []) + .filter(pair => { + // check if one of the chunks sizes is smaller than the minChunkSize + const p0SmallerThanMinChunkSize = + pair[0].size(equalOptions) < minChunkSize; + const p1SmallerThanMinChunkSize = + pair[1].size(equalOptions) < minChunkSize; + return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; + }) + .map(pair => { + // extend combination pairs with size and integrated size + const a = pair[0].size(options); + const b = pair[1].size(options); + const ab = pair[0].integratedSize(pair[1], options); + return [a + b - ab, ab, pair[0], pair[1]]; + }) + .filter(pair => { + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + return pair[1] !== false; + }) + .sort((a, b) => { + // sadly javascript does an inplace sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + pair[2].integrate(pair[3], "min-size"); + chunks.splice(chunks.indexOf(pair[3]), 1); + return true; + } + ); + }); + } +} +module.exports = MinChunkSizePlugin; + + +/***/ }), + +/***/ 25472: +/***/ ((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__(97391); +const SizeFormatHelpers = __webpack_require__(12496); + +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 optimiziation.splitChunks configuration." + ); + } +} + +module.exports = MinMaxSizeWarning; + + +/***/ }), + +/***/ 45184: +/***/ ((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__(81599); +const ModuleHotAcceptDependency = __webpack_require__(29018); +const ModuleHotDeclineDependency = __webpack_require__(60482); +const ConcatenatedModule = __webpack_require__(16953); +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const StackedSetMap = __webpack_require__(92251); + +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; +}; + +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "ModuleConcatenationPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { + // Because of variable renaming we can't use modules with eval. + parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ModuleConcatenationPlugin", handler); + + const bailoutReasonMap = new Map(); + + const setBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + module.optimizationBailout.push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; + + const getBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; + + compilation.hooks.optimizeChunkModules.tap( + "ModuleConcatenationPlugin", + (allChunks, modules) => { + const relevantModules = []; + const possibleInners = new Set(); + for (const module of modules) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + !module.dependencies.some( + d => d instanceof HarmonyCompatibilityDependency + ) + ) { + setBailoutReason(module, "Module is not an ECMAScript module"); + continue; + } + + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if ( + module.buildMeta && + module.buildMeta.moduleConcatenationBailout + ) { + setBailoutReason( + module, + `Module uses ${module.buildMeta.moduleConcatenationBailout}` + ); + continue; + } + + // Exports must be known (and not dynamic) + if (!Array.isArray(module.buildMeta.providedExports)) { + setBailoutReason(module, "Module exports are unknown"); + continue; + } + + // Using dependency variables is not possible as this wraps the code in a function + if (module.variables.length > 0) { + setBailoutReason( + module, + `Module uses injected variables (${module.variables + .map(v => v.name) + .join(", ")})` + ); + continue; + } + + // Hot Module Replacement need it's own module to work correctly + if ( + module.dependencies.some( + dep => + dep instanceof ModuleHotAcceptDependency || + dep instanceof ModuleHotDeclineDependency + ) + ) { + setBailoutReason(module, "Module uses Hot Module Replacement"); + continue; + } + + relevantModules.push(module); + + // Module must not be the entry points + if (module.isEntryModule()) { + setBailoutReason(module, "Module is an entry point"); + continue; + } + + // Module must be in any chunk (we don't want to do useless work) + if (module.getNumberOfChunks() === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; + } + + // Module must only be used by Harmony Imports + const nonHarmonyReasons = module.reasons.filter( + reason => + !reason.dependency || + !(reason.dependency instanceof HarmonyImportDependency) + ); + if (nonHarmonyReasons.length > 0) { + const importingModules = new Set( + nonHarmonyReasons.map(r => r.module).filter(Boolean) + ); + const importingExplanations = new Set( + nonHarmonyReasons.map(r => r.explanation).filter(Boolean) + ); + const importingModuleTypes = new Map( + Array.from(importingModules).map( + m => /** @type {[string, Set]} */ ([ + m, + new Set( + nonHarmonyReasons + .filter(r => r.module === m) + .map(r => r.dependency.type) + .sort() + ) + ]) + ) + ); + setBailoutReason(module, requestShortener => { + const names = Array.from(importingModules) + .map( + m => + `${m.readableIdentifier( + requestShortener + )} (referenced with ${Array.from( + importingModuleTypes.get(m) + ).join(", ")})` + ) + .sort(); + const explanations = Array.from(importingExplanations).sort(); + if (names.length > 0 && explanations.length === 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + } else if (names.length === 0 && explanations.length > 0) { + return `Module is referenced by: ${explanations.join( + ", " + )}`; + } else if (names.length > 0 && explanations.length > 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )} and by: ${explanations.join(", ")}`; + } else { + return "Module is referenced in a unsupported way"; + } + }); + continue; + } + + possibleInners.add(module); + } + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + relevantModules.sort((a, b) => { + return a.depth - b.depth; + }); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + if (usedAsInner.has(currentRoot)) continue; + + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration(currentRoot); + + // cache failures to add modules + const failureCache = new Map(); + + // try to add all imports + for (const imp of this._getImports(compilation, currentRoot)) { + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + possibleInners, + failureCache + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } + } + if (!currentConfiguration.isEmpty()) { + concatConfigurations.push(currentConfiguration); + for (const module of currentConfiguration.getModules()) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } + } + // HACK: Sort configurations by length and start with the longest one + // to get the biggers groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + concatConfigurations.sort((a, b) => { + return b.modules.size - a.modules.size; + }); + const usedModules = new Set(); + for (const concatConfiguration of concatConfigurations) { + if (usedModules.has(concatConfiguration.rootModule)) continue; + const modules = concatConfiguration.getModules(); + const rootModule = concatConfiguration.rootModule; + const newModule = new ConcatenatedModule( + rootModule, + Array.from(modules), + ConcatenatedModule.createConcatenationList( + rootModule, + modules, + compilation + ) + ); + for (const warning of concatConfiguration.getWarningsSorted()) { + newModule.optimizationBailout.push(requestShortener => { + const reason = getBailoutReason(warning[0], requestShortener); + const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; + if (warning[0] === warning[1]) { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } else { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )} because of ${warning[1].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + }); + } + const chunks = concatConfiguration.rootModule.getChunks(); + for (const m of modules) { + usedModules.add(m); + for (const chunk of chunks) { + chunk.removeModule(m); + } + } + for (const chunk of chunks) { + chunk.addModule(newModule); + newModule.addChunk(chunk); + } + for (const chunk of allChunks) { + if (chunk.entryModule === concatConfiguration.rootModule) { + chunk.entryModule = newModule; + } + } + compilation.modules.push(newModule); + for (const reason of newModule.reasons) { + if (reason.dependency.module === concatConfiguration.rootModule) + reason.dependency.module = newModule; + if ( + reason.dependency.redirectedModule === + concatConfiguration.rootModule + ) + reason.dependency.redirectedModule = newModule; + } + // TODO: remove when LTS node version contains fixed v8 version + // @see https://github.com/webpack/webpack/pull/6613 + // Turbofan does not correctly inline for-of loops with polymorphic input arrays. + // Work around issue by using a standard for loop and assigning dep.module.reasons + for (let i = 0; i < newModule.dependencies.length; i++) { + let dep = newModule.dependencies[i]; + if (dep.module) { + let reasons = dep.module.reasons; + for (let j = 0; j < reasons.length; j++) { + let reason = reasons[j]; + if (reason.dependency === dep) { + reason.module = newModule; + } + } + } + } + } + compilation.modules = compilation.modules.filter( + m => !usedModules.has(m) + ); + } + ); + } + ); + } + + _getImports(compilation, module) { + return new Set( + module.dependencies + + // Get reference info only for harmony Dependencies + .map(dep => { + if (!(dep instanceof HarmonyImportDependency)) return null; + if (!compilation) return dep.getReference(); + return compilation.getDependencyReference(module, dep); + }) + + // Reference is valid and has a module + // Dependencies are simple enough to concat them + .filter( + ref => + ref && + ref.module && + (Array.isArray(ref.importedNames) || + Array.isArray(ref.module.buildMeta.providedExports)) + ) + + // Take the imported module + .map(ref => ref.module) + ); + } + + _tryToAdd(compilation, config, module, possibleModules, failureCache) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + return cacheEntry; + } + + // Already added? + if (config.has(module)) { + return null; + } + + // Not possible to add? + if (!possibleModules.has(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } + + // module must be in the same chunks + if (!config.rootModule.hasEqualsChunks(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } + + // Clone config to make experimental changes + const testConfig = config.clone(); + + // Add the module + testConfig.add(module); + + // Every module which depends on the added module must be in the configuration too. + for (const reason of module.reasons) { + // Modules that are not used can be ignored + if ( + reason.module.factoryMeta.sideEffectFree && + reason.module.used === false + ) + continue; + + const problem = this._tryToAdd( + compilation, + testConfig, + reason.module, + possibleModules, + failureCache + ); + if (problem) { + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + // Commit experimental changes + config.set(testConfig); + + // Eagerly try to add imports too if possible + for (const imp of this._getImports(compilation, module)) { + const problem = this._tryToAdd( + compilation, + config, + imp, + possibleModules, + failureCache + ); + if (problem) { + config.addWarning(imp, problem); + } + } + return null; + } +} + +class ConcatConfiguration { + constructor(rootModule, cloneFrom) { + this.rootModule = rootModule; + if (cloneFrom) { + this.modules = cloneFrom.modules.createChild(5); + this.warnings = cloneFrom.warnings.createChild(5); + } else { + this.modules = new StackedSetMap(); + this.modules.add(rootModule); + this.warnings = new StackedSetMap(); + } + } + + add(module) { + this.modules.add(module); + } + + has(module) { + return this.modules.has(module); + } + + isEmpty() { + return this.modules.size === 1; + } + + addWarning(module, problem) { + this.warnings.set(module, problem); + } + + getWarningsSorted() { + return new Map( + this.warnings.asPairArray().sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) + ); + } + + getModules() { + return this.modules.asSet(); + } + + clone() { + return new ConcatConfiguration(this.rootModule, this); + } + + set(config) { + this.rootModule = config.rootModule; + this.modules = config.modules; + this.warnings = config.warnings; + } +} + +module.exports = ModuleConcatenationPlugin; + + +/***/ }), + +/***/ 68053: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("../Compiler")} Compiler */ + +class NaturalChunkOrderPlugin { + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("NaturalChunkOrderPlugin", compilation => { + compilation.hooks.optimizeChunkOrder.tap( + "NaturalChunkOrderPlugin", + chunks => { + chunks.sort((chunkA, chunkB) => { + const a = chunkA.modulesIterable[Symbol.iterator](); + const b = chunkB.modulesIterable[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done && bItem.done) return 0; + if (aItem.done) return -1; + if (bItem.done) return 1; + const aModuleId = aItem.value.id; + const bModuleId = bItem.value.id; + if (aModuleId < bModuleId) return -1; + if (aModuleId > bModuleId) return 1; + } + }); + } + ); + }); + } +} + +module.exports = NaturalChunkOrderPlugin; + + +/***/ }), + +/***/ 83741: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(88771); + +/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ + +class OccurrenceOrderChunkIdsPlugin { + /** + * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); + this.options = options; + } + + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap( + "OccurrenceOrderChunkIdsPlugin", + compilation => { + compilation.hooks.optimizeChunkOrder.tap( + "OccurrenceOrderChunkIdsPlugin", + chunks => { + const occursInInitialChunksMap = new Map(); + const originalOrder = new Map(); + + let i = 0; + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + originalOrder.set(c, i++); + } + + chunks.sort((a, b) => { + 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; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + } + ); + } +} + +module.exports = OccurrenceOrderChunkIdsPlugin; + + +/***/ }), + +/***/ 62000: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(81430); + +/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderModuleIdsPlugin").OccurrenceOrderModuleIdsPluginOptions} OccurrenceOrderModuleIdsPluginOptions */ + +class OccurrenceOrderModuleIdsPlugin { + /** + * @param {OccurrenceOrderModuleIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validateOptions(schema, options, "Occurrence Order Module Ids Plugin"); + this.options = options; + } + + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap( + "OccurrenceOrderModuleIdsPlugin", + compilation => { + compilation.hooks.optimizeModuleOrder.tap( + "OccurrenceOrderModuleIdsPlugin", + modules => { + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); + + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modules) { + let initial = 0; + let entry = 0; + for (const c of m.chunksIterable) { + if (c.canBeInitial()) initial++; + if (c.entryModule === m) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } + + const countOccursInEntry = (sum, r) => { + if (!r.module) { + return sum; + } + const count = initialChunkChunkMap.get(r.module); + if (!count) { + return sum; + } + return sum + count; + }; + const countOccurs = (sum, r) => { + if (!r.module) { + return sum; + } + let factor = 1; + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { + factor = r.dependency.getNumberOfIdOccurrences(); + } + if (factor === 0) { + return sum; + } + return sum + factor * r.module.getNumberOfChunks(); + }; + + if (prioritiseInitial) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } + + const originalOrder = new Map(); + let i = 0; + for (const m of modules) { + const result = + m.reasons.reduce(countOccurs, 0) + + m.getNumberOfChunks() + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + originalOrder.set(m, i++); + } + + modules.sort((a, b) => { + if (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; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + } + ); + } +} + +module.exports = OccurrenceOrderModuleIdsPlugin; + + +/***/ }), + +/***/ 67340: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +// TODO webpack 5 remove this plugin +// It has been splitted into separate plugins for modules and chunks +class OccurrenceOrderPlugin { + constructor(preferEntry) { + if (preferEntry !== undefined && typeof preferEntry !== "boolean") { + throw new Error( + "Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/" + ); + } + this.preferEntry = preferEntry; + } + apply(compiler) { + const preferEntry = this.preferEntry; + compiler.hooks.compilation.tap("OccurrenceOrderPlugin", compilation => { + compilation.hooks.optimizeModuleOrder.tap( + "OccurrenceOrderPlugin", + modules => { + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); + + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modules) { + let initial = 0; + let entry = 0; + for (const c of m.chunksIterable) { + if (c.canBeInitial()) initial++; + if (c.entryModule === m) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } + + const countOccursInEntry = (sum, r) => { + if (!r.module) { + return sum; + } + return sum + initialChunkChunkMap.get(r.module); + }; + const countOccurs = (sum, r) => { + if (!r.module) { + return sum; + } + let factor = 1; + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { + factor = r.dependency.getNumberOfIdOccurrences(); + } + if (factor === 0) { + return sum; + } + return sum + factor * r.module.getNumberOfChunks(); + }; + + if (preferEntry) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } + + const originalOrder = new Map(); + let i = 0; + for (const m of modules) { + const result = + m.reasons.reduce(countOccurs, 0) + + m.getNumberOfChunks() + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + originalOrder.set(m, i++); + } + + modules.sort((a, b) => { + if (preferEntry) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + compilation.hooks.optimizeChunkOrder.tap( + "OccurrenceOrderPlugin", + chunks => { + const occursInInitialChunksMap = new Map(); + const originalOrder = new Map(); + + let i = 0; + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + originalOrder.set(c, i++); + } + + chunks.sort((a, b) => { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + }); + } +} + +module.exports = OccurrenceOrderPlugin; + + +/***/ }), + +/***/ 78085: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class RemoveEmptyChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { + const handler = chunks => { + for (let i = chunks.length - 1; i >= 0; i--) { + const chunk = chunks[i]; + if ( + chunk.isEmpty() && + !chunk.hasRuntime() && + !chunk.hasEntryModule() + ) { + chunk.remove("empty"); + chunks.splice(i, 1); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + }); + } +} +module.exports = RemoveEmptyChunksPlugin; + + +/***/ }), + +/***/ 58142: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Queue = __webpack_require__(38637); +const { intersect } = __webpack_require__(54262); + +const getParentChunksWithModule = (currentChunk, module) => { + const chunks = []; + const stack = new Set(currentChunk.parentsIterable); + + for (const chunk of stack) { + if (chunk.containsModule(module)) { + chunks.push(chunk); + } else { + for (const parent of chunk.parentsIterable) { + stack.add(parent); + } + } + } + + return chunks; +}; + +class RemoveParentModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const queue = new Queue(); + const availableModulesMap = new WeakMap(); + + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + + while (queue.length > 0) { + const chunkGroup = queue.dequeue(); + let availableModules = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + // If we know the available modules in parent: process these + if (availableModules === undefined) { + // if we have not own info yet: create new entry + availableModules = new Set(availableModulesInParent); + for (const chunk of parent.chunks) { + for (const m of chunk.modulesIterable) { + availableModules.add(m); + } + } + availableModulesMap.set(chunkGroup, availableModules); + changed = true; + } else { + for (const m of availableModules) { + if ( + !parent.containsModule(m) && + !availableModulesInParent.has(m) + ) { + availableModules.delete(m); + changed = true; + } + } + } + } + } + if (changed) { + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + } + + // now we have available modules for every chunk + for (const chunk of chunks) { + const availableModulesSets = Array.from( + chunk.groupsIterable, + chunkGroup => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group + const availableModules = + availableModulesSets.length === 1 + ? availableModulesSets[0] + : intersect(availableModulesSets); + const numberOfModules = chunk.getNumberOfModules(); + const toRemove = new Set(); + if (numberOfModules < availableModules.size) { + for (const m of chunk.modulesIterable) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } + } else { + for (const m of availableModules) { + if (chunk.containsModule(m)) { + toRemove.add(m); + } + } + } + for (const module of toRemove) { + module.rewriteChunkInReasons( + chunk, + getParentChunksWithModule(chunk, module) + ); + chunk.removeModule(module); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); + }); + } +} +module.exports = RemoveParentModulesPlugin; + + +/***/ }), + +/***/ 76894: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class RuntimeChunkPlugin { + constructor(options) { + this.options = Object.assign( + { + name: entrypoint => `runtime~${entrypoint.name}` + }, + options + ); + } + + apply(compiler) { + compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap("RuntimeChunkPlugin", () => { + for (const entrypoint of compilation.entrypoints.values()) { + const chunk = entrypoint.getRuntimeChunk(); + let name = this.options.name; + if (typeof name === "function") { + name = name(entrypoint); + } + if ( + chunk.getNumberOfModules() > 0 || + !chunk.preventIntegration || + chunk.name !== name + ) { + const newChunk = compilation.addChunk(name); + newChunk.preventIntegration = true; + entrypoint.unshiftChunk(newChunk); + newChunk.addGroup(entrypoint); + entrypoint.setRuntimeChunk(newChunk); + } + } + }); + }); + } +}; + + +/***/ }), + +/***/ 83654: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const mm = __webpack_require__(53024); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Dependency")} Dependency */ + +/** + * @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 + */ + +/** + * @param {ReexportInfo} info info object + * @param {string} exportName name of export + * @returns {ExportInModule | undefined} static export + */ +const getMappingFromInfo = (info, exportName) => { + const staticMappings = info.static.get(exportName); + if (staticMappings !== undefined) { + if (staticMappings.length === 1) return staticMappings[0]; + return undefined; + } + const dynamicMappings = Array.from(info.dynamic).filter( + ([_, ignored]) => !ignored.has(exportName) + ); + if (dynamicMappings.length === 1) { + return { + module: dynamicMappings[0][0], + exportName, + checked: true + }; + } + return undefined; +}; + +/** + * @param {ReexportInfo} info info object + * @param {string} exportName name of export of source module + * @param {Module} module the target module + * @param {string} innerExportName name of export of target module + * @param {boolean} checked true, if existence of target module is checked + */ +const addStaticReexport = ( + info, + exportName, + module, + innerExportName, + checked +) => { + let mappings = info.static.get(exportName); + if (mappings !== undefined) { + for (const mapping of mappings) { + if (mapping.module === module && mapping.exportName === innerExportName) { + mapping.checked = mapping.checked && checked; + return; + } + } + } else { + mappings = []; + info.static.set(exportName, mappings); + } + mappings.push({ + module, + exportName: innerExportName, + checked + }); +}; + +/** + * @param {ReexportInfo} info info object + * @param {Module} module the reexport module + * @param {Set} ignored ignore list + * @returns {void} + */ +const addDynamicReexport = (info, module, ignored) => { + const existingList = info.dynamic.get(module); + if (existingList !== undefined) { + for (const key of existingList) { + if (!ignored.has(key)) existingList.delete(key); + } + } else { + info.dynamic.set(module, new Set(ignored)); + } +}; + +class SideEffectsFlagPlugin { + apply(compiler) { + compiler.hooks.normalModuleFactory.tap("SideEffectsFlagPlugin", nmf => { + nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { + const resolveData = data.resourceResolveData; + if ( + resolveData && + resolveData.descriptionFileData && + resolveData.relativePath + ) { + const sideEffects = resolveData.descriptionFileData.sideEffects; + const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( + resolveData.relativePath, + sideEffects + ); + if (!hasSideEffects) { + module.factoryMeta.sideEffectFree = true; + } + } + + return module; + }); + nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { + if (data.settings.sideEffects === false) { + module.factoryMeta.sideEffectFree = true; + } else if (data.settings.sideEffects === true) { + module.factoryMeta.sideEffectFree = false; + } + }); + }); + compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { + compilation.hooks.optimizeDependencies.tap( + "SideEffectsFlagPlugin", + modules => { + /** @type {Map} */ + const reexportMaps = new Map(); + + // Capture reexports of sideEffectFree modules + for (const module of modules) { + /** @type {Dependency[]} */ + const removeDependencies = []; + for (const dep of module.dependencies) { + if (dep instanceof HarmonyImportSideEffectDependency) { + if (dep.module && dep.module.factoryMeta.sideEffectFree) { + removeDependencies.push(dep); + } + } else if ( + dep instanceof HarmonyExportImportedSpecifierDependency + ) { + if (module.factoryMeta.sideEffectFree) { + const mode = dep.getMode(true); + if ( + mode.type === "safe-reexport" || + mode.type === "checked-reexport" || + mode.type === "dynamic-reexport" || + mode.type === "reexport-non-harmony-default" || + mode.type === "reexport-non-harmony-default-strict" || + mode.type === "reexport-named-default" + ) { + let info = reexportMaps.get(module); + if (!info) { + reexportMaps.set( + module, + (info = { + static: new Map(), + dynamic: new Map() + }) + ); + } + const targetModule = dep._module; + switch (mode.type) { + case "safe-reexport": + for (const [key, id] of mode.map) { + if (id) { + addStaticReexport( + info, + key, + targetModule, + id, + false + ); + } + } + break; + case "checked-reexport": + for (const [key, id] of mode.map) { + if (id) { + addStaticReexport( + info, + key, + targetModule, + id, + true + ); + } + } + break; + case "dynamic-reexport": + addDynamicReexport(info, targetModule, mode.ignored); + break; + case "reexport-non-harmony-default": + case "reexport-non-harmony-default-strict": + case "reexport-named-default": + addStaticReexport( + info, + mode.name, + targetModule, + "default", + false + ); + break; + } + } + } + } + } + } + + // Flatten reexports + for (const info of reexportMaps.values()) { + const dynamicReexports = info.dynamic; + info.dynamic = new Map(); + for (const reexport of dynamicReexports) { + let [targetModule, ignored] = reexport; + for (;;) { + const innerInfo = reexportMaps.get(targetModule); + if (!innerInfo) break; + + for (const [key, reexports] of innerInfo.static) { + if (ignored.has(key)) continue; + for (const { module, exportName, checked } of reexports) { + addStaticReexport(info, key, module, exportName, checked); + } + } + + // Follow dynamic reexport if there is only one + if (innerInfo.dynamic.size !== 1) { + // When there are more then one, we don't know which one + break; + } + + ignored = new Set(ignored); + for (const [innerModule, innerIgnored] of innerInfo.dynamic) { + for (const key of innerIgnored) { + if (ignored.has(key)) continue; + // This reexports ends here + addStaticReexport(info, key, targetModule, key, true); + ignored.add(key); + } + targetModule = innerModule; + } + } + + // Update reexport as all other cases has been handled + addDynamicReexport(info, targetModule, ignored); + } + } + + for (const info of reexportMaps.values()) { + const staticReexports = info.static; + info.static = new Map(); + for (const [key, reexports] of staticReexports) { + for (let mapping of reexports) { + for (;;) { + const innerInfo = reexportMaps.get(mapping.module); + if (!innerInfo) break; + + const newMapping = getMappingFromInfo( + innerInfo, + mapping.exportName + ); + if (!newMapping) break; + mapping = newMapping; + } + addStaticReexport( + info, + key, + mapping.module, + mapping.exportName, + mapping.checked + ); + } + } + } + + // Update imports along the reexports from sideEffectFree modules + for (const pair of reexportMaps) { + const module = pair[0]; + const info = pair[1]; + let newReasons = undefined; + for (let i = 0; i < module.reasons.length; i++) { + const reason = module.reasons[i]; + const dep = reason.dependency; + if ( + (dep instanceof HarmonyExportImportedSpecifierDependency || + (dep instanceof HarmonyImportSpecifierDependency && + !dep.namespaceObjectAsContext)) && + dep._id + ) { + const mapping = getMappingFromInfo(info, dep._id); + if (mapping) { + dep.redirectedModule = mapping.module; + dep.redirectedId = mapping.exportName; + mapping.module.addReason( + reason.module, + dep, + reason.explanation + ? reason.explanation + + " (skipped side-effect-free modules)" + : "(skipped side-effect-free modules)" + ); + // removing the currect reason, by not adding it to the newReasons array + // lazily create the newReasons array + if (newReasons === undefined) { + newReasons = i === 0 ? [] : module.reasons.slice(0, i); + } + continue; + } + } + if (newReasons !== undefined) newReasons.push(reason); + } + if (newReasons !== undefined) { + module.reasons = newReasons; + } + } + } + ); + }); + } + + static moduleHasSideEffects(moduleName, flagValue) { + switch (typeof flagValue) { + case "undefined": + return true; + case "boolean": + return flagValue; + case "string": + if (process.platform === "win32") { + flagValue = flagValue.replace(/\\/g, "/"); + } + return mm.isMatch(moduleName, flagValue, { + matchBase: true + }); + case "object": + return flagValue.some(glob => + SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob) + ); + } + } +} +module.exports = SideEffectsFlagPlugin; + + +/***/ }), + +/***/ 60474: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const crypto = __webpack_require__(76417); +const SortableSet = __webpack_require__(50071); +const GraphHelpers = __webpack_require__(32973); +const { isSubset } = __webpack_require__(54262); +const deterministicGrouping = __webpack_require__(30815); +const MinMaxSizeWarning = __webpack_require__(25472); +const contextify = __webpack_require__(94658).contextify; + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ + +const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); + +const hashFilename = name => { + return crypto + .createHash("md4") + .update(name) + .digest("hex") + .slice(0, 8); +}; + +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; + +const getRequests = chunk => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); + } + return requests; +}; + +const getModulesSize = modules => { + let sum = 0; + for (const m of modules) { + sum += m.size(); + } + return sum; +}; + +/** + * @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 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 = a.size * (a.chunks.size - 1); + const bSizeReduce = b.size * (b.chunks.size - 1); + const diffSizeReduce = aSizeReduce - bSizeReduce; + if (diffSizeReduce) return diffSizeReduce; + // 4. by cache group index + const indexDiff = a.cacheGroupIndex - b.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(); + const aI = modulesA[Symbol.iterator](); + const bI = modulesB[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) return 0; + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier > bModuleIdentifier) return -1; + if (aModuleIdentifier < bModuleIdentifier) return 1; + } +}; + +const compareNumbers = (a, b) => a - b; + +const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); +const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); +const ALL_CHUNK_FILTER = chunk => true; + +module.exports = class SplitChunksPlugin { + constructor(options) { + this.options = SplitChunksPlugin.normalizeOptions(options); + } + + static normalizeOptions(options = {}) { + return { + chunksFilter: SplitChunksPlugin.normalizeChunksFilter( + options.chunks || "all" + ), + minSize: options.minSize || 0, + enforceSizeThreshold: options.enforceSizeThreshold || 0, + maxSize: options.maxSize || 0, + minChunks: options.minChunks || 1, + maxAsyncRequests: options.maxAsyncRequests || 1, + maxInitialRequests: options.maxInitialRequests || 1, + hidePathInfo: options.hidePathInfo || false, + filename: options.filename || undefined, + getCacheGroups: SplitChunksPlugin.normalizeCacheGroups({ + cacheGroups: options.cacheGroups, + name: options.name, + automaticNameDelimiter: options.automaticNameDelimiter, + automaticNameMaxLength: options.automaticNameMaxLength + }), + automaticNameDelimiter: options.automaticNameDelimiter, + automaticNameMaxLength: options.automaticNameMaxLength || 109, + fallbackCacheGroup: SplitChunksPlugin.normalizeFallbackCacheGroup( + options.fallbackCacheGroup || {}, + options + ) + }; + } + + static normalizeName({ + name, + automaticNameDelimiter, + automaticNamePrefix, + automaticNameMaxLength + }) { + if (name === true) { + /** @type {WeakMap>} */ + const cache = new WeakMap(); + const fn = (module, chunks, cacheGroup) => { + let cacheEntry = cache.get(chunks); + if (cacheEntry === undefined) { + cacheEntry = {}; + cache.set(chunks, cacheEntry); + } else if (cacheGroup in cacheEntry) { + return cacheEntry[cacheGroup]; + } + const names = chunks.map(c => c.name); + if (!names.every(Boolean)) { + cacheEntry[cacheGroup] = undefined; + return; + } + names.sort(); + const prefix = + typeof automaticNamePrefix === "string" + ? automaticNamePrefix + : cacheGroup; + const namePrefix = prefix ? prefix + automaticNameDelimiter : ""; + let name = namePrefix + names.join(automaticNameDelimiter); + // Filenames and paths can't be too long otherwise an + // ENAMETOOLONG error is raised. If the generated name if too + // long, it is truncated and a hash is appended. The limit has + // been set to 109 to prevent `[name].[chunkhash].[ext]` from + // generating a 256+ character string. + if (name.length > automaticNameMaxLength) { + const hashedFilename = hashFilename(name); + const sliceLength = + automaticNameMaxLength - + (automaticNameDelimiter.length + hashedFilename.length); + name = + name.slice(0, sliceLength) + + automaticNameDelimiter + + hashedFilename; + } + cacheEntry[cacheGroup] = name; + return name; + }; + return fn; + } + if (typeof name === "string") { + const fn = () => { + return name; + }; + return fn; + } + if (typeof name === "function") return name; + } + + static 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; + } + + static normalizeFallbackCacheGroup( + { + minSize = undefined, + maxSize = undefined, + automaticNameDelimiter = undefined + }, + { + minSize: defaultMinSize = undefined, + maxSize: defaultMaxSize = undefined, + automaticNameDelimiter: defaultAutomaticNameDelimiter = undefined + } + ) { + return { + minSize: typeof minSize === "number" ? minSize : defaultMinSize || 0, + maxSize: typeof maxSize === "number" ? maxSize : defaultMaxSize || 0, + automaticNameDelimiter: + automaticNameDelimiter || defaultAutomaticNameDelimiter || "~" + }; + } + + static normalizeCacheGroups({ + cacheGroups, + name, + automaticNameDelimiter, + automaticNameMaxLength + }) { + if (typeof cacheGroups === "function") { + // TODO webpack 5 remove this + if (cacheGroups.length !== 1) { + return module => cacheGroups(module, module.getChunks()); + } + return cacheGroups; + } + if (cacheGroups && typeof cacheGroups === "object") { + const fn = module => { + let results; + for (const key of Object.keys(cacheGroups)) { + let option = cacheGroups[key]; + if (option === false) continue; + if (option instanceof RegExp || typeof option === "string") { + option = { + test: option + }; + } + if (typeof option === "function") { + let result = option(module); + if (result) { + if (results === undefined) results = []; + for (const r of Array.isArray(result) ? result : [result]) { + const result = Object.assign({ key }, r); + if (result.name) result.getName = () => result.name; + if (result.chunks) { + result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( + result.chunks + ); + } + results.push(result); + } + } + } else if (SplitChunksPlugin.checkTest(option.test, module)) { + if (results === undefined) results = []; + results.push({ + key: key, + priority: option.priority, + getName: + SplitChunksPlugin.normalizeName({ + name: option.name || name, + automaticNameDelimiter: + typeof option.automaticNameDelimiter === "string" + ? option.automaticNameDelimiter + : automaticNameDelimiter, + automaticNamePrefix: option.automaticNamePrefix, + automaticNameMaxLength: + option.automaticNameMaxLength || automaticNameMaxLength + }) || (() => {}), + chunksFilter: SplitChunksPlugin.normalizeChunksFilter( + option.chunks + ), + enforce: option.enforce, + minSize: option.minSize, + enforceSizeThreshold: option.enforceSizeThreshold, + maxSize: option.maxSize, + minChunks: option.minChunks, + maxAsyncRequests: option.maxAsyncRequests, + maxInitialRequests: option.maxInitialRequests, + filename: option.filename, + reuseExistingChunk: option.reuseExistingChunk + }); + } + } + return results; + }; + return fn; + } + const fn = () => {}; + return fn; + } + + static checkTest(test, module) { + if (test === undefined) return true; + if (typeof test === "function") { + if (test.length !== 1) { + return test(module, module.getChunks()); + } + return test(module); + } + if (typeof test === "boolean") return test; + if (typeof test === "string") { + if ( + module.nameForCondition && + module.nameForCondition().startsWith(test) + ) { + return true; + } + for (const chunk of module.chunksIterable) { + if (chunk.name && chunk.name.startsWith(test)) { + return true; + } + } + return false; + } + if (test instanceof RegExp) { + if (module.nameForCondition && test.test(module.nameForCondition())) { + return true; + } + for (const chunk of module.chunksIterable) { + if (chunk.name && test.test(chunk.name)) { + return true; + } + } + return false; + } + return false; + } + + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { + let alreadyOptimized = false; + compilation.hooks.unseal.tap("SplitChunksPlugin", () => { + alreadyOptimized = false; + }); + compilation.hooks.optimizeChunksAdvanced.tap( + "SplitChunksPlugin", + chunks => { + if (alreadyOptimized) return; + alreadyOptimized = true; + // Give each selected chunk an index (to create strings from chunks) + const indexMap = new Map(); + let index = 1; + for (const chunk of chunks) { + indexMap.set(chunk, index++); + } + const getKey = chunks => { + return Array.from(chunks, c => indexMap.get(c)) + .sort(compareNumbers) + .join(); + }; + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + for (const module of compilation.modules) { + const chunksKey = getKey(module.chunksIterable); + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(module.chunksIterable)); + } + } + + // group these set of chunks by count + // to allow to check less sets via isSubset + // (only smaller sets can be subset) + /** @type {Map>>} */ + const chunkSetsByCount = new Map(); + for (const chunksSet of chunkSetsInGraph.values()) { + const count = chunksSet.size; + let array = chunkSetsByCount.get(count); + if (array === undefined) { + array = []; + chunkSetsByCount.set(count, array); + } + array.push(chunksSet); + } + + // Create a list of possible combinations + const combinationsCache = new Map(); // Map[]> + + const getCombinations = key => { + const chunksSet = chunkSetsInGraph.get(key); + var array = [chunksSet]; + if (chunksSet.size > 1) { + 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); + } + } + } + } + } + return array; + }; + + /** + * @typedef {Object} SelectedChunksResult + * @property {Chunk[]} chunks the list of chunks + * @property {string} key a key of the list + */ + + /** + * @typedef {function(Chunk): boolean} ChunkFilterFunction + */ + + /** @type {WeakMap, 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} 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 = []; + for (const chunk of chunks) { + if (chunkFilter(chunk)) selectedChunks.push(chunk); + } + entry2 = { + chunks: selectedChunks, + key: getKey(selectedChunks) + }; + entry.set(chunkFilter, entry2); + } + return entry2; + }; + + /** + * @typedef {Object} ChunksInfoItem + * @property {SortableSet} modules + * @property {TODO} cacheGroup + * @property {number} cacheGroupIndex + * @property {string} name + * @property {number} size + * @property {Set} chunks + * @property {Set} reuseableChunks + * @property {Set} chunksKeys + */ + + // 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 {TODO} 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 {string} 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 + ); + // Create key for maps + // When it has a name we use the name as key + // Elsewise we create the key from chunks and cache group key + // This automatically merges equal names + const key = + cacheGroup.key + + (name ? ` name:${name}` : ` chunks:${selectedChunksKey}`); + // Add module to maps + let info = chunksInfoMap.get(key); + if (info === undefined) { + chunksInfoMap.set( + key, + (info = { + modules: new SortableSet(undefined, sortByIdentifier), + cacheGroup, + cacheGroupIndex, + name, + size: 0, + chunks: new Set(), + reuseableChunks: new Set(), + chunksKeys: new Set() + }) + ); + } + info.modules.add(module); + info.size += module.size(); + if (!info.chunksKeys.has(selectedChunksKey)) { + info.chunksKeys.add(selectedChunksKey); + for (const chunk of selectedChunks) { + info.chunks.add(chunk); + } + } + }; + + // Walk through all modules + for (const module of compilation.modules) { + // Get cache group + let cacheGroups = this.options.getCacheGroups(module); + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { + continue; + } + + // Prepare some values + const chunksKey = getKey(module.chunksIterable); + let combs = combinationsCache.get(chunksKey); + if (combs === undefined) { + combs = getCombinations(chunksKey); + combinationsCache.set(chunksKey, combs); + } + + let cacheGroupIndex = 0; + for (const cacheGroupSource of cacheGroups) { + const minSize = + cacheGroupSource.minSize !== undefined + ? cacheGroupSource.minSize + : cacheGroupSource.enforce + ? 0 + : this.options.minSize; + const enforceSizeThreshold = + cacheGroupSource.enforceSizeThreshold !== undefined + ? cacheGroupSource.enforceSizeThreshold + : cacheGroupSource.enforce + ? 0 + : this.options.enforceSizeThreshold; + const cacheGroup = { + key: cacheGroupSource.key, + priority: cacheGroupSource.priority || 0, + chunksFilter: + cacheGroupSource.chunksFilter || this.options.chunksFilter, + minSize, + minSizeForMaxSize: + cacheGroupSource.minSize !== undefined + ? cacheGroupSource.minSize + : this.options.minSize, + enforceSizeThreshold, + maxSize: + cacheGroupSource.maxSize !== undefined + ? cacheGroupSource.maxSize + : cacheGroupSource.enforce + ? 0 + : this.options.maxSize, + 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, + filename: + cacheGroupSource.filename !== undefined + ? cacheGroupSource.filename + : this.options.filename, + automaticNameDelimiter: + cacheGroupSource.automaticNameDelimiter !== undefined + ? cacheGroupSource.automaticNameDelimiter + : this.options.automaticNameDelimiter, + reuseExistingChunk: cacheGroupSource.reuseExistingChunk, + _validateSize: minSize > 0, + _conditionalEnforce: enforceSizeThreshold > 0 + }; + // For all combination of chunk selection + for (const chunkCombination of combs) { + // Break if minimum number of chunks is not reached + if (chunkCombination.size < cacheGroup.minChunks) continue; + // Select chunks by configuration + const { + chunks: selectedChunks, + key: selectedChunksKey + } = getSelectedChunks( + chunkCombination, + cacheGroup.chunksFilter + ); + + addModuleToChunksInfoMap( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ); + } + cacheGroupIndex++; + } + } + + // Filter items were size < minSize + for (const pair of chunksInfoMap) { + const info = pair[1]; + if ( + info.cacheGroup._validateSize && + info.size < info.cacheGroup.minSize + ) { + chunksInfoMap.delete(pair[0]); + } + } + + /** @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) { + bestEntry = info; + bestEntryKey = key; + } else if (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 isReused = false; + if (item.cacheGroup.reuseExistingChunk) { + outer: for (const chunk of item.chunks) { + if (chunk.getNumberOfModules() !== item.modules.size) continue; + if (chunk.hasEntryModule()) continue; + for (const module of item.modules) { + if (!chunk.containsModule(module)) 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; + } + chunkName = undefined; + isReused = true; + } + } + // Check if maxRequests condition can be fulfilled + + const selectedChunks = Array.from(item.chunks).filter(chunk => { + // skip if we address ourself + return ( + (!chunkName || chunk.name !== chunkName) && chunk !== newChunk + ); + }); + + const enforced = + item.cacheGroup._conditionalEnforce && + item.size >= item.cacheGroup.enforceSizeThreshold; + + // Skip when no chunk selected + if (selectedChunks.length === 0) continue; + + const usedChunks = new Set(selectedChunks); + + // 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 (chunk.containsModule(module)) 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 < selectedChunks.length) { + 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; + } + + // Create the new chunk if not reusing one + if (!isReused) { + 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 = isReused + ? "reused as split chunk" + : "split chunk"; + if (item.cacheGroup.key) { + newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; + } + if (chunkName) { + newChunk.chunkReason += ` (name: ${chunkName})`; + // If the chosen name is already an entry point we remove the entry point + const entrypoint = compilation.entrypoints.get(chunkName); + if (entrypoint) { + compilation.entrypoints.delete(chunkName); + entrypoint.remove(); + newChunk.entryModule = undefined; + } + } + if (item.cacheGroup.filename) { + if (!newChunk.isOnlyInitial()) { + throw new Error( + "SplitChunksPlugin: You are trying to set a filename for a chunk which is (also) loaded on demand. " + + "The runtime can only handle loading of chunks which match the chunkFilename schema. " + + "Using a custom filename would fail at runtime. " + + `(cache group: ${item.cacheGroup.key})` + ); + } + newChunk.filenameTemplate = item.cacheGroup.filename; + } + if (!isReused) { + // Add all modules to the new chunk + for (const module of item.modules) { + if (typeof module.chunkCondition === "function") { + if (!module.chunkCondition(newChunk)) continue; + } + // Add module to new chunk + GraphHelpers.connectChunkAndModule(newChunk, module); + // Remove module from used chunks + for (const chunk of usedChunks) { + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newChunk]); + } + } + } else { + // Remove all modules from used chunks + for (const module of item.modules) { + for (const chunk of usedChunks) { + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newChunk]); + } + } + } + + if (item.cacheGroup.maxSize > 0) { + const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); + maxSizeQueueMap.set(newChunk, { + minSize: Math.max( + oldMaxSizeSettings ? oldMaxSizeSettings.minSize : 0, + item.cacheGroup.minSizeForMaxSize + ), + maxSize: Math.min( + oldMaxSizeSettings ? oldMaxSizeSettings.maxSize : Infinity, + item.cacheGroup.maxSize + ), + 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 + const oldSize = info.modules.size; + for (const module of item.modules) { + info.modules.delete(module); + } + if (info.modules.size !== oldSize) { + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + continue; + } + info.size = getModulesSize(info.modules); + if ( + info.cacheGroup._validateSize && + info.size < info.cacheGroup.minSize + ) { + chunksInfoMap.delete(key); + } + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + } + } + } + } + } + + const incorrectMinMaxSizeSet = new Set(); + + // Make sure that maxSize is fulfilled + for (const chunk of compilation.chunks.slice()) { + const { minSize, maxSize, automaticNameDelimiter, keys } = + maxSizeQueueMap.get(chunk) || this.options.fallbackCacheGroup; + if (!maxSize) continue; + if (minSize > maxSize) { + const warningKey = `${keys && keys.join()} ${minSize} ${maxSize}`; + if (!incorrectMinMaxSizeSet.has(warningKey)) { + incorrectMinMaxSizeSet.add(warningKey); + compilation.warnings.push( + new MinMaxSizeWarning(keys, minSize, maxSize) + ); + } + } + const results = deterministicGroupingForModules({ + maxSize: Math.max(minSize, maxSize), + minSize, + items: chunk.modulesIterable, + getKey(module) { + const ident = contextify( + compilation.options.context, + module.identifier() + ); + const name = module.nameForCondition + ? contextify( + compilation.options.context, + module.nameForCondition() + ) + : ident.replace(/^.*!|\?[^?!]*$/g, ""); + const fullKey = + name + automaticNameDelimiter + hashFilename(ident); + return fullKey.replace(/[\\/?]/g, "_"); + }, + getSize(module) { + return module.size(); + } + }); + results.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + for (let i = 0; i < results.length; i++) { + const group = results[i]; + const key = this.options.hidePathInfo + ? hashFilename(group.key) + : group.key; + let name = chunk.name + ? chunk.name + automaticNameDelimiter + key + : null; + if (name && name.length > 100) { + name = + name.slice(0, 100) + + automaticNameDelimiter + + hashFilename(name); + } + let newPart; + if (i !== results.length - 1) { + 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 (typeof module.chunkCondition === "function") { + if (!module.chunkCondition(newPart)) continue; + } + // Add module to new chunk + GraphHelpers.connectChunkAndModule(newPart, module); + // Remove module from used chunks + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newPart]); + } + } else { + // change the chunk to be a part + newPart = chunk; + chunk.name = name; + } + } + } + } + ); + }); + } +}; + + +/***/ }), + +/***/ 89339: +/***/ ((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__(97391); +const SizeFormatHelpers = __webpack_require__(12496); + +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map( + asset => + `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` + ) + .join(""); + + super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); + + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 41336: +/***/ ((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__(97391); +const SizeFormatHelpers = __webpack_require__(12496); + +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + entrypoint => + `\n ${entrypoint.name} (${SizeFormatHelpers.formatSize( + entrypoint.size + )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); + + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 53006: +/***/ ((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__(97391); + +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { + super( + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "NoAsyncChunksWarning"; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 68310: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +const EntrypointsOverSizeLimitWarning = __webpack_require__(41336); +const AssetsOverSizeLimitWarning = __webpack_require__(89339); +const NoAsyncChunksWarning = __webpack_require__(53006); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ + +module.exports = class SizeLimitsPlugin { + constructor(options) { + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; + } + + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = + this.assetFilter || ((name, source, info) => !info.development); + + compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { + const warnings = []; + + /** + * @param {Entrypoint} entrypoint an entrypoint + * @returns {number} the size of the entrypoint + */ + const getEntrypointSize = entrypoint => + entrypoint.getFiles().reduce((currentSize, file) => { + const asset = compilation.getAsset(file); + if ( + asset && + assetFilter(asset.name, asset.source, asset.info) && + asset.source + ) { + return currentSize + (asset.info.size || asset.source.size()); + } + + return currentSize; + }, 0); + + 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 + }); + /** @type {any} */ (source).isOverSizeLimit = true; + } + } + + const fileFilter = name => { + const asset = compilation.getAsset(name); + return asset && assetFilter(asset.name, asset.source, asset.info); + }; + + 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) + }); + /** @type {any} */ (entry).isOverSizeLimit = true; + } + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) + ); + } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + entrypointSizeLimit + ) + ); + } + + if (warnings.length > 0) { + const hasAsyncChunks = + compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > + 0; + + if (!hasAsyncChunks) { + warnings.push(new NoAsyncChunksWarning()); + } + + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); + } + } + } + }); + } +}; + + +/***/ }), + +/***/ 52315: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SortableSet = __webpack_require__(50071); + +/** + * @template T + * @template K + * 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 + */ +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 = this._keys.values().next().value; + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = leafEntry.values().next().value; + 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; + } + }; + } + 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); + } + }; + } + } + + /** + * @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); + } + } + } + + /** + * @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; + } + }; + } +} + +module.exports = LazyBucketSortedSet; + + +/***/ }), + +/***/ 38637: +/***/ ((module) => { + +"use strict"; + + +/** + * @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; + + +/***/ }), + +/***/ 33349: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class Semaphore { + /** + * Creates an instance of Semaphore. + * + * @param {number} available the amount available number of "tasks" + * in the Semaphore + */ + constructor(available) { + this.available = available; + /** @type {(function(): void)[]} */ + this.waiters = []; + /** @private */ + this._continue = this._continue.bind(this); + } + + /** + * @param {function(): void} callback function block to capture and run + * @returns {void} + */ + acquire(callback) { + if (this.available > 0) { + this.available--; + callback(); + } else { + this.waiters.push(callback); + } + } + + release() { + this.available++; + if (this.waiters.length > 0) { + process.nextTick(this._continue); + } + } + + _continue() { + if (this.available > 0) { + if (this.waiters.length > 0) { + this.available--; + const callback = this.waiters.pop(); + callback(); + } + } + } +} + +module.exports = Semaphore; + + +/***/ }), + +/***/ 54262: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * intersect creates Set containing the intersection of elements between all sets + * @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 + * @param {Set} bigSet a Set which contains the original elements to compare against + * @param {Set} smallSet the set whos 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; +}; + +exports.intersect = intersect; +exports.isSubset = isSubset; + + +/***/ }), + +/***/ 50071: +/***/ ((module) => { + +"use strict"; + + +/** + * 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 {function(T, T): number}} */ + this._sortFn = defaultSort; + /** @private @type {function(T, T): number} | null} */ + this._lastActiveSortFn = null; + /** @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 = null; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; + } + + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } + + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); + } + + /** + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } + + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } + + sort() { + this.sortWith(this._sortFn); + } + + /** + * Get data from cache + * @param {function(SortableSet): T[]} fn function to calculate value + * @returns {T[]} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const data = this._cache.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } + + /** + * @param {function(SortableSet): string|number|T[]} fn function to calculate value + * @returns {any} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const data = this._cacheOrderIndependent.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } + + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); + } + } + + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } +} + +module.exports = SortableSet; + + +/***/ }), + +/***/ 92251: +/***/ ((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__(31669); + +const TOMBSTONE = {}; +const UNDEFINED_MARKER = {}; + +class StackedSetMap { + constructor(parentStack) { + this.stack = parentStack === undefined ? [] : parentStack.slice(); + this.map = new Map(); + this.stack.push(this.map); + } + + add(item) { + this.map.set(item, true); + } + + set(item, value) { + this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); + } + + delete(item) { + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } + } + + has(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) return topValue !== TOMBSTONE; + if (this.stack.length > 1) { + for (var 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; + } + + 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 (var 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.entries(), pair => pair[0]); + } + + asSet() { + return new Set(this.asArray()); + } + + asPairArray() { + this._compress(); + return Array.from(this.map.entries(), pair => + /** @type {[TODO, TODO]} */ (pair[1] === UNDEFINED_MARKER + ? [pair[0], undefined] + : pair) + ); + } + + asMap() { + return new Map(this.asPairArray()); + } + + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedSetMap(this.stack); + } + + get length() { + throw new Error("This is no longer an Array"); + } + + set length(value) { + throw new Error("This is no longer an Array"); + } +} + +// TODO remove in webpack 5 +StackedSetMap.prototype.push = util.deprecate( + /** + * @deprecated + * @this {StackedSetMap} + * @param {any} item Item to add + * @returns {void} + */ + function(item) { + this.add(item); + }, + "This is no longer an Array: Use add instead." +); + +module.exports = StackedSetMap; + + +/***/ }), + +/***/ 67916: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const mergeCache = new WeakMap(); + +/** + * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. + * @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 {object} first first object + * @param {object} second second object + * @returns {object} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + 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); + innerCache.set(second, newMerge); + return newMerge; +}; + +/** + * Merges two objects. Objects are not deeply merged. + * TODO webpack 5: merge objects deeply clever. + * Arrays might reference the old value with "..." + * @param {object} first first object + * @param {object} second second object + * @returns {object} merged object of first and second object + */ +const cleverMerge = (first, second) => { + const newObject = Object.assign({}, first); + for (const key of Object.keys(second)) { + if (!(key in newObject)) { + newObject[key] = second[key]; + continue; + } + const secondValue = second[key]; + if (!Array.isArray(secondValue)) { + newObject[key] = secondValue; + continue; + } + const firstValue = newObject[key]; + if (Array.isArray(firstValue)) { + const newArray = []; + for (const item of secondValue) { + if (item === "...") { + for (const item of firstValue) { + newArray.push(item); + } + } else { + newArray.push(item); + } + } + newObject[key] = newArray; + } else { + newObject[key] = secondValue; + } + } + return newObject; +}; + +exports.cachedCleverMerge = cachedCleverMerge; +exports.cleverMerge = cleverMerge; + + +/***/ }), + +/***/ 15660: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const AbstractMethodError = __webpack_require__(36104); + +const BULK_SIZE = 1000; + +class 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) { + throw new AbstractMethodError(); + } + + /** + * 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) { + throw new AbstractMethodError(); + } +} + +exports.Hash = Hash; +/** @typedef {typeof Hash} HashConstructor */ + +class BulkUpdateDecorator extends Hash { + /** + * @param {Hash} hash hash + */ + constructor(hash) { + super(); + this.hash = hash; + 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.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) { + this.hash.update(this.buffer); + this.buffer = ""; + } + } + 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.buffer.length > 0) { + this.hash.update(this.buffer); + } + var digestResult = this.hash.digest(encoding); + return typeof digestResult === "string" + ? digestResult + : digestResult.toString(); + } +} + +/** + * 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"); + this.string += data; + 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 this.string.replace(/[^a-z0-9]+/gi, m => + Buffer.from(m).toString("hex") + ); + } +} + +/** + * Creates a hash by name or function + * @param {string | HashConstructor} 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(); + default: + return new BulkUpdateDecorator(__webpack_require__(76417).createHash(algorithm)); + } +}; + + +/***/ }), + +/***/ 30815: +/***/ ((module) => { + +"use strict"; + + +// 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 + * @returns {string} the common part and a single char for the difference + */ +const getName = (a, b) => { + const l = Math.min(a.length, b.length); + let r = ""; + for (let i = 0; i < l; i++) { + const ca = a.charAt(i); + const cb = b.charAt(i); + r += ca; + if (ca === cb) { + continue; + } + return r; + } + return a; +}; + +/** + * @template T + */ +class Node { + /** + * @param {T} item item + * @param {string} key key + * @param {number} size size + */ + constructor(item, key, size) { + this.item = item; + this.key = key; + this.size = size; + } +} + +/** + * @template T + */ +class Group { + /** + * @param {Node[]} nodes nodes + * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) + */ + constructor(nodes, similarities) { + this.nodes = nodes; + this.similarities = similarities; + this.size = nodes.reduce((size, node) => size + node.size, 0); + /** @type {string} */ + this.key = undefined; + } +} + +/** + * @template T + * @typedef {Object} GroupedItems + * @property {string} key + * @property {T[]} items + * @property {number} size + */ + +/** + * @template T + * @typedef {Object} Options + * @property {number} maxSize maximum size of a group + * @property {number} minSize minimum size of a group (preferred over maximum size) + * @property {Iterable} items a list of items + * @property {function(T): number} 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 + for (const node of nodes) { + if (node.size >= maxSize) { + result.push(new Group([node], [])); + } else { + initialNodes.push(node); + } + } + + if (initialNodes.length > 0) { + // calculate similarities between lexically adjacent nodes + /** @type {number[]} */ + const similarities = []; + for (let i = 1; i < initialNodes.length; i++) { + const a = initialNodes[i - 1]; + const b = initialNodes[i]; + similarities.push(similarity(a.key, b.key)); + } + + const initialGroup = new Group(initialNodes, similarities); + + if (initialGroup.size < minSize) { + // We hit an edgecase where the working set is already smaller than minSize + // We merge it with the smallest result node to keep minSize intact + if (result.length > 0) { + const smallestGroup = result.reduce((min, group) => + min.size > group.size ? group : min + ); + for (const node of initialGroup.nodes) smallestGroup.nodes.push(node); + smallestGroup.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 + // We use all nodes and have to accept that it's smaller than minSize + result.push(initialGroup); + } + } else { + const queue = [initialGroup]; + + while (queue.length) { + const group = queue.pop(); + // only groups bigger than maxSize need to be splitted + if (group.size < maxSize) { + result.push(group); + continue; + } + + // 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 = 0; + let leftSize = 0; + while (leftSize <= minSize) { + leftSize += group.nodes[left].size; + left++; + } + let right = group.nodes.length - 1; + let rightSize = 0; + while (rightSize <= minSize) { + rightSize += group.nodes[right].size; + right--; + } + + if (left - 1 > right) { + // can't split group while holding minSize + // because minSize is preferred of maxSize we return + // the group 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 + let best = left - 1; + let bestSimilarity = group.similarities[best]; + for (let i = left; i <= right; i++) { + const similarity = group.similarities[i]; + if (similarity < bestSimilarity) { + best = i; + bestSimilarity = similarity; + } + } + left = best + 1; + right = best; + } + + // create two new groups for left and right area + // and queue them up + const rightNodes = [group.nodes[right + 1]]; + /** @type {number[]} */ + const rightSimilaries = []; + for (let i = right + 2; i < group.nodes.length; i++) { + rightSimilaries.push(group.similarities[i - 1]); + rightNodes.push(group.nodes[i]); + } + queue.push(new Group(rightNodes, rightSimilaries)); + + const leftNodes = [group.nodes[0]]; + /** @type {number[]} */ + const leftSimilaries = []; + for (let i = 1; i < left; i++) { + leftSimilaries.push(group.similarities[i - 1]); + leftNodes.push(group.nodes[i]); + } + queue.push(new Group(leftNodes, leftSimilaries)); + } + } + } + + // 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 + for (let i = 0; i < result.length; i++) { + const group = result[i]; + const first = group.nodes[0]; + const last = group.nodes[group.nodes.length - 1]; + let name = getName(first.key, last.key); + 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 + }; + }); +}; + + +/***/ }), + +/***/ 94658: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +const path = __webpack_require__(85622); + +/** + * @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 {Object} MakeRelativePathsCache + * @property {Map>=} relativePaths + */ + +/** + * + * @param {string} maybeAbsolutePath path to check + * @returns {boolean} returns true if path is "Absolute Path"-like + */ +const looksLikeAbsolutePath = maybeAbsolutePath => { + if (/^\/.*\/$/.test(maybeAbsolutePath)) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return false; + } + return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); +}; + +/** + * + * @param {string} p path to normalize + * @returns {string} normalized version of path + */ +const normalizePathSeparator = p => p.replace(/\\/g, "/"); + +/** + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsRelative = (context, identifier) => { + return identifier + .split(/([|! ])/) + .map(str => + looksLikeAbsolutePath(str) + ? normalizePathSeparator(path.relative(context, str)) + : str + ) + .join(""); +}; + +/** + * + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @param {MakeRelativePathsCache=} cache the cache object being set + * @returns {string} the returned relative path + */ +exports.makePathsRelative = (context, identifier, cache) => { + if (!cache) return _makePathsRelative(context, identifier); + + const relativePaths = + cache.relativePaths || (cache.relativePaths = new Map()); + + let cachedResult; + let contextCache = relativePaths.get(context); + if (contextCache === undefined) { + relativePaths.set(context, (contextCache = new Map())); + } else { + cachedResult = contextCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } else { + const relativePath = _makePathsRelative(context, identifier); + contextCache.set(identifier, relativePath); + return relativePath; + } +}; + +/** + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible + */ +exports.contextify = (context, request) => { + return request + .split("!") + .map(r => { + const splitPath = r.split("?", 2); + if (/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = path.win32.relative(context, splitPath[0]); + if (!/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = splitPath[0].replace(/\\/g, "/"); + } + } + if (/^\//.test(splitPath[0])) { + splitPath[0] = path.posix.relative(context, splitPath[0]); + } + if (!/^(\.\.\/|\/|[a-zA-Z]:\\)/.test(splitPath[0])) { + splitPath[0] = "./" + splitPath[0]; + } + return splitPath.join("?"); + }) + .join("!"); +}; + +/** + * @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("!"); +}; + +exports.absolutify = _absolutify; + + +/***/ }), + +/***/ 1111: +/***/ ((module) => { + +/** + * convert an object into its 2D array equivalent to be turned + * into an ES6 map + * + * @param {object} obj any object type that works with Object.keys() + * @returns {Map} an ES6 Map of KV pairs + */ +module.exports = function objectToMap(obj) { + return new Map( + Object.keys(obj).map(key => { + /** @type {[string, string]} */ + const pair = [key, obj[key]]; + return pair; + }) + ); +}; + + +/***/ }), + +/***/ 68935: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ + + +const Ajv = __webpack_require__(21414); +const ajv = new Ajv({ + errorDataPath: "configuration", + allErrors: true, + verbose: true +}); +__webpack_require__(82133)(ajv, ["instanceof"]); +__webpack_require__(51613)(ajv); + +const validateSchema = (schema, options) => { + if (Array.isArray(options)) { + const errors = options.map(options => validateObject(schema, options)); + errors.forEach((list, idx) => { + const applyPrefix = err => { + err.dataPath = `[${idx}]${err.dataPath}`; + if (err.children) { + err.children.forEach(applyPrefix); + } + }; + list.forEach(applyPrefix); + }); + return errors.reduce((arr, items) => { + return arr.concat(items); + }, []); + } else { + return validateObject(schema, options); + } +}; + +const validateObject = (schema, options) => { + const validate = ajv.compile(schema); + const valid = validate(options); + return valid ? [] : filterErrors(validate.errors); +}; + +const filterErrors = errors => { + let newErrors = []; + for (const err of errors) { + const dataPath = err.dataPath; + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.dataPath.includes(dataPath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); + } + oldError.children = undefined; + children.push(oldError); + return false; + } + return true; + }); + if (children.length) { + err.children = children; + } + newErrors.push(err); + } + + return newErrors; +}; + +module.exports = validateSchema; + + +/***/ }), + +/***/ 43101: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + +const WebpackError = __webpack_require__(97391); + +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 10557: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + +const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); + +class WasmFinalizeExportsPlugin { + 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; + } + + for (const reason of module.reasons) { + // 2. is referenced by a non-WebAssembly module + if (reason.module.type.startsWith("webassembly") === false) { + const ref = compilation.getDependencyReference( + reason.module, + reason.dependency + ); + + if (!ref) continue; + + const importedNames = ref.importedNames; + + if (Array.isArray(importedNames)) { + importedNames.forEach(name => { + // 3. and uses a func with an incompatible JS signature + if ( + Object.prototype.hasOwnProperty.call( + jsIncompatibleExports, + name + ) + ) { + // 4. error + /** @type {any} */ + const error = new UnsupportedWebAssemblyFeatureError( + `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies` + ); + error.module = module; + error.origin = reason.module; + error.originLoc = reason.dependency.loc; + error.dependencies = [reason.dependency]; + compilation.errors.push(error); + } + }); + } + } + } + } + } + } + ); + }); + } +} + +module.exports = WasmFinalizeExportsPlugin; + + +/***/ }), + +/***/ 65331: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); +const WebAssemblyUtils = __webpack_require__(52136); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../MainTemplate")} MainTemplate */ + +// Get all wasm modules +const getAllWasmModules = chunk => { + const wasmModules = chunk.getAllAsyncChunks(); + const array = []; + for (const chunk of wasmModules) { + for (const m of chunk.modulesIterable) { + if (m.type.startsWith("webassembly")) { + array.push(m); + } + } + } + + return array; +}; + +/** + * generates the import object function for a module + * @param {Module} module the module + * @param {boolean} mangle mangle imports + * @returns {string} source code + */ +const generateImportObject = (module, mangle) => { + const waitForInstances = new Map(); + const properties = []; + const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( + module, + mangle + ); + for (const usedDep of usedWasmDependencies) { + const dep = usedDep.dependency; + const importedModule = dep.module; + const exportName = dep.name; + const usedName = importedModule && importedModule.isUsed(exportName); + 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, importedModule.id); + properties.push({ + module, + name, + value: `${instanceVar}[${JSON.stringify(usedName)}]` + }); + } else { + const params = description.signature.params.map( + (param, k) => "p" + k + param.valtype + ); + + const mod = `installedModules[${JSON.stringify(importedModule.id)}]`; + const func = `${mod}.exports[${JSON.stringify(usedName)}]`; + + properties.push({ + module, + name, + value: Template.asString([ + (importedModule.type.startsWith("webassembly") + ? `${mod} ? ${func} : ` + : "") + `function(${params}) {`, + Template.indent([`return ${func}(${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") + ]), + "};" + ]; + } + + 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([ + `${JSON.stringify(module.id)}: 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([ + `${JSON.stringify(module.id)}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, + Template.indent([`var ${variables};`, ...importObject]), + "});" + ]), + "}," + ]); + } else { + return Template.asString([ + `${JSON.stringify(module.id)}: function() {`, + Template.indent(importObject), + "}," + ]); + } +}; + +class WasmMainTemplatePlugin { + constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + } + + /** + * @param {MainTemplate} mainTemplate main template + * @returns {void} + */ + apply(mainTemplate) { + mainTemplate.hooks.localVars.tap( + "WasmMainTemplatePlugin", + (source, chunk) => { + const wasmModules = getAllWasmModules(chunk); + if (wasmModules.length === 0) return source; + const importObjects = wasmModules.map(module => { + return generateImportObject(module, this.mangleImports); + }); + return Template.asString([ + source, + "", + "// object to store loaded and loading wasm modules", + "var installedWasmModules = {};", + "", + // This function is used to delay reading the installed wasm module promises + // by a microtask. Sorting them doesn't help because there are egdecases 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(); }", + "", + "var wasmImportObjects = {", + Template.indent(importObjects), + "};" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + "WasmMainTemplatePlugin", + (source, chunk, hash) => { + const webassemblyModuleFilename = + mainTemplate.outputOptions.webassemblyModuleFilename; + + const chunkModuleMaps = chunk.getChunkModuleMaps(m => + m.type.startsWith("webassembly") + ); + if (Object.keys(chunkModuleMaps.id).length === 0) return source; + const wasmModuleSrcPath = mainTemplate.getAssetPath( + JSON.stringify(webassemblyModuleFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + ${JSON.stringify( + chunkModuleMaps.hash + )}[wasmModuleId] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { + if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") { + shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ + wasmModuleId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[wasmModuleId] + "`; + } + } + } + ); + const createImportObject = content => + this.mangleImports + ? `{ ${JSON.stringify( + WebAssemblyUtils.MANGLED_MODULE + )}: ${content} }` + : content; + return Template.asString([ + source, + "", + "// Fetch + compile chunk loading for webassembly", + "", + `var wasmModules = ${JSON.stringify( + chunkModuleMaps.id + )}[chunkId] || [];`, + "", + "wasmModules.forEach(function(wasmModuleId) {", + 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 instanceof Promise && 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 instanceof Promise) {", + 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 ${mainTemplate.requireFn}.w[wasmModuleId] = (res.instance || res).exports;` + ]), + "}));" + ]), + "}" + ]), + "});" + ]); + } + ); + mainTemplate.hooks.requireExtensions.tap( + "WasmMainTemplatePlugin", + (source, chunk) => { + if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) { + return source; + } + return Template.asString([ + source, + "", + "// object with all WebAssembly.instance exports", + `${mainTemplate.requireFn}.w = {};` + ]); + } + ); + mainTemplate.hooks.hash.tap("WasmMainTemplatePlugin", hash => { + hash.update("WasmMainTemplatePlugin"); + hash.update("2"); + }); + } +} + +module.exports = WasmMainTemplatePlugin; + + +/***/ }), + +/***/ 13099: +/***/ ((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__(39172); +const Template = __webpack_require__(96066); +const WebAssemblyUtils = __webpack_require__(52136); +const { RawSource } = __webpack_require__(53665); + +const { editWithAST, addWithAST } = __webpack_require__(65584); +const { decode } = __webpack_require__(8062); +const t = __webpack_require__(98688); +const { + moduleContextFromModuleAST +} = __webpack_require__(71234); + +const WebAssemblyExportImportedDependency = __webpack_require__(18925); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ + +/** + * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform + */ + +/** + * @template T + * @param {Function[]} fns transforms + * @returns {Function} composed transform + */ +const compose = (...fns) => { + return fns.reduce( + (prevFn, nextFn) => { + return value => nextFn(prevFn(value)); + }, + value => value + ); +}; + +// TODO replace with @callback + +/** + * Removes the start instruction + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform + */ +const removeStartFunc = state => bin => { + return editWithAST(state.ast, bin, { + Start(path) { + path.remove(); + } + }); +}; + +/** + * Get imported globals + * + * @param {Object} ast Module's AST + * @returns {Array} - nodes + */ +const getImportedGlobals = ast => { + const importedGlobals = []; + + 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; + + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; + } + } + }); + + 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); + } + + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; + +/** + * 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 + */ +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); + + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); + } + + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; + + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; + +/** + * 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); + } +}; + +/** + * 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 = []; + + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = path.node.descr; + + globalType.mutability = "var"; + + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; + + newGlobals.push(t.global(globalType, init)); + + path.remove(); + } + }, + + // 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]; + + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; + + 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); +}; + +/** + * Rewrite the export names + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Module} state.module Module + * @param {Set} state.externalExports Module + * @returns {ArrayBufferTransform} transform + */ +const rewriteExportNames = ({ ast, module, externalExports }) => bin => { + return editWithAST(ast, bin, { + ModuleExport(path) { + const isExternal = externalExports.has(path.node.name); + if (isExternal) { + path.remove(); + return; + } + const usedName = module.isUsed(path.node.name); + 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 + ); + + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } + } + }); +}; + +/** + * 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}`); + + return t.funcParam(importedGlobal.descr.valtype, id); + }); + + const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => { + const args = [t.indexLiteral(index)]; + const body = [ + t.instruction("get_local", args), + t.instruction("set_global", args) + ]; + + return [...acc, ...body]; + }, []); + + if (typeof startAtFuncOffset === "number") { + funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))); + } + + for (const instr of additionalInitCode) { + funcBody.push(instr); + } + + 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); + + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); + + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); +}; + +/** + * Extract mangle mappings from module + * @param {Module} module current module + * @param {boolean} mangle mangle imports + * @returns {Map} mappings to mangled names + */ +const getUsedDependencyMap = (module, mangle) => { + /** @type {Map} */ + const map = new Map(); + for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) { + const dep = usedDep.dependency; + const request = dep.request; + const exportName = dep.name; + map.set(request + ":" + exportName, usedDep); + } + return map; +}; + +class WebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + let bin = module.originalSource().source(); + + const initFuncId = t.identifier( + Array.isArray(module.usedExports) + ? Template.numberToIdentifer(module.usedExports.length) + : "__webpack_init__" + ); + + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); + + const moduleContext = moduleContextFromModuleAST(ast.body[0]); + + const importedGlobals = getImportedGlobals(ast); + const countImportedFunc = getCountImportedFunc(ast); + const startAtFuncOffset = moduleContext.getStart(); + const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); + const nextTypeIndex = getNextTypeIndex(ast); + + const usedDependencyMap = getUsedDependencyMap( + 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, + module, + externalExports + }), + + removeStartFunc({ ast }), + + rewriteImportedGlobals({ ast, additionalInitCode }), + + rewriteImports({ + ast, + usedDependencyMap + }), + + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); + + const newBin = transform(bin); + + return new RawSource(newBin); + } +} + +module.exports = WebAssemblyGenerator; + + +/***/ }), + +/***/ 45283: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + +const WebpackError = __webpack_require__(97391); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../RequestShortener")} RequestShortener */ + +/** + * @param {Module} module module to get chains from + * @param {RequestShortener} requestShortener to make readable identifiers + * @returns {string[]} all chains to the module + */ +const getInitialModuleChains = (module, 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(); + + for (const chain of queue) { + const { head, message } = chain; + let final = true; + /** @type {Set} */ + const alreadyReferencedModules = new Set(); + for (const reason of head.reasons) { + const newHead = reason.module; + if (newHead) { + if (!newHead.getChunks().some(c => c.canBeInitial())) continue; + final = false; + if (alreadyReferencedModules.has(newHead)) continue; + alreadyReferencedModules.add(newHead); + const moduleName = newHead.readableIdentifier(requestShortener); + const detail = reason.explanation ? ` (${reason.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 = reason.explanation + ? `(${reason.explanation}) --> ${message}` + : message; + results.add(newMessage); + } + } + 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 {RequestShortener} requestShortener request shortener + */ + constructor(module, requestShortener) { + const moduleChains = getInitialModuleChains(module, 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 splitpoint (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; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 13411: +/***/ ((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__(39172); +const Template = __webpack_require__(96066); +const { RawSource } = __webpack_require__(53665); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); + +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ + +class WebAssemblyJavascriptGenerator extends Generator { + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + const initIdentifer = Array.isArray(module.usedExports) + ? Template.numberToIdentifer(module.usedExports.length) + : "__webpack_init__"; + + let needExportsCopy = false; + const importedModules = new Map(); + const initParams = []; + let index = 0; + for (const dep of module.dependencies) { + const depAsAny = /** @type {any} */ (dep); + if (dep.module) { + let importData = importedModules.get(dep.module); + if (importData === undefined) { + importedModules.set( + dep.module, + (importData = { + importVar: `m${index}`, + index, + request: + "userRequest" in depAsAny ? depAsAny.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 usedName = dep.module && dep.module.isUsed(exportName); + + if (dep.module) { + if (usedName) { + initParams.push( + runtimeTemplate.exportFromImport({ + module: dep.module, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null + }) + ); + } + } + } + } + if (dep instanceof WebAssemblyExportImportedDependency) { + importData.names.add(dep.name); + const usedName = module.isUsed(dep.exportName); + if (usedName) { + const exportProp = `${module.exportsArgument}[${JSON.stringify( + usedName + )}]`; + const defineStatement = Template.asString([ + `${exportProp} = ${runtimeTemplate.exportFromImport({ + module: dep.module, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null + })};`, + `if(WebAssembly.Global) ${exportProp} = ` + + `new WebAssembly.Global({ value: ${JSON.stringify( + dep.valueType + )} }, ${exportProp});` + ]); + importData.reexports.push(defineStatement); + needExportsCopy = true; + } + } + } + } + const importsCode = Template.asString( + Array.from( + importedModules, + ([module, { importVar, request, reexports }]) => { + const importStatement = runtimeTemplate.importStatement({ + module, + request, + importVar, + originModule: module + }); + return importStatement + reexports.join("\n"); + } + ) + ); + + // create source + const source = new RawSource( + [ + '"use strict";', + "// Instantiate WebAssembly module", + "var wasmExports = __webpack_require__.w[module.i];", + + !Array.isArray(module.usedExports) + ? `__webpack_require__.r(${module.exportsArgument});` + : "", + + // this must be before import for circular dependencies + "// export exports from WebAssembly module", + Array.isArray(module.usedExports) && !needExportsCopy + ? `${module.moduleArgument}.exports = wasmExports;` + : "for(var name in wasmExports) " + + `if(name != ${JSON.stringify(initIdentifer)}) ` + + `${module.exportsArgument}[name] = wasmExports[name];`, + "// exec imports from WebAssembly module (for esm order)", + importsCode, + "", + "// exec wasm module", + `wasmExports[${JSON.stringify(initIdentifer)}](${initParams.join( + ", " + )})` + ].join("\n") + ); + return source; + } +} + +module.exports = WebAssemblyJavascriptGenerator; + + +/***/ }), + +/***/ 99510: +/***/ ((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__(39172); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyInInitialChunkError = __webpack_require__(45283); + +/** @typedef {import("../Compiler")} Compiler */ + +let WebAssemblyGenerator; +let WebAssemblyJavascriptGenerator; +let WebAssemblyParser; + +class WebAssemblyModulesPlugin { + constructor(options) { + this.options = options; + } + + /** + * @param {Compiler} compiler compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "WebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + WebAssemblyExportImportedDependency, + normalModuleFactory + ); + + normalModuleFactory.hooks.createParser + .for("webassembly/experimental") + .tap("WebAssemblyModulesPlugin", () => { + if (WebAssemblyParser === undefined) { + WebAssemblyParser = __webpack_require__(77703); + } + return new WebAssemblyParser(); + }); + + normalModuleFactory.hooks.createGenerator + .for("webassembly/experimental") + .tap("WebAssemblyModulesPlugin", () => { + if (WebAssemblyGenerator === undefined) { + WebAssemblyGenerator = __webpack_require__(13099); + } + if (WebAssemblyJavascriptGenerator === undefined) { + WebAssemblyJavascriptGenerator = __webpack_require__(13411); + } + return Generator.byType({ + javascript: new WebAssemblyJavascriptGenerator(), + webassembly: new WebAssemblyGenerator(this.options) + }); + }); + + compilation.chunkTemplate.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; + + for (const module of chunk.modulesIterable) { + if (module.type && module.type.startsWith("webassembly")) { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; + + result.push({ + render: () => + this.renderWebAssembly( + module, + moduleTemplates.webassembly, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + module + }, + identifier: `webassemblyModule${module.id}`, + hash: module.hash + }); + } + } + + return result; + } + ); + + compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { + const initialWasmModules = new Set(); + for (const chunk of compilation.chunks) { + if (chunk.canBeInitial()) { + for (const module of chunk.modulesIterable) { + if (module.type.startsWith("webassembly")) { + initialWasmModules.add(module); + } + } + } + } + for (const module of initialWasmModules) { + compilation.errors.push( + new WebAssemblyInInitialChunkError( + module, + compilation.requestShortener + ) + ); + } + }); + } + ); + } + + renderWebAssembly(module, moduleTemplate, dependencyTemplates) { + return moduleTemplate.render(module, dependencyTemplates, {}); + } +} + +module.exports = WebAssemblyModulesPlugin; + + +/***/ }), + +/***/ 77703: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const t = __webpack_require__(98688); +const { decode } = __webpack_require__(8062); +const { + moduleContextFromModuleAST +} = __webpack_require__(71234); + +const { Tapable } = __webpack_require__(92402); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); + +/** @typedef {import("../Module")} Module */ + +const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); + +/** + * @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; +}; + +/** + * 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; +}; + +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Tapable { + constructor(options) { + super(); + this.hooks = {}; + this.options = options; + } + + parse(binary, state) { + // flag it as ESM + state.module.buildMeta.exportsType = "namespace"; + + // parse it + const program = decode(binary, decoderOpts); + const module = program.body[0]; + + const moduleContext = moduleContextFromModuleAST(module); + + // extract imports and exports + const exports = (state.module.buildMeta.providedExports = []); + const jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = []); + + 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) { + 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 Sigurature (${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 + ); + + state.module.addDependency(dep); + + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + + return state; + } +} + +module.exports = WebAssemblyParser; + + +/***/ }), + +/***/ 52136: +/***/ ((__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__(96066); +const WebAssemblyImportDependency = __webpack_require__(52959); + +/** @typedef {import("../Module")} Module */ + +/** @typedef {Object} UsedWasmDependency + * @property {WebAssemblyImportDependency} dependency the dependency + * @property {string} name the export name + * @property {string} module the module name + */ + +const MANGLED_MODULE = "a"; + +/** + * @param {Module} module the module + * @param {boolean} mangle mangle module and export names + * @returns {UsedWasmDependency[]} used dependencies and (mangled) name + */ +const getUsedDependencies = (module, mangle) => { + /** @type {UsedWasmDependency[]} */ + const array = []; + let importIndex = 0; + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + if (dep.description.type === "GlobalType" || dep.module === null) { + continue; + } + + const exportName = dep.name; + // TODO add the following 3 lines when removing of ModuleExport is possible + // const importedModule = dep.module; + // const usedName = importedModule && importedModule.isUsed(exportName); + // if (usedName !== false) { + if (mangle) { + array.push({ + dependency: dep, + name: Template.numberToIdentifer(importIndex++), + module: MANGLED_MODULE + }); + } else { + array.push({ + dependency: dep, + name: exportName, + module: dep.request + }); + } + } + } + return array; +}; + +exports.getUsedDependencies = getUsedDependencies; +exports.MANGLED_MODULE = MANGLED_MODULE; + + +/***/ }), + +/***/ 52669: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const WasmMainTemplatePlugin = __webpack_require__(65331); + +class FetchCompileWasmTemplatePlugin { + constructor(options) { + this.options = options || {}; + } + + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileWasmTemplatePlugin", + compilation => { + const mainTemplate = compilation.mainTemplate; + const generateLoadBinaryCode = path => + `fetch(${mainTemplate.requireFn}.p + ${path})`; + + const plugin = new WasmMainTemplatePlugin( + Object.assign( + { + generateLoadBinaryCode, + supportsStreaming: true + }, + this.options + ) + ); + plugin.apply(mainTemplate); + } + ); + } +} + +module.exports = FetchCompileWasmTemplatePlugin; + + +/***/ }), + +/***/ 31898: +/***/ ((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__(53665); + +/** @typedef {import("../ChunkTemplate")} ChunkTemplate */ + +const getEntryInfo = chunk => { + return [chunk.entryModule].filter(Boolean).map(m => + [m.id].concat( + Array.from(chunk.groupsIterable)[0] + .chunks.filter(c => c !== chunk) + .map(c => c.id) + ) + ); +}; + +class JsonpChunkTemplatePlugin { + /** + * @param {ChunkTemplate} chunkTemplate the chunk template + * @returns {void} + */ + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "JsonpChunkTemplatePlugin", + (modules, chunk) => { + const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction; + const globalObject = chunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + const prefetchChunks = chunk.getChildIdsByOrders().prefetch; + source.add( + `(${globalObject}[${JSON.stringify( + jsonpFunction + )}] = ${globalObject}[${JSON.stringify( + jsonpFunction + )}] || []).push([${JSON.stringify(chunk.ids)},` + ); + source.add(modules); + const entries = getEntryInfo(chunk); + if (entries.length > 0) { + source.add(`,${JSON.stringify(entries)}`); + } else if (prefetchChunks && prefetchChunks.length) { + source.add(`,0`); + } + + if (prefetchChunks && prefetchChunks.length) { + source.add(`,${JSON.stringify(prefetchChunks)}`); + } + source.add("])"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => { + hash.update("JsonpChunkTemplatePlugin"); + hash.update("4"); + hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`); + hash.update(`${chunkTemplate.outputOptions.globalObject}`); + }); + chunkTemplate.hooks.hashForChunk.tap( + "JsonpChunkTemplatePlugin", + (hash, chunk) => { + hash.update(JSON.stringify(getEntryInfo(chunk))); + hash.update(JSON.stringify(chunk.getChildIdsByOrders().prefetch) || ""); + } + ); + } +} +module.exports = JsonpChunkTemplatePlugin; + + +/***/ }), + +/***/ 13732: +/***/ ((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__(53665); + +class JsonpExportMainTemplatePlugin { + /** + * @param {string} name jsonp function name + */ + constructor(name) { + this.name = name; + } + + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const name = mainTemplate.getAssetPath(this.name || "", { + hash, + chunk + }); + return new ConcatSource(`${name}(`, source, ");"); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "JsonpExportMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap( + "JsonpExportMainTemplatePlugin", + paths => { + if (this.name) paths.push(this.name); + return paths; + } + ); + + mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => { + hash.update("jsonp export"); + hash.update(`${this.name}`); + }); + } +} + +module.exports = JsonpExportMainTemplatePlugin; + + +/***/ }), + +/***/ 44458: +/***/ ((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__(53665); + +class JsonpHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "JsonpHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const source = new ConcatSource(); + source.add( + `${ + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + }(${JSON.stringify(id)},` + ); + source.add(modulesSource); + source.add(")"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "JsonpHotUpdateChunkTemplatePlugin", + hash => { + hash.update("JsonpHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + `${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}` + ); + hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`); + } + ); + } +} + +module.exports = JsonpHotUpdateChunkTemplatePlugin; + + +/***/ }), + +/***/ 24916: +/***/ ((module) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var hotAddUpdateChunk = undefined; +var parentHotUpdateCallback = undefined; +var $require$ = undefined; +var $hotMainFilename$ = undefined; +var $hotChunkFilename$ = undefined; +var $crossOriginLoading$ = undefined; + +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon + + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var script = document.createElement("script"); + script.charset = "utf-8"; + script.src = $require$.p + $hotChunkFilename$; + if ($crossOriginLoading$) script.crossOrigin = $crossOriginLoading$; + document.head.appendChild(script); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest(requestTimeout) { + requestTimeout = requestTimeout || 10000; + return new Promise(function(resolve, reject) { + if (typeof XMLHttpRequest === "undefined") { + return reject(new Error("No browser support")); + } + try { + var request = new XMLHttpRequest(); + var requestPath = $require$.p + $hotMainFilename$; + request.open("GET", requestPath, true); + request.timeout = requestTimeout; + request.send(null); + } catch (err) { + return reject(err); + } + request.onreadystatechange = function() { + if (request.readyState !== 4) return; + if (request.status === 0) { + // timeout + reject( + new Error("Manifest request to " + requestPath + " timed out.") + ); + } else if (request.status === 404) { + // no update available + resolve(); + } else if (request.status !== 200 && request.status !== 304) { + // other failure + reject(new Error("Manifest request to " + requestPath + " failed.")); + } else { + // success + try { + var update = JSON.parse(request.responseText); + } catch (e) { + reject(e); + return; + } + resolve(update); + } + }; + }); + } +}; + + +/***/ }), + +/***/ 38017: +/***/ ((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__(92402); +const Template = __webpack_require__(96066); + +class JsonpMainTemplatePlugin { + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + const needChunkLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + const needEntryDeferringCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + } + return false; + }; + const needPrefetchingCode = chunk => { + const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; + return allPrefetchChunks && Object.keys(allPrefetchChunks).length; + }; + + // TODO webpack 5, no adding to .hooks, use WeakMap and static methods + ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { + if (!mainTemplate.hooks[hook]) { + mainTemplate.hooks[hook] = new SyncWaterfallHook([ + "source", + "chunk", + "hash" + ]); + } + }); + + const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: `" + ${chunkIdExpression} + "`, + hash: `" + ${JSON.stringify( + chunkMaps.hash + )}[${chunkIdExpression}] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[${chunkIdExpression}] + "`; + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[${chunkIdExpression}] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[${chunkIdExpression}] + "`; + } + } + }, + contentHashType: "javascript" + }); + }; + mainTemplate.hooks.localVars.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const extraCode = []; + if (needChunkLoadingCode(chunk)) { + extraCode.push( + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// Promise = chunk loading, 0 = chunk loaded", + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};", + "", + needEntryDeferringCode(chunk) + ? needPrefetchingCode(chunk) + ? "var deferredModules = [], deferredPrefetch = [];" + : "var deferredModules = [];" + : "" + ); + } + if (needChunkOnDemandLoadingCode(chunk)) { + extraCode.push( + "", + "// script path function", + "function jsonpScriptSrc(chunkId) {", + Template.indent([ + `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( + hash, + chunk, + "chunkId" + )}` + ]), + "}" + ); + } + if (extraCode.length === 0) return source; + return Template.asString([source, ...extraCode]); + } + ); + + mainTemplate.hooks.jsonpScript.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; + const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; + + return Template.asString([ + "var script = document.createElement('script');", + "var onScriptComplete;", + jsonpScriptType + ? `script.type = ${JSON.stringify(jsonpScriptType)};` + : "", + "script.charset = 'utf-8';", + `script.timeout = ${chunkLoadTimeout / 1000};`, + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + "script.src = jsonpScriptSrc(chunkId);", + crossOriginLoading + ? Template.asString([ + "if (script.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "", + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + "onScriptComplete = function (event) {", + Template.indent([ + "// avoid mem leaks in IE.", + "script.onerror = script.onload = null;", + "clearTimeout(timeout);", + "var chunk = installedChunks[chunkId];", + "if(chunk !== 0) {", + Template.indent([ + "if(chunk) {", + 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;", + "chunk[1](error);" + ]), + "}", + "installedChunks[chunkId] = undefined;" + ]), + "}" + ]), + "};", + "var timeout = setTimeout(function(){", + Template.indent([ + "onScriptComplete({ type: 'timeout', target: script });" + ]), + `}, ${chunkLoadTimeout});`, + "script.onerror = script.onload = onScriptComplete;" + ]); + } + ); + mainTemplate.hooks.linkPreload.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; + + return Template.asString([ + "var link = document.createElement('link');", + jsonpScriptType + ? `link.type = ${JSON.stringify(jsonpScriptType)};` + : "", + "link.charset = 'utf-8';", + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + 'link.rel = "preload";', + 'link.as = "script";', + "link.href = jsonpScriptSrc(chunkId);", + crossOriginLoading + ? Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); + } + ); + mainTemplate.hooks.linkPrefetch.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + + return Template.asString([ + "var link = document.createElement('link');", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + : "", + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + "link.href = jsonpScriptSrc(chunkId);" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + "JsonpMainTemplatePlugin load", + (source, chunk, hash) => { + return Template.asString([ + source, + "", + "// JSONP chunk loading for javascript", + "", + "var installedChunkData = installedChunks[chunkId];", + '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([ + "// setup Promise in chunk cache", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];" + ]), + "});", + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + mainTemplate.hooks.jsonpScript.call("", chunk, hash), + "document.head.appendChild(script);" + ]), + "}" + ]), + "}" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + { + name: "JsonpMainTemplatePlugin preload", + stage: 10 + }, + (source, chunk, hash) => { + const chunkMap = chunk.getChildIdsByOrdersMap().preload; + if (!chunkMap || Object.keys(chunkMap).length === 0) return source; + return Template.asString([ + source, + "", + "// chunk preloadng for javascript", + "", + `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, + "", + "var chunkPreloadData = chunkPreloadMap[chunkId];", + "if(chunkPreloadData) {", + Template.indent([ + "chunkPreloadData.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPreload.call("", chunk, hash), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});" + ]), + "}" + ]); + } + ); + mainTemplate.hooks.requireExtensions.tap( + "JsonpMainTemplatePlugin", + (source, chunk) => { + if (!needChunkOnDemandLoadingCode(chunk)) return source; + + return Template.asString([ + source, + "", + "// on error function for async loading", + `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };` + ]); + } + ); + mainTemplate.hooks.bootstrap.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkLoadingCode(chunk)) { + const withDefer = needEntryDeferringCode(chunk); + const withPrefetch = needPrefetchingCode(chunk); + return Template.asString([ + source, + "", + "// install a JSONP callback for chunk loading", + "function webpackJsonpCallback(data) {", + Template.indent([ + "var chunkIds = data[0];", + "var moreModules = data[1];", + withDefer ? "var executeModules = data[2];" : "", + withPrefetch ? "var prefetchChunks = data[3] || [];" : "", + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0, resolves = [];", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + "if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {", + Template.indent("resolves.push(installedChunks[chunkId][0]);"), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + "for(moduleId in moreModules) {", + Template.indent([ + "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}" + ]), + "}", + "if(parentJsonpFunction) parentJsonpFunction(data);", + withPrefetch + ? withDefer + ? "deferredPrefetch.push.apply(deferredPrefetch, prefetchChunks);" + : Template.asString([ + "// chunk prefetching for javascript", + "prefetchChunks.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPrefetch.call("", chunk, hash), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});" + ]) + : "", + "while(resolves.length) {", + Template.indent("resolves.shift()();"), + "}", + withDefer + ? Template.asString([ + "", + "// add entry modules from loaded chunk to deferred list", + "deferredModules.push.apply(deferredModules, executeModules || []);", + "", + "// run deferred modules when all chunks ready", + "return checkDeferredModules();" + ]) + : "" + ]), + "};", + withDefer + ? Template.asString([ + "function checkDeferredModules() {", + Template.indent([ + "var result;", + "for(var i = 0; i < deferredModules.length; i++) {", + Template.indent([ + "var deferredModule = deferredModules[i];", + "var fulfilled = true;", + "for(var j = 1; j < deferredModule.length; j++) {", + Template.indent([ + "var depId = deferredModule[j];", + "if(installedChunks[depId] !== 0) fulfilled = false;" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferredModules.splice(i--, 1);", + "result = " + + mainTemplate.requireFn + + "(" + + mainTemplate.requireFn + + ".s = deferredModule[0]);" + ]), + "}" + ]), + "}", + withPrefetch + ? Template.asString([ + "if(deferredModules.length === 0) {", + Template.indent([ + "// chunk prefetching for javascript", + "deferredPrefetch.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPrefetch.call( + "", + chunk, + hash + ), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});", + "deferredPrefetch.length = 0;" + ]), + "}" + ]) + : "", + "return result;" + ]), + "}" + ]) + : "" + ]); + } + return source; + } + ); + mainTemplate.hooks.beforeStartup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkLoadingCode(chunk)) { + var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; + var globalObject = mainTemplate.outputOptions.globalObject; + return Template.asString([ + `var jsonpArray = ${globalObject}[${JSON.stringify( + jsonpFunction + )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, + "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", + "jsonpArray.push = webpackJsonpCallback;", + "jsonpArray = jsonpArray.slice();", + "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", + "var parentJsonpFunction = oldJsonpFunction;", + "", + source + ]); + } + return source; + } + ); + mainTemplate.hooks.afterStartup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const prefetchChunks = chunk.getChildIdsByOrders().prefetch; + if ( + needChunkLoadingCode(chunk) && + prefetchChunks && + prefetchChunks.length + ) { + return Template.asString([ + source, + `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( + prefetchChunks + )}]);` + ]); + } + return source; + } + ); + mainTemplate.hooks.startup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needEntryDeferringCode(chunk)) { + if (chunk.hasEntryModule()) { + const entries = [chunk.entryModule].filter(Boolean).map(m => + [m.id].concat( + Array.from(chunk.groupsIterable)[0] + .chunks.filter(c => c !== chunk) + .map(c => c.id) + ) + ); + return Template.asString([ + "// add entry module to deferred list", + `deferredModules.push(${entries + .map(e => JSON.stringify(e)) + .join(", ")});`, + "// run deferred modules when ready", + "return checkDeferredModules();" + ]); + } else { + return Template.asString([ + "// run deferred modules from other chunks", + "checkDeferredModules();" + ]); + } + } + return source; + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const globalObject = mainTemplate.outputOptions.globalObject; + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "' + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + const runtimeSource = Template.getFunctionContent( + __webpack_require__(24916) + ) + .replace(/\/\/\$semicolon/g, ";") + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace( + /\$crossOriginLoading\$/g, + crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" + ) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) + .replace(/\$hash\$/g, JSON.stringify(hash)); + return `${source} +function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; +} +var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( + hotUpdateFunction + )}]; +${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; + } + ); + mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { + hash.update("jsonp"); + hash.update("6"); + }); + } +} +module.exports = JsonpMainTemplatePlugin; + + +/***/ }), + +/***/ 92764: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const JsonpMainTemplatePlugin = __webpack_require__(38017); +const JsonpChunkTemplatePlugin = __webpack_require__(31898); +const JsonpHotUpdateChunkTemplatePlugin = __webpack_require__(44458); + +class JsonpTemplatePlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap("JsonpTemplatePlugin", compilation => { + new JsonpMainTemplatePlugin().apply(compilation.mainTemplate); + new JsonpChunkTemplatePlugin().apply(compilation.chunkTemplate); + new JsonpHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + }); + } +} + +module.exports = JsonpTemplatePlugin; + + +/***/ }), + +/***/ 92929: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Compiler = __webpack_require__(58705); +const MultiCompiler = __webpack_require__(10238); +const NodeEnvironmentPlugin = __webpack_require__(52520); +const WebpackOptionsApply = __webpack_require__(2779); +const WebpackOptionsDefaulter = __webpack_require__(60016); +const validateSchema = __webpack_require__(68935); +const WebpackOptionsValidationError = __webpack_require__(285); +const webpackOptionsSchema = __webpack_require__(37863); +const RemovedPluginError = __webpack_require__(15377); +const version = __webpack_require__(71618)/* .version */ .i8; + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ + +/** + * @param {WebpackOptions} options options object + * @param {function(Error=, Stats=): void=} callback callback + * @returns {Compiler | MultiCompiler} the compiler object + */ +const webpack = (options, callback) => { + const webpackOptionsValidationErrors = validateSchema( + webpackOptionsSchema, + options + ); + if (webpackOptionsValidationErrors.length) { + throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); + } + let compiler; + if (Array.isArray(options)) { + compiler = new MultiCompiler( + Array.from(options).map(options => webpack(options)) + ); + } else if (typeof options === "object") { + options = new WebpackOptionsDefaulter().process(options); + + compiler = new Compiler(options.context); + compiler.options = options; + new NodeEnvironmentPlugin({ + infrastructureLogging: options.infrastructureLogging + }).apply(compiler); + if (options.plugins && Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + if (typeof plugin === "function") { + plugin.call(compiler, compiler); + } else { + plugin.apply(compiler); + } + } + } + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + compiler.options = new WebpackOptionsApply().process(options, compiler); + } else { + throw new Error("Invalid argument: options"); + } + if (callback) { + if (typeof callback !== "function") { + throw new Error("Invalid argument: callback"); + } + if ( + options.watch === true || + (Array.isArray(options) && options.some(o => o.watch)) + ) { + const watchOptions = Array.isArray(options) + ? options.map(o => o.watchOptions || {}) + : options.watchOptions || {}; + return compiler.watch(watchOptions, callback); + } + compiler.run(callback); + } + return compiler; +}; + +exports = module.exports = webpack; +exports.version = version; + +webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; +webpack.WebpackOptionsApply = WebpackOptionsApply; +webpack.Compiler = Compiler; +webpack.MultiCompiler = MultiCompiler; +webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; +// @ts-ignore Global @this directive is not supported +webpack.validate = validateSchema.bind(this, webpackOptionsSchema); +webpack.validateSchema = validateSchema; +webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; + +const exportPlugins = (obj, mappings) => { + for (const name of Object.keys(mappings)) { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: mappings[name] + }); + } +}; + +exportPlugins(exports, { + AutomaticPrefetchPlugin: () => __webpack_require__(51596), + BannerPlugin: () => __webpack_require__(4009), + CachePlugin: () => __webpack_require__(6465), + ContextExclusionPlugin: () => __webpack_require__(10706), + ContextReplacementPlugin: () => __webpack_require__(27295), + DefinePlugin: () => __webpack_require__(97374), + Dependency: () => __webpack_require__(57282), + DllPlugin: () => __webpack_require__(45255), + DllReferencePlugin: () => __webpack_require__(86231), + EnvironmentPlugin: () => __webpack_require__(6098), + EvalDevToolModulePlugin: () => __webpack_require__(65200), + EvalSourceMapDevToolPlugin: () => __webpack_require__(99994), + ExtendedAPIPlugin: () => __webpack_require__(17270), + ExternalsPlugin: () => __webpack_require__(75705), + HashedModuleIdsPlugin: () => __webpack_require__(50268), + HotModuleReplacementPlugin: () => __webpack_require__(69575), + IgnorePlugin: () => __webpack_require__(41364), + LibraryTemplatePlugin: () => __webpack_require__(65237), + LoaderOptionsPlugin: () => __webpack_require__(48775), + LoaderTargetPlugin: () => __webpack_require__(95154), + MemoryOutputFileSystem: () => __webpack_require__(50332), + Module: () => __webpack_require__(75993), + ModuleFilenameHelpers: () => __webpack_require__(71474), + NamedChunksPlugin: () => __webpack_require__(70419), + NamedModulesPlugin: () => __webpack_require__(86707), + NoEmitOnErrorsPlugin: () => __webpack_require__(22615), + NormalModuleReplacementPlugin: () => + __webpack_require__(73253), + PrefetchPlugin: () => __webpack_require__(27850), + ProgressPlugin: () => __webpack_require__(63123), + ProvidePlugin: () => __webpack_require__(72861), + SetVarMainTemplatePlugin: () => __webpack_require__(37098), + SingleEntryPlugin: () => __webpack_require__(19070), + SourceMapDevToolPlugin: () => __webpack_require__(11851), + Stats: () => __webpack_require__(99977), + Template: () => __webpack_require__(96066), + UmdMainTemplatePlugin: () => __webpack_require__(75374), + WatchIgnorePlugin: () => __webpack_require__(88015) +}); +exportPlugins((exports.dependencies = {}), { + DependencyReference: () => __webpack_require__(71722) +}); +exportPlugins((exports.optimize = {}), { + AggressiveMergingPlugin: () => __webpack_require__(88197), + AggressiveSplittingPlugin: () => + __webpack_require__(26688), + ChunkModuleIdRangePlugin: () => + __webpack_require__(30346), + LimitChunkCountPlugin: () => __webpack_require__(3846), + MinChunkSizePlugin: () => __webpack_require__(55607), + ModuleConcatenationPlugin: () => + __webpack_require__(45184), + OccurrenceOrderPlugin: () => __webpack_require__(67340), + OccurrenceModuleOrderPlugin: () => + __webpack_require__(62000), + OccurrenceChunkOrderPlugin: () => + __webpack_require__(83741), + RuntimeChunkPlugin: () => __webpack_require__(76894), + SideEffectsFlagPlugin: () => __webpack_require__(83654), + SplitChunksPlugin: () => __webpack_require__(60474) +}); +exportPlugins((exports.web = {}), { + FetchCompileWasmTemplatePlugin: () => + __webpack_require__(52669), + JsonpTemplatePlugin: () => __webpack_require__(92764) +}); +exportPlugins((exports.webworker = {}), { + WebWorkerTemplatePlugin: () => __webpack_require__(21328) +}); +exportPlugins((exports.node = {}), { + NodeTemplatePlugin: () => __webpack_require__(90010), + ReadFileCompileWasmTemplatePlugin: () => + __webpack_require__(73839) +}); +exportPlugins((exports.debug = {}), { + ProfilingPlugin: () => __webpack_require__(72890) +}); +exportPlugins((exports.util = {}), { + createHash: () => __webpack_require__(15660) +}); + +const defineMissingPluginError = (namespace, pluginName, errorMessage) => { + Object.defineProperty(namespace, pluginName, { + configurable: false, + enumerable: true, + get() { + throw new RemovedPluginError(errorMessage); + } + }); +}; + +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "UglifyJsPlugin", + "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." +); + +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "CommonsChunkPlugin", + "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." +); + + +/***/ }), + +/***/ 37919: +/***/ ((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__(53665); + +class WebWorkerChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "WebWorkerChunkTemplatePlugin", + (modules, chunk) => { + const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName; + const globalObject = chunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}](${JSON.stringify(chunk.ids)},` + ); + source.add(modules); + source.add(")"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("WebWorkerChunkTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("3"); + hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`); + hash.update(`${chunkTemplate.outputOptions.globalObject}`); + }); + } +} +module.exports = WebWorkerChunkTemplatePlugin; + + +/***/ }), + +/***/ 45493: +/***/ ((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__(53665); + +class WebWorkerHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const hotUpdateFunction = + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction; + const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + hotUpdateFunction + )}](${JSON.stringify(id)},` + ); + source.add(modulesSource); + source.add(")"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + hash => { + hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.globalObject + ""); + } + ); + } +} +module.exports = WebWorkerHotUpdateChunkTemplatePlugin; + + +/***/ }), + +/***/ 72337: +/***/ ((module) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var hotAddUpdateChunk = undefined; +var parentHotUpdateCallback = undefined; +var $require$ = undefined; +var $hotChunkFilename$ = undefined; +var $hotMainFilename$ = undefined; +var installedChunks = undefined; +var importScripts = undefined; + +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon + + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + importScripts($require$.p + $hotChunkFilename$); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest(requestTimeout) { + requestTimeout = requestTimeout || 10000; + return new Promise(function(resolve, reject) { + if (typeof XMLHttpRequest === "undefined") { + return reject(new Error("No browser support")); + } + try { + var request = new XMLHttpRequest(); + var requestPath = $require$.p + $hotMainFilename$; + request.open("GET", requestPath, true); + request.timeout = requestTimeout; + request.send(null); + } catch (err) { + return reject(err); + } + request.onreadystatechange = function() { + if (request.readyState !== 4) return; + if (request.status === 0) { + // timeout + reject( + new Error("Manifest request to " + requestPath + " timed out.") + ); + } else if (request.status === 404) { + // no update available + resolve(); + } else if (request.status !== 200 && request.status !== 304) { + // other failure + reject(new Error("Manifest request to " + requestPath + " failed.")); + } else { + // success + try { + var update = JSON.parse(request.responseText); + } catch (e) { + reject(e); + return; + } + resolve(update); + } + }; + }); + } + + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; + + +/***/ }), + +/***/ 20482: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); + +class WebWorkerMainTemplatePlugin { + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + mainTemplate.hooks.localVars.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "WebWorkerMainTemplatePlugin", + (_, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + return Template.asString([ + "promises.push(Promise.resolve().then(function() {", + Template.indent([ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + "importScripts(" + + "__webpack_require__.p + " + + mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + }) + + ");" + ]), + "}" + ]), + "}));" + ]); + } + ); + mainTemplate.hooks.bootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkOnDemandLoadingCode(chunk)) { + const chunkCallbackName = + mainTemplate.outputOptions.chunkCallbackName; + const globalObject = mainTemplate.outputOptions.globalObject; + return Template.asString([ + source, + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}] = function webpackChunkCallback(chunkIds, moreModules) {`, + Template.indent([ + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}", + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;") + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; + const globalObject = mainTemplate.outputOptions.globalObject; + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "' + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + + return ( + source + + "\n" + + `var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( + hotUpdateFunction + )}];\n` + + `${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ` + + Template.getFunctionContent( + __webpack_require__(72337) + ) + .replace(/\/\/\$semicolon/g, ";") + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) + .replace(/\$hash\$/g, JSON.stringify(hash)) + ); + } + ); + mainTemplate.hooks.hash.tap("WebWorkerMainTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("4"); + }); + } +} +module.exports = WebWorkerMainTemplatePlugin; + + +/***/ }), + +/***/ 21328: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const WebWorkerMainTemplatePlugin = __webpack_require__(20482); +const WebWorkerChunkTemplatePlugin = __webpack_require__(37919); +const WebWorkerHotUpdateChunkTemplatePlugin = __webpack_require__(45493); + +class WebWorkerTemplatePlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WebWorkerTemplatePlugin", + compilation => { + new WebWorkerMainTemplatePlugin().apply(compilation.mainTemplate); + new WebWorkerChunkTemplatePlugin().apply(compilation.chunkTemplate); + new WebWorkerHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + } + ); + } +} +module.exports = WebWorkerTemplatePlugin; + + +/***/ }), + +/***/ 77087: +/***/ (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-\u08bd\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\u0d05-\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\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-\uab67\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\u0b56\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\u0d82\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\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\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,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,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,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,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,270,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,754,9486,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,42710,42,4148,12,221,3,5761,15,7472,3104,541]; + + // 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,525,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,4,9,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,232,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,19723,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,792487,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), + 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), + 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}), + + // 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, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (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 optional argument can be given to further configure + // the parser process. These options are recognized: + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 + // (2019). This influences support for strict mode, the set of + // reserved words, and support for new syntax features. The default + // is 9. + ecmaVersion: 9, + // `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. + allowImportExportEverywhere: false, + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: false, + // 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 + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + 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_VAR = SCOPE_TOP | SCOPE_FUNCTION, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128; + + 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) { + for (var v = options.ecmaVersion;; v--) + { if (reserved = reservedWords[v]) { break } } + 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; + + // 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 = {}; + + // 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; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { 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 }; + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; + prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + // Switch to a getter for 7.0.0. + Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 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") { return true } + 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 = {}; + 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) { return true } // '[' + if (context) { return false } + + if (nextCh === 123) { return true } // '{' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } + 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; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) + }; + + // 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) // '(' + { 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.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && 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 refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(true, refDestructuringErrors); + if (this.type === types._in || (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; } + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLVal(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.checkLVal(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) { + 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.eat(types.braceR)) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + 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") + ); + } else if (init.type === "AssignmentPattern") { + this.raise(init.start, "Invalid left-hand side in for-loop"); + } + 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.checkLVal(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) { + 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.checkLVal(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); + + 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 classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types.braceL); + while (!this.eat(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; + } + } + } + node.body = this.finishNode(classBody, "ClassBody"); + this.strict = oldStrict; + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$1.parseClassElement = function(constructorAllowsSuper) { + var this$1 = this; + + if (this.eat(types.semi)) { return null } + + var method = this.startNode(); + var tryContextual = function (k, noLineBreak) { + if ( noLineBreak === void 0 ) noLineBreak = false; + + var start = this$1.start, startLoc = this$1.startLoc; + if (!this$1.eatContextual(k)) { return false } + if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } + if (method.key) { this$1.unexpected(); } + method.computed = false; + method.key = this$1.startNodeAt(start, startLoc); + method.key.name = k; + this$1.finishNode(method.key, "Identifier"); + return false + }; + + method.kind = "method"; + method.static = tryContextual("static"); + var isGenerator = this.eat(types.star); + var isAsync = false; + if (!isGenerator) { + if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + } else if (tryContextual("get")) { + method.kind = "get"; + } else if (tryContextual("set")) { + method.kind = "set"; + } + } + if (!method.key) { this.parsePropertyName(method); } + var key = method.key; + var allowsDirectSuper = false; + if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || + key.type === "Literal" && key.value === "constructor")) { + if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } + 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"); } + method.kind = "constructor"; + allowsDirectSuper = constructorAllowsSuper; + } else if (method.static && key.type === "Identifier" && key.name === "prototype") { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); + if (method.kind === "get" && method.value.params.length !== 0) + { this.raiseRecoverable(method.value.start, "getter should have no params"); } + if (method.kind === "set" && method.value.params.length !== 1) + { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } + if (method.kind === "set" && method.value.params[0].type === "RestElement") + { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } + return method + }; + + pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + return this.finishNode(method, "MethodDefinition") + }; + + pp$1.parseClassId = function(node, isStatement) { + if (this.type === types.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLVal(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() : null; + }; + + // Parses module export declaration. + + pp$1.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types.star)) { + 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.checkLVal(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.checkLVal(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.checkLVal(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 "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); + // falls through to AssignmentPattern + + case "AssignmentPattern": + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + 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") + }; + + // Verify that a node is an lval — something that can be assigned + // to. + // bindingType can be either: + // 'var' indicating that the lval creates a 'var' binding + // 'let' indicating that the lval creates a lexical ('let' or 'const') binding + // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references + + pp$2.checkLVal = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (checkClashes) { + if (has(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + break + + case "MemberExpression": + if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkLVal(prop, bindingType, checkClashes); + } + break + + case "Property": + // AssignmentProperty has type === "Property" + this.checkLVal(expr.value, 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.checkLVal(elem, bindingType, checkClashes); } + } + break + + case "AssignmentPattern": + this.checkLVal(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLVal(expr.argument, bindingType, checkClashes); + break + + case "ParenthesizedExpression": + this.checkLVal(expr.expression, bindingType, checkClashes); + break + + default: + this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + // A recursive descent parser operates by defining functions for all + + var pp$3 = 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$3.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 && 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$3.parseExpression = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(noIn, 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(noIn, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(noIn) } + // 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, oldShorthandAssign = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldShorthandAssign = refDestructuringErrors.shorthandAssign; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -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; } + var left = this.parseMaybeConditional(noIn, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; + if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } + refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly + this.checkLVal(left); + this.next(); + node.right = this.parseMaybeAssign(noIn); + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(noIn, 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(noIn); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$3.parseExprOps = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) + }; + + // 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$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.type.binop; + if (prec != null && (!noIn || this.type !== types._in)) { + if (prec > minPrec) { + var logical = this.type === types.logicalOR || this.type === types.logicalAND; + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) + } + } + return left + }; + + pp$3.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$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { + expr = this.parseAwait(); + 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); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLVal(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors); + 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.checkLVal(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!sawUnary && this.eat(types.starstar)) + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + else + { return expr } + }; + + // Parse call, dot, and `[]`-subscript expressions. + + pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; + if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + } + return result + }; + + pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow); + if (element === base || element.type === "ArrowFunctionExpression") { return element } + base = element; + } + }; + + pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) { + var computed = this.eat(types.bracketL); + if (computed || this.eat(types.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); + node.computed = !!computed; + if (computed) { this.expect(types.bracketR); } + 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 && base.type !== "Import", false, refDestructuringErrors); + if (maybeAsyncArrow && !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) + } + 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 (node$1.callee.type === "Import") { + if (node$1.arguments.length !== 1) { + this.raise(node$1.start, "import() requires exactly one argument"); + } + + var importArg = node$1.arguments[0]; + if (importArg && importArg.type === "SpreadElement") { + this.raise(importArg.start, "... is not allowed in import()"); + } + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types.backQuote) { + 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$3.parseExprAtom = function(refDestructuringErrors) { + // 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)) + { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + 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); + 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: + 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 > 10) { + return this.parseDynamicImport() + } else { + return this.unexpected() + } + + default: + this.unexpected(); + } + }; + + pp$3.parseDynamicImport = function() { + var node = this.startNode(); + this.next(); + if (this.type !== types.parenL) { + this.unexpected(); + } + return this.finishNode(node, "Import") + }; + + pp$3.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); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val + }; + + pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + 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.start, innerEndLoc = this.startLoc; + 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) + } + + 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$3.parseParenItem = function(item) { + return item + }; + + pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) + }; + + // 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$3.parseNew = function() { + 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" || containsEsc) + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } + if (!this.inNonArrowFunction()) + { this.raiseRecoverable(node.start, "new.target can only be used in functions"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + if (this.options.ecmaVersion > 10 && node.callee.type === "Import") { + this.raise(node.callee.start, "Cannot use new with import(...)"); + } + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && node.callee.type !== "Import", false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$3.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$3.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$3.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$3.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.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$3.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$3.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)) { + 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, prop.key); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); + } else { + prop.value = prop.key; + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$3.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$3.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$3.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); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$3.parseArrowExpression = function(node, params, isAsync) { + 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); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + 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)); + node.body = this.parseBlock(false); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } + this.strict = oldStrict; + }; + + pp$3.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$3.checkParams = function(node, allowDuplicates) { + var nameHash = {}; + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLVal(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$3.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$3.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.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$3.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(); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + // Parses yield expression inside generator. + + pp$3.parseYield = function(noIn) { + 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(noIn); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = 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$4.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$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$5 = 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 = []; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$5.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$5.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$5.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$5.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$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$5.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$5.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$6 = Parser.prototype; + + pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$6.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$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + // 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$7 = Parser.prototype; + + pp$7.initialContext = function() { + return [types$1.b_stat] + }; + + pp$7.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$7.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$7.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; } + }; + + // 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.semi && prevType !== types._else && + !(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; + }; + + // 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 unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties + }; + + // #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 unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues + }; + + 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); + + 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" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : 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) { + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!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) { + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!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 () { + return this.at(this.pos) + }; + + RegExpValidationState.prototype.lookahead = function lookahead () { + return this.at(this.nextIndex(this.pos)) + }; + + RegExpValidationState.prototype.advance = function advance () { + this.pos = this.nextIndex(this.pos); + }; + + RegExpValidationState.prototype.eat = function eat (ch) { + if (this.current() === ch) { + this.advance(); + 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[U] :: + // [empty] + // `?` GroupName[?U] + 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[U] :: + // `<` RegExpIdentifierName[?U] `>` + // 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[U] :: + // RegExpIdentifierStart[?U] + // RegExpIdentifierName[?U] RegExpIdentifierPart[?U] + // 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[U] :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[?U] + pp$8.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + 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[U] :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[?U] + // + // + pp$8.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + 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) || + (!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) { + var start = state.pos; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (state.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 ( + state.switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (state.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() { + 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). + + pp$9.curContext = function() { + return this.context[this.context.length - 1] + }; + + // 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 >= 0xe000) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return (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) { 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) { + // ` 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"); + +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} + */ +class BinaryMiddleware extends SerializerMiddleware { + static optimizeSerializedData(data) { + const result = []; + const temp = []; + const flush = () => { + if (temp.length > 0) { + if (temp.length === 1) { + result.push(temp[0]); + } else { + result.push(Buffer.concat(temp)); + } + temp.length = 0; + } + }; + for (const item of data) { + if (Buffer.isBuffer(item)) { + temp.push(item); + } else { + flush(); + result.push(item); + } + } + flush(); + return result; + } + + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + return this._serialize(data, context); + } + + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType} serialized data + */ + _serialize(data, context) { + /** @type {Buffer} */ + let currentBuffer = null; + /** @type {Buffer} */ + let leftOverBuffer = null; + let currentPosition = 0; + /** @type {BufferSerializableType[]} */ + const buffers = []; + let buffersTotalLength = 0; + const allocate = (bytesNeeded, exact = false) => { + if (currentBuffer !== null) { + if (currentBuffer.length - currentPosition >= bytesNeeded) return; + flush(); + } + if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { + currentBuffer = leftOverBuffer; + leftOverBuffer = null; + } else { + currentBuffer = Buffer.allocUnsafe( + exact ? bytesNeeded : Math.max(bytesNeeded, buffersTotalLength, 1024) + ); + } + }; + const flush = () => { + if (currentBuffer !== null) { + buffers.push(currentBuffer.slice(0, currentPosition)); + if ( + !leftOverBuffer || + leftOverBuffer.length < currentBuffer.length - currentPosition + ) + leftOverBuffer = currentBuffer.slice(currentPosition); + currentBuffer = null; + buffersTotalLength += currentPosition; + 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; + }; + const serializeData = data => { + 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)) { + const data = this._serialize(thing(), context); + SerializerMiddleware.setLazySerializedValue(thing, data); + serializedData = data; + } else { + serializedData = SerializerMiddleware.serializeLazy( + thing, + data => this._serialize(data, context) + ); + } + } + if (typeof serializedData === "function") { + flush(); + buffers.push(serializedData); + } else { + 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); + } + for (const item of serializedData) { + flush(); + 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); + } else { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + currentBuffer.write(thing, currentPosition, "latin1"); + } + currentPosition += len; + 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 * 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 * 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)) { + allocate(HEADER_SIZE + I32_SIZE, true); + 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; + } + } + } + }; + serializeData(data); + flush(); + return buffers; + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + return 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 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; + }; + /** + * Reads n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const read = n => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" + ); + } + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + return Buffer.concat([read(rem), read(n - rem)]); + } + const res = /** @type {Buffer} */ (currentBuffer).slice( + currentPosition, + 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 => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" + ); + } + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + n = rem; + } + const res = /** @type {Buffer} */ (currentBuffer).slice( + currentPosition, + currentPosition + n + ); + currentPosition += n; + checkOverflow(); + return res; + }; + const readU8 = () => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" + ); + } + /** + * 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(buf); + } while (l > 0); + } + } + result.push( + SerializerMiddleware.createLazy( + memorize(() => this._deserialize(content, context)), + this, + undefined, + content + ) + ); + }; + case BUFFER_HEADER: + return () => { + const len = readU32(); + result.push(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)) { + 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) { + 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)) { + 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} */ + const result = []; + while (currentBuffer !== null) { + if (typeof currentBuffer === "function") { + result.push( + SerializerMiddleware.deserializeLazy(currentBuffer, data => + this._deserialize(data, context) + ) + ); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + const header = readU8(); + dispatchTable[header](); + } + } + return result; + } +} + +module.exports = BinaryMiddleware; + +module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; +module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; + + +/***/ }), + +/***/ 32973: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +class DateObjectSerializer { + serialize(obj, { write }) { + write(obj.getTime()); + } + deserialize({ read }) { + return new Date(read()); + } +} + +module.exports = DateObjectSerializer; + + +/***/ }), + +/***/ 60252: +/***/ ((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); + } + + deserialize({ read }) { + const err = new this.Type(); + + err.message = read(); + err.stack = read(); + + return err; + } +} + +module.exports = ErrorObjectSerializer; + + +/***/ }), + +/***/ 40572: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { constants } = __webpack_require__(64293); +const createHash = __webpack_require__(24123); +const { dirname, join, mkdirp } = __webpack_require__(93204); +const memorize = __webpack_require__(8118); +const SerializerMiddleware = __webpack_require__(37063); + +/** @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; +const hashForName = buffers => { + const hash = createHash("md4"); + for (const buf of buffers) hash.update(buf); + return /** @type {string} */ (hash.digest("hex")); +}; + +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 + * @returns {Promise} resulting file pointer and promise + */ +const serialize = async (middleware, data, name, writeFile) => { + /** @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 + ).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); + } + 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 + */ +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 = []; + for (let i = 0; i < sectionCount; i++) { + lengths.push(readInt32LE()); + } + 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( + memorize(() => deserialize(middleware, name, readFile)), + middleware, + { + name, + size + }, + slice + ) + ); + } else { + if (contentPosition === contentItemLength) { + nextContent(); + } else if (contentPosition !== 0) { + if (length <= contentItemLength - contentPosition) { + result.push( + contentItem.slice(contentPosition, contentPosition + length) + ); + contentPosition += length; + length = 0; + } else { + result.push(contentItem.slice(contentPosition)); + length -= contentItemLength - contentPosition; + contentPosition = contentItemLength; + } + } else { + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push(contentItem.slice(0, length)); + contentPosition += length; + length = 0; + } + } + while (length > 0) { + nextContent(); + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push(contentItem.slice(0, length)); + contentPosition += length; + length = 0; + } + } + } + } + return result; +}; + +/** + * @typedef {BufferSerializableType[]} DeserializedType + * @typedef {true} SerializedType + * @extends {SerializerMiddleware} + */ +class FileMiddleware extends SerializerMiddleware { + /** + * @param {IntermediateFileSystem} fs filesystem + */ + constructor(fs) { + super(); + this.fs = fs; + } + /** + * @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) => { + const stream = this.fs.createWriteStream(file + "_"); + for (const b of content) stream.write(b); + stream.end(); + stream.on("error", err => reject(err)); + stream.on("finish", () => resolve()); + }); + if (name) allWrittenFiles.add(file); + }; + + resolve( + serialize(this, data, false, writeFile).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); + } + ) + ); + }); + }); + } + + /** + * @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 = stats.size; + let currentBuffer; + let currentBufferUsed; + const buf = []; + 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) + ); + currentBufferUsed = 0; + } + let readBuffer = currentBuffer; + let readOffset = currentBufferUsed; + let readLength = currentBuffer.length - currentBufferUsed; + 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) { + buf.push(currentBuffer); + currentBuffer = undefined; + if (remaining === 0) { + this.fs.close(fd, err => { + if (err) { + reject(err); + return; + } + resolve(buf); + }); + return; + } + } + read(); + } + ); + }; + read(); + }); + }); + }); + return deserialize(this, false, readFile); + } +} + +module.exports = FileMiddleware; + + +/***/ }), + +/***/ 82547: +/***/ ((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; + + +/***/ }), + +/***/ 52985: +/***/ ((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; + + +/***/ }), + +/***/ 77815: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const createHash = __webpack_require__(24123); +const ArraySerializer = __webpack_require__(80573); +const DateObjectSerializer = __webpack_require__(32973); +const ErrorObjectSerializer = __webpack_require__(60252); +const MapObjectSerializer = __webpack_require__(82547); +const NullPrototypeObjectSerializer = __webpack_require__(52985); +const PlainObjectSerializer = __webpack_require__(24298); +const RegExpObjectSerializer = __webpack_require__(90410); +const SerializerMiddleware = __webpack_require__(37063); +const SetObjectSerializer = __webpack_require__(85199); + +/** @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 + */ + +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); + } + } +}; + +const toHash = buffer => { + const hash = createHash("md4"); + 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); + } + } +} + +{ + 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 { + constructor(extendContext) { + super(); + this.extendContext = extendContext; + } + /** + * @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); + } + + /** + * @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` + ); + } + + 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); + } + + /** + * @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) { + let c = object.constructor; + if (!c) { + if (Object.getPrototypeOf(object) === null) { + // Object created with Object.create(null) + c = null; + } else { + 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; + } + + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + /** @type {any[]} */ + const result = [CURRENT_VERSION]; + let currentPos = 0; + const referenceable = new Map(); + const addReferenceable = item => { + referenceable.set(item, currentPos++); + }; + const 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); + const newMap = new Map(); + newMap.set(hash, entry); + bufferDedupeMap.set(len, newMap); + const hashBuf = toHash(buf); + 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); + let found; + for (const item of entry) { + const itemHash = toHash(item); + 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); + const item = entry.get(hash); + if (item !== undefined) { + return item; + } + entry.set(hash, buf); + return buf; + } + }; + let currentPosTypeLookup = 0; + const 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; + const ctx = { + write(value, key) { + try { + process(value); + } catch (e) { + if (hasDebugInfoAttached === undefined) + hasDebugInfoAttached = new WeakSet(); + if (!hasDebugInfoAttached.has(e)) { + e.message += `\nwhile serializing ${stackToString(value)}`; + hasDebugInfoAttached.add(e); + } + throw e; + } + }, + 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 => { + // check if we can emit a reference + const ref = referenceable.get(item); + + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + + return; + } + + if (Buffer.isBuffer(item)) { + 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 (typeof item === "object" && item !== null) { + if (cycleStack.has(item)) { + throw new Error(`Circular references can't be serialized`); + } + + 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) + 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 (item === ESCAPE) { + result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); + } 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 { + result.push( + SerializerMiddleware.serializeLazy(item, data => + this.serialize([data], context) + ) + ); + } + } else if (item === undefined) { + result.push(ESCAPE, ESCAPE_UNDEFINED); + } else { + result.push(item); + } + }; + + try { + for (const item of data) { + process(item); + } + } catch (e) { + if (e === NOT_SERIALIZABLE) return null; + + throw e; + } + + return result; + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + let currentDataPos = 0; + const read = () => { + if (currentDataPos >= data.length) + throw new Error("Unexpected end of stream"); + + return data[currentDataPos++]; + }; + + if (read() !== CURRENT_VERSION) + throw new Error("Version mismatch, serializer changed"); + + let currentPos = 0; + let referenceable = []; + const addReferenceable = item => { + referenceable.push(item); + currentPos++; + }; + let currentPosTypeLookup = 0; + let objectTypeLookup = []; + const result = []; + const ctx = { + read() { + return decodeValue(); + }, + ...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 if (typeof nextItem === "number" && nextItem < 0) { + // relative reference + return referenceable[currentPos + nextItem]; + } else { + const request = nextItem; + let serializer; + + if (typeof request === "number") { + 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 (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); + } + + serializer = ObjectMiddleware.getDeserializerFor(request, name); + + objectTypeLookup.push(serializer); + currentPosTypeLookup++; + } + 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; + } + }; + + while (currentDataPos < data.length) { + result.push(decodeValue()); + } + + // Help the GC, as functions above might be cached in inline caches + referenceable = undefined; + objectTypeLookup = undefined; + data = undefined; + + return result; + } +} + +module.exports = ObjectMiddleware; +module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; + + +/***/ }), + +/***/ 24298: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const cache = new WeakMap(); + +class ObjectStructure { + constructor(keys) { + this.keys = keys; + this.children = new Map(); + } + + getKeys() { + return this.keys; + } + + key(key) { + const child = this.children.get(key); + if (child !== undefined) return child; + const newChild = new ObjectStructure(this.keys.concat(key)); + 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(); +}; + +class PlainObjectSerializer { + serialize(obj, { write }) { + const keys = Object.keys(obj); + 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; + + +/***/ }), + +/***/ 90410: +/***/ ((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; + + +/***/ }), + +/***/ 24754: +/***/ ((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; + } + + serialize(obj, context) { + const ctx = { ...context, ...this.context }; + let current = obj; + for (const middleware of this.serializeMiddlewares) { + if (current instanceof Promise) { + current = current.then( + data => data && middleware.serialize(data, context) + ); + } 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 instanceof Promise) { + current = current.then(data => middleware.deserialize(data, context)); + } else { + current = middleware.deserialize(current, ctx); + } + } + return current; + } +} + +module.exports = Serializer; + + +/***/ }), + +/***/ 37063: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const memorize = __webpack_require__(8118); + +const LAZY_TARGET = Symbol("lazy serialization target"); +const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); + +/** + * @template DeserializedType + * @template SerializedType + */ +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__(570); + 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__(570); + throw new AbstractMethodError(); + } + + /** + * @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; + } + + /** + * @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 {function(): Promise | any} fn lazy function + * @returns {object} options + */ + static getLazyOptions(fn) { + if (typeof fn !== "function") return undefined; + return /** @type {any} */ (fn).options; + } + + /** + * @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(): Promise | any} fn lazy function + * @param {any} value serialized value + * @returns {void} + */ + static setLazySerializedValue(fn, value) { + fn[LAZY_SERIALIZED_VALUE] = value; + } + + /** + * @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 = memorize(() => { + const r = lazy(); + if (r instanceof Promise) return r.then(data => data && serialize(data)); + if (r) return serialize(r); + return null; + }); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; + lazy[LAZY_SERIALIZED_VALUE] = fn; + return fn; + } + + /** + * @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 = memorize(() => { + const r = lazy(); + if (r instanceof Promise) 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; + } +} + +module.exports = SerializerMiddleware; + + +/***/ }), + +/***/ 85199: +/***/ ((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; + } +} + +module.exports = SetObjectSerializer; + + +/***/ }), + +/***/ 63340: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const SerializerMiddleware = __webpack_require__(37063); + +/** + * @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]; + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + return data[0]; + } +} + +module.exports = SingleItemMiddleware; + + +/***/ }), + +/***/ 90489: +/***/ ((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__(80944); +const makeSerializable = __webpack_require__(26522); + +class ConsumeSharedFallbackDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "consume shared fallback"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ConsumeSharedFallbackDependency, + "webpack/lib/sharing/ConsumeSharedFallbackDependency" +); + +module.exports = ConsumeSharedFallbackDependency; + + +/***/ }), + +/***/ 61474: +/***/ ((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__(55600); +const AsyncDependenciesBlock = __webpack_require__(11315); +const Module = __webpack_require__(85887); +const RuntimeGlobals = __webpack_require__(49404); +const makeSerializable = __webpack_require__(26522); +const { rangeToString, stringifyHoley } = __webpack_require__(60473); +const ConsumeSharedFallbackDependency = __webpack_require__(90489); + +/** @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 */ + +/** + * @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 {string} context context + * @param {ConsumeOptions} options consume options + */ + constructor(context, options) { + super("consume-shared-module", context); + this.options = options; + } + + /** + * @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 {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 {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + const { shareKey, shareScope, import: request } = this.options; + return `webpack/sharing/consume/${shareScope}/${shareKey}${ + request ? `/${request}` : "" + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + 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 = {}; + 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(); + } + + /** + * @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 42; + } + + /** + * @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); + } + + /** + * @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 + }); + } + } + 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"; + } + 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); + } + + deserialize(context) { + const { read } = context; + this.options = read(); + super.deserialize(context); + } +} + +makeSerializable( + ConsumeSharedModule, + "webpack/lib/sharing/ConsumeSharedModule" +); + +module.exports = ConsumeSharedModule; + + +/***/ }), + +/***/ 19984: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { validate } = __webpack_require__(79286); +const schema = __webpack_require__(9515); +const ModuleNotFoundError = __webpack_require__(82908); +const RuntimeGlobals = __webpack_require__(49404); +const WebpackError = __webpack_require__(68422); +const { parseOptions } = __webpack_require__(56084); +const LazySet = __webpack_require__(59534); +const { parseRange } = __webpack_require__(60473); +const ConsumeSharedFallbackDependency = __webpack_require__(90489); +const ConsumeSharedModule = __webpack_require__(61474); +const ConsumeSharedRuntimeModule = __webpack_require__(830); +const ProvideForSharedDependency = __webpack_require__(40235); +const { resolveMatchedConfigs } = __webpack_require__(18436); +const { + isRequiredVersion, + getDescriptionFile, + getRequiredVersionFromDescriptionFile +} = __webpack_require__(58854); + +/** @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 */ + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; +const PLUGIN_NAME = "ConsumeSharedPlugin"; + +class ConsumeSharedPlugin { + /** + * @param {ConsumeSharedPluginOptions} options options + */ + constructor(options) { + if (typeof options !== "string") { + validate(schema, options, { name: "Consumes Shared Plugin" }); + } + + /** @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 + * @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; + } + ); + + const resolver = compilation.resolverFactory.get( + "normal", + RESOLVE_OPTIONS + ); + + /** + * @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.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.shareScopeMap); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ConsumeSharedRuntimeModule(set) + ); + } + ); + } + ); + } +} + +module.exports = ConsumeSharedPlugin; + + +/***/ }), + +/***/ 830: +/***/ ((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__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); +const { + parseVersionRuntimeCode, + versionLtRuntimeCode, + rangeToStringRuntimeCode, + satisfyRuntimeCode +} = __webpack_require__(60473); + +/** @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, + chunkGraph, + codeGenerationResults + } = this.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([ + 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( + "key, version, requiredVersion", + [ + `return "Unsatisfied version " + version + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"` + ] + )};`, + `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(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(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 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 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", [ + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( + "module", + [ + "// Handle case when module is used sync", + "installedModules[id] = 0;", + "delete __webpack_module_cache__[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;", + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( + "module", + [ + "delete __webpack_module_cache__[id];", + "module.exports = factory();" + ] + )}` + ] + )};`, + `var onError = ${runtimeTemplate.basicFunction("error", [ + "delete installedModules[id];", + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( + "module", + ["delete __webpack_module_cache__[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 = ConsumeSharedRuntimeModule; + + +/***/ }), + +/***/ 40235: +/***/ ((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__(80944); +const makeSerializable = __webpack_require__(26522); + +class ProvideForSharedDependency extends ModuleDependency { + /** + * + * @param {string} request request string + */ + constructor(request) { + super(request); + } + + get type() { + return "provide module for shared"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ProvideForSharedDependency, + "webpack/lib/sharing/ProvideForSharedDependency" +); + +module.exports = ProvideForSharedDependency; + + +/***/ }), + +/***/ 99355: +/***/ ((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__(50384); +const makeSerializable = __webpack_require__(26522); + +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); + } + + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedDependency( + read(), + read(), + read(), + read(), + read() + ); + this.shareScope = context.read(); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + ProvideSharedDependency, + "webpack/lib/sharing/ProvideSharedDependency" +); + +module.exports = ProvideSharedDependency; + + +/***/ }), + +/***/ 65945: +/***/ ((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__(11315); +const Module = __webpack_require__(85887); +const RuntimeGlobals = __webpack_require__(49404); +const makeSerializable = __webpack_require__(26522); +const ProvideForSharedDependency = __webpack_require__(40235); + +/** @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 {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; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; + } + + /** + * @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)}`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `webpack/sharing/provide/${this._shareScope}/${this._name}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + 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(); + const dep = new ProvideForSharedDependency(this._request); + if (this._eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + + 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 42; + } + + /** + * @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 + }) + });`; + const sources = new Map(); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this._shareScope, + initStage: 10, + init: code + } + ]); + return { sources, data, runtimeRequirements }; + } + + 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; + } +} + +makeSerializable( + ProvideSharedModule, + "webpack/lib/sharing/ProvideSharedModule" +); + +module.exports = ProvideSharedModule; + + +/***/ }), + +/***/ 89859: +/***/ ((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__(61574); +const ProvideSharedModule = __webpack_require__(65945); + +/** @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 + ) + }); + } +} + +module.exports = ProvideSharedModuleFactory; + + +/***/ }), + +/***/ 42672: +/***/ ((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 { validate } = __webpack_require__(79286); +const schema = __webpack_require__(12287); +const WebpackError = __webpack_require__(68422); +const { parseOptions } = __webpack_require__(56084); +const ProvideForSharedDependency = __webpack_require__(40235); +const ProvideSharedDependency = __webpack_require__(99355); +const ProvideSharedModuleFactory = __webpack_require__(89859); + +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {Object} ProvideOptions + * @property {string} shareKey + * @property {string} shareScope + * @property {string | undefined | false} version + * @property {boolean} eager + */ + +/** @typedef {Map} ResolvedProvideMap */ + +class ProvideSharedPlugin { + /** + * @param {ProvideSharedPluginOptions} options options + */ + constructor(options) { + validate(schema, options, { name: "Provide Shared Plugin" }); + + /** @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} + */ + apply(compiler) { + /** @type {WeakMap} */ + const compilationData = new WeakMap(); + + 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(() => {}); + }); + + compiler.hooks.compilation.tap( + "ProvideSharedPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ProvideForSharedDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + ProvideSharedDependency, + new ProvideSharedModuleFactory() + ); + } + ); + } +} + +module.exports = ProvideSharedPlugin; + + +/***/ }), + +/***/ 25790: +/***/ ((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 { parseOptions } = __webpack_require__(56084); +const ConsumeSharedPlugin = __webpack_require__(19984); +const ProvideSharedPlugin = __webpack_require__(42672); +const { isRequiredVersion } = __webpack_require__(58854); + +/** @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); + } +} + +module.exports = SharePlugin; + + +/***/ }), + +/***/ 97207: +/***/ ((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__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); +const { + compareModulesByIdentifier, + compareStrings +} = __webpack_require__(26296); + +class ShareRuntimeModule extends RuntimeModule { + constructor() { + super("sharing"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { + runtimeTemplate, + chunkGraph, + codeGenerationResults, + outputOptions: { uniqueName } + } = this.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", + [ + "var versions = scope[name] = scope[name] || {};", + "var activeVersion = versions[version];", + "if(!activeVersion || !activeVersion.loaded && uniqueName > activeVersion.from) versions[version] = { get: factory, from: uniqueName };" + ] + )};`, + `var initExternal = ${runtimeTemplate.basicFunction("id", [ + `var handleError = ${runtimeTemplate.returningFunction( + '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 = ShareRuntimeModule; + + +/***/ }), + +/***/ 18436: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ModuleNotFoundError = __webpack_require__(82908); +const LazySet = __webpack_require__(59534); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ + +/** + * @template T + * @typedef {Object} MatchedConfigs + * @property {Map} resolved + * @property {Map} unresolved + * @property {Map} prefixed + */ + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; + +/** + * @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 }; + }); +}; + + +/***/ }), + +/***/ 58854: +/***/ ((__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__(93204); + +/** @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=, {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]; + } +}; + + +/***/ }), + +/***/ 91293: +/***/ ((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__(31669); +const ModuleDependency = __webpack_require__(80944); +const formatLocation = __webpack_require__(57261); +const { LogType } = __webpack_require__(54667); +const AggressiveSplittingPlugin = __webpack_require__(10055); +const ConcatenatedModule = __webpack_require__(1881); +const SizeLimitsPlugin = __webpack_require__(64025); +const { + compareLocations, + compareChunksById, + compareNumbers, + compareIds, + concatComparators, + compareSelect, + compareModulesByIdentifier +} = __webpack_require__(26296); +const { makePathsRelative, parseResource } = __webpack_require__(96236); + +/** @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").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 {Asset & { type: string, related: ExtendedAsset[] }} ExtendedAsset */ + +/** @template T @typedef {Record void>} ExtractorsByOption */ + +/** + * @typedef {Object} SimpleExtractors + * @property {ExtractorsByOption} compilation + * @property {ExtractorsByOption} asset + * @property {ExtractorsByOption} asset$visible + * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }>} 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 }>} moduleTraceItem + * @property {ExtractorsByOption} moduleTraceDependency + */ + +/** + * @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); + } + } + 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); +}; + +/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ + +/** + * @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)); + } + return newObj; +}; + +/** + * @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; +}; + +/** + * @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; +}; + +/** @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) => { + if (typeof error !== "string") { + object.details = error.details; + } + }, + errorStack: (object, error) => { + if (typeof error !== "string") { + object.stack = error.stack; + } + } +}; + +/** @type {SimpleExtractors} */ +const SIMPLE_EXTRACTORS = { + compilation: { + _: (object, compilation, context) => { + 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; + } + }, + hash: (object, compilation) => { + object.hash = compilation.hash; + }, + version: object => { + object.version = __webpack_require__(87168)/* .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(); + const assets = new Set(); + for (const asset of compilation.getAssets()) { + 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 + ); + }, + 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) + ); + }); + }); + }, + logging: (object, compilation, _context, options, factory) => { + const util = __webpack_require__(31669); + const { loggingDebug, loggingTrace, context } = options; + object.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (options.logging) { + case "none": + 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( + context, + compilation.compiler.root + ); + let depthInCollapsedGroup = 0; + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some(fn => fn(origin)); + const groupStack = []; + 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)); + } + 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 + }; + } + }, + 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); + const toAsset = name => { + const asset = compilation.getAsset(name); + return { + name, + size: asset ? asset.info.size : -1 + }; + }; + 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); + Object.assign(object, { + 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); + return { + 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 + }; + }) + ) + : 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 + }); + }, + 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 sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); + } + Object.assign(object, { + type: "module", + moduleType: module.type, + size: module.size(), + sizes, + built, + codeGenerated, + cached: !built && !codeGenerated + }); + 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; + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); + } + Object.assign(object, { + 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 + }); + 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; + object.reasons = factory.create( + `${type.slice(0, -8)}.reasons`, + Array.from(moduleGraph.getIncomingConnections(module)), + context + ); + }, + 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; + if (module instanceof ConcatenatedModule) { + const modules = module.modules; + const groupedModules = factory.create( + `${type.slice(0, -8)}.modules`, + modules, + 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) => { + Object.assign(object, { + 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 + }); + } + }, + moduleIssuer: { + _: (object, module, context, { requestShortener }, factory) => { + const { compilation, type } = context; + const { moduleGraph } = compilation; + const profile = moduleGraph.getProfile(module); + Object.assign(object, { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener) + }); + 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; + Object.assign(object, { + 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 + }); + 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); + + Object.assign(object, { + 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 + }); + }, + 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 }) => { + Object.assign(object, { + 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 + }); + }, + 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); + } + } +}; + +/** @type {Record boolean | undefined>>} */ +const FILTER = { + "module.reasons": { + "!orphanModules": (reason, { compilation: { chunkGraph } }) => { + if ( + reason.originModule && + chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 + ) { + return false; + } + } + } +}; + +/** @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) => { + /** @type {any[] | undefined} */ + let children = undefined; + /** @type {number | undefined} */ + let filteredChildren = undefined; + // This are the groups, which take 1+ lines each + const groups = itemsAndGroups.filter(c => c.children || c.filteredChildren); + // The sizes of the groups are stored in groupSizes + const groupSizes = groups.map(g => getItemSize(g)); + // This are the items, which take 1 line each + const items = itemsAndGroups.filter(c => !c.children && !c.filteredChildren); + // The total of group sizes + let groupsSize = groupSizes.reduce((a, b) => a + b, 0); + if (groupsSize + items.length <= max) { + // The total size in the current state fits into the max + // keep all + children = groups.concat(items); + } else if ( + groups.length > 0 && + groups.length + Math.min(1, items.length) < max + ) { + // If each group would take 1 line the total would be below the maximum + // collapse some groups, keep items + while (groupsSize + items.length + (filteredChildren ? 1 : 0) > max) { + // calculate how much we are over the size limit + // this allows to approach the limit faster + // it's always > 1 + const oversize = + items.length + groupsSize + (filteredChildren ? 1 : 0) - max; + // 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.children + ? 0 + : group.filteredChildren + ? 2 + : 1; + const limited = spaceLimited( + group.children, + groupSizes[i] - headerSize - oversize / groups.length + ); + groups[i] = { + ...group, + children: limited.children, + filteredChildren: + (group.filteredChildren || 0) + limited.filteredChildren + }; + const newSize = getItemSize(groups[i]); + groupsSize -= groupSizes[i] - newSize; + groupSizes[i] = newSize; + break; + } + } + } + children = groups.concat(items); + } else if ( + groups.length > 0 && + groups.length + Math.min(1, items.length) <= 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 = groups.length ? collapse(groups) : undefined; + 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 + }; +}; + +/** @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 && /(\.[^.]+)(?:\?.*|$)/.exec(asset.name); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupAssetsByPath && /(.+)[/\\][^/\\]+(?:\?.*|$)/.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(string): 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, + 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 (groupModulesByPath || groupModulesByExtension) { + groupConfigs.push({ + getKeys: module => { + if (!module.name) return; + const resource = parseResource(module.name.split("!").pop()).path; + const extensionMatch = + groupModulesByExtension && /(\.[^.]+)(?:\?.*|$)/.exec(resource); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupModulesByPath && /(.+)[/\\][^/\\]+(?:\?.*|$)/.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) => { + return { + type: groupModulesByPath + ? "modules by path" + : "modules by extension", + name: 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") +}; + +// remove a prefixed "!" that can be specified to reverse sort order +const normalizeFieldKey = field => { + if (field[0] === "!") { + return field.substr(1); + } + return field; +}; + +// 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); + + 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); + } + + return sortFn; +}; + +const ASSET_SORTERS = { + 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 +}; + +/** + * @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]); + } + } +}; + +/** @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" +}; + +/** + * @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; + + +/***/ }), + +/***/ 2130: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RequestShortener = __webpack_require__(43157); + +/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ +/** @typedef {import("../Compiler")} Compiler */ + +const applyDefaults = (options, defaults) => { + for (const key of Object.keys(defaults)) { + if (typeof options[key] === "undefined") { + options[key] = defaults[key]; + } + } +}; + +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, + assetsSpace: 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: Infinity, + assetsSpace: Infinity + }, + 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 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; + +/** @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: ({ all }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString) return "auto"; + return true; + }, + 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, + 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, + 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: OFF_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 +}; + +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] : []; + } + return value.map(normalizeFilter); + } +}; + +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; + + +/***/ }), + +/***/ 78303: +/***/ ((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 plural = (n, singular, plural) => (n === 1 ? singular : plural); + +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]]); + } +}; + +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}`); + +const isValidId = id => { + return typeof id === "number" || id; +}; + +/** @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 || + timeMessage || + hashMessage + ) + return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; + }, + "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 => + filteredModules > 0 + ? `${filteredModules} ${plural(filteredModules, "module", "modules")}` + : undefined, + "compilation.filteredAssets": (filteredAssets, { compilation: { assets } }) => + filteredAssets > 0 + ? `${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.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` + ); + } + } + }, + + "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 + ? `${filteredRelated} related ${plural( + filteredRelated, + "asset", + "assets" + )}` + : undefined, + "asset.filteredChildren": filteredChildren => + filteredChildren > 0 + ? `${filteredChildren} ${plural(filteredChildren, "asset", "assets")}` + : undefined, + + assetChunk: (id, { formatChunkId }) => formatChunkId(id), + + 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] = /^(.*!)?([^!]*)$/.exec(name); + return (prefix || "") + bold(resource); + }, + "module.identifier": identifier => 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.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 === module.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 => + filteredModules > 0 + ? `${filteredModules} nested ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "module.filteredChildren": filteredChildren => + filteredChildren > 0 + ? `${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(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), + + "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 => + n > 0 ? `${n} ${plural(n, "asset", "assets")}` : undefined, + "chunkGroup.filteredAuxiliaryAssets": n => + n > 0 ? `${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 => + filteredModules > 0 + ? `${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 }) => bold(message), + "error.details": details => 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", + "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 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!", + "errors", + "errorsInChildren!", + "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", + "sizes", + "chunks", + "depth", + "cacheable", + "orphan", + "runtime", + "optional", + "dependent", + "built", + "codeGenerated", + "cached", + "assets", + "failed", + "warnings", + "errors", + "children", + "filteredChildren", + "providedExports", + "usedExports", + "optimizationBailout", + "reasons", + "issuerPath", + "profile", + "modules", + "filteredModules" + ], + moduleReason: [ + "active", + "type", + "userRequest", + "moduleId", + "module", + "resolvedModule", + "loc", + "explanation" + ], + "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; + +/** @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) +}; + +const joinOneLine = items => + items + .map(item => item.content) + .filter(Boolean) + .join(" "); + +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); + } + 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 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(); +}; + +const joinError = error => (items, { red, yellow }) => + `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( + items, + "" + )}`; + +/** @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 === "errors" || + 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; + }) + ); + }, + "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}]`, + formatSize: __webpack_require__(15979).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}`; + } + } +}; + +const RESULT_MODIFIER = { + "module.modules": result => { + return indent(result, "| "); + } +}; + +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; +}; + +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}${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; + }); + + 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); + }); + } + + 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 = DefaultStatsPrinterPlugin; + + +/***/ }), + +/***/ 69646: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { HookMap, SyncBailHook, SyncWaterfallHook } = __webpack_require__(34718); +const { concatComparators, keepOriginalOrder } = __webpack_require__(26296); +const smartGrouping = __webpack_require__(84820); + +/** @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); + } + } + 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; + } + } + + _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; + + +/***/ }), + +/***/ 61025: +/***/ ((module, __unused_webpack_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__(34718); + +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("tapable").Hook} Hook */ + +/** + * @typedef {Object} PrintedElement + * @property {string} element + * @property {string} content + */ + +/** + * @typedef {Object} KnownStatsPrinterContext + * @property {string=} type + * @property {Object=} compilation + * @property {Object=} chunkGroup + * @property {Object=} asset + * @property {Object=} module + * @property {Object=} chunk + * @property {Object=} 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; + } + + /** + * @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; + } + } + } + + /** + * @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; + + +/***/ }), + +/***/ 21537: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +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; +}; + + +/***/ }), + +/***/ 55531: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { SyncHook, AsyncSeriesHook } = __webpack_require__(34718); + +const QUEUED_STATE = 0; +const PROCESSING_STATE = 1; +const DONE_STATE = 2; + +let inHandleResult = 0; + +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} result + */ + +/** + * @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; + this.error = undefined; + } +} + +/** + * @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 {function(T): K=} options.getKey extract key from item + * @param {function(T, Callback): void} options.processor async function to process items + */ + constructor({ name, parallelism, processor, getKey }) { + this._name = name; + this._parallelism = parallelism; + this._processor = processor; + this._getKey = + getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item)); + /** @type {Map>} */ + this._entries = new Map(); + /** @type {AsyncQueueEntry[]} */ + this._queued = []; + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._stopped = false; + + 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 a item + * @param {Callback} callback callback function + * @returns {void} + */ + add(item, callback) { + if (this._stopped) return callback(new Error("Queue was stopped")); + this.hooks.beforeAdd.callAsync(item, err => { + if (err) { + callback(err); + return; + } + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry !== undefined) { + 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); + } + return; + } + const newEntry = new AsyncQueueEntry(item, callback); + if (this._stopped) { + this.hooks.added.call(item); + this._activeTasks++; + process.nextTick(() => + this._handleResult(newEntry, new Error("Queue was stopped")) + ); + } else { + this._entries.set(key, newEntry); + this._queued.push(newEntry); + if (this._willEnsureProcessing === false) { + this._willEnsureProcessing = true; + setImmediate(this._ensureProcessing); + } + this.hooks.added.call(item); + } + }); + } + + /** + * @param {T} item a 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) { + const idx = this._queued.indexOf(entry); + if (idx >= 0) { + this._queued.splice(idx, 1); + } + } + } + + /** + * @returns {void} + */ + stop() { + this._stopped = true; + const queue = this._queued; + this._queued = []; + for (const entry of queue) { + this._entries.delete(this._getKey(entry.item)); + this._activeTasks++; + this._handleResult(entry, new Error("Queue was stopped")); + } + } + + /** + * @returns {void} + */ + increaseParallelism() { + this._parallelism++; + /* istanbul ignore next */ + if (this._willEnsureProcessing === false && this._queued.length > 0) { + this._willEnsureProcessing = true; + setImmediate(this._ensureProcessing); + } + } + + /** + * @returns {void} + */ + decreaseParallelism() { + this._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; + } + + /** + * @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; + } + + /** + * @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 && this._queued.length > 0) { + const entry = this._queued.pop(); + this._activeTasks++; + entry.state = PROCESSING_STATE; + this._startProcessing(entry); + } + this._willEnsureProcessing = false; + } + + /** + * @param {AsyncQueueEntry} entry the entry + * @returns {void} + */ + _startProcessing(entry) { + this.hooks.beforeStart.callAsync(entry.item, err => { + if (err) { + this._handleResult(entry, err); + 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 {Error=} 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 || 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; + this._activeTasks--; + + if (this._willEnsureProcessing === false && this._queued.length > 0) { + this._willEnsureProcessing = true; + setImmediate(this._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--; + }); + } +} + +module.exports = AsyncQueue; + + +/***/ }), + +/***/ 61538: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +// 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"); +}; + +const getMimetype = uri => { + const match = URIRegEx.exec(uri); + if (!match) return ""; + + return match[1] || "text/plain"; +}; + +module.exports = { + decodeDataURI, + getMimetype +}; + + +/***/ }), + +/***/ 21301: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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__(570); + throw new AbstractMethodError(); + } + + /* 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__(570); + throw new AbstractMethodError(); + } +} + +module.exports = Hash; + + +/***/ }), + +/***/ 79300: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SortableSet = __webpack_require__(67563); + +/** + * 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 = this._keys.values().next().value; + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = leafEntry.values().next().value; + 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; + } + }; + } + 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); + } + }; + } + } + + /** + * @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); + } + } + } + + /** + * @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; + } + }; + } +} + +module.exports = LazyBucketSortedSet; + + +/***/ }), + +/***/ 59534: +/***/ ((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__(26522); + +/** + * @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); + } + } +}; + +/** + * @template T + * @param {Set>} targetSet set where iterables should be added + * @param {Array | LazySet>} toDeepMerge iterables or lazy set to be flattened + * @returns {void} + */ +const flatten = (targetSet, toDeepMerge) => { + for (const set of toDeepMerge) { + if (set instanceof LazySet) { + 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); + } + } else { + targetSet.add(set); + } + } +}; + +/** + * 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 | LazySet>} */ + 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; + } + + 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 { + this._toDeepMerge.push(iterable); + this._needMerge = true; + // Avoid being too memory hungry + if (this._toDeepMerge.length > 100000) { + this._flatten(); + 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(); + } + + /** + * @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(); + } + + 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"; + } + + serialize({ write }) { + if (this._needMerge) this._merge(); + write(this._set.size); + for (const item of this._set) write(item); + } + + static deserialize({ read }) { + const count = read(); + const items = []; + for (let i = 0; i < count; i++) { + items.push(read()); + } + return new LazySet(items); + } +} + +makeSerializable(LazySet, "webpack/lib/util/LazySet"); + +module.exports = LazySet; + + +/***/ }), + +/***/ 65753: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** + * @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; + + +/***/ }), + +/***/ 34715: +/***/ ((__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 + * @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 + * @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; + } +}; + +exports.intersect = intersect; +exports.isSubset = isSubset; +exports.find = find; + + +/***/ }), + +/***/ 67563: +/***/ ((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 {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; + } + + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } + + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); + } + + /** + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } + + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } + + sort() { + this.sortWith(this._sortFn); + 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; + } + + /** + * 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; + } + + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); + } + } + + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } + + /** + * @returns {T[]} the raw array + */ + toJSON() { + return Array.from(this); + } +} + +module.exports = SortableSet; + + +/***/ }), + +/***/ 60798: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +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); + } + + /** + * @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; + } + + _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); + } + + asMap() { + return new Map(this.asPairArray()); + } + + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedMap(this.stack); + } +} + +module.exports = StackedMap; + + +/***/ }), + +/***/ 23877: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +class StringXor { + constructor() { + this._value = undefined; + this._buffer = undefined; + } + + add(str) { + let buf = this._buffer; + let value; + if (buf === undefined) { + buf = this._buffer = Buffer.from(str, "latin1"); + this._value = Buffer.from(buf); + return; + } else if (buf.length !== str.length) { + value = this._value; + buf = this._buffer = Buffer.from(str, "latin1"); + if (value.length < buf.length) { + this._value = Buffer.allocUnsafe(buf.length); + value.copy(this._value); + this._value.fill(0, value.length); + value = this._value; + } + } else { + value = this._value; + buf.write(str, "latin1"); + } + const len = buf.length; + for (let i = 0; i < len; i++) { + value[i] = value[i] ^ buf[i]; + } + } + + toString() { + return this._value === undefined ? "" : this._value.toString("latin1"); + } + + updateHash(hash) { + if (this._value !== undefined) hash.update(this._value); + } +} + +module.exports = StringXor; + + +/***/ }), + +/***/ 54345: +/***/ ((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__(39322); + +/** + * @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](); + } + + /** + * 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) { + 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 = TupleQueue; + + +/***/ }), + +/***/ 39322: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** + * @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 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; + } + + /** + * @param {T} args tuple + * @returns {boolean} true, if the tuple is in the Set + */ + 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 {T} args tuple + * @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; + } + } + + 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; + } + + /** + * @returns {Iterator} iterator + */ + [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; + + +/***/ }), + +/***/ 49606: +/***/ ((__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; + + +/***/ }), + +/***/ 11217: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @type {WeakMap>} */ +const mergeCache = new WeakMap(); +/** @type {WeakMap>>} */ +const setPropertyCache = new WeakMap(); +const DELETE = Symbol("DELETE"); + +/** + * 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} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + 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); + + if (mapByProperty === undefined) { + mapByProperty = new Map(); + setPropertyCache.set(obj, mapByProperty); + } + + let mapByValue = mapByProperty.get(property); + + if (mapByValue === undefined) { + mapByValue = new Map(); + mapByProperty.set(property, mapByValue); + } + + let result = mapByValue.get(value); + + if (result) return result; + + 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 + */ + +/** @type {WeakMap>} */ +const parseCache = new WeakMap(); + +/** + * @param {object} obj the object + * @returns {Map} parsed properties + */ +const cachedParseObject = obj => { + const entry = parseCache.get(obj); + if (entry !== undefined) return entry; + const result = parseObject(obj); + parseCache.set(obj, result); + return result; +}; + +/** + * @param {object} obj the object + * @returns {Map} parsed properties + */ +const parseObject = obj => { + const info = new Map(); + 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]; + 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 { + const entry = getInfo(key); + entry.base = obj[key]; + } + } + return info; +}; + +/** + * @param {Map} info property entries + * @returns {object} the object + */ +const serializeObject = info => { + 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; + } + } + } + return obj; +}; + +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 "..." + * @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) => { + if (second === undefined) return first; + if (first === undefined) return second; + const firstInfo = internalCaching + ? cachedParseObject(first) + : parseObject(first); + const secondInfo = internalCaching + ? cachedParseObject(second) + : parseObject(second); + /** @type {Map} */ + const result = new Map(); + for (const [key, firstEntry] of firstInfo) { + const secondEntry = secondInfo.get(key); + const entry = + secondEntry !== undefined + ? mergeEntries(firstEntry, secondEntry, internalCaching) + : firstEntry; + result.set(key, entry); + } + for (const [key, secondEntry] of secondInfo) { + if (!firstInfo.has(key)) { + result.set(key, secondEntry); + } + } + return serializeObject(result); +}; + +/** + * @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 + }; + } + } +}; + +/** + * @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"); +}; + +/** + * @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"); + } +}; + +/** + * @param {any} obj the object + * @returns {any} the object without operations like "..." or DELETE + */ +const removeOperations = obj => { + const newObj = {}; + 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; +}; + +exports.cachedSetProperty = cachedSetProperty; +exports.cachedCleverMerge = cachedCleverMerge; +exports.cleverMerge = cleverMerge; +exports.removeOperations = removeOperations; +exports.DELETE = DELETE; + + +/***/ }), + +/***/ 26296: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { compareRuntime } = __webpack_require__(19655); + +/** @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 = (a, b) => { + return fn(arg, a, b); + }; + 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 + */ +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; + +/** + * @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; + +/** + * @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 +); + +/** + * @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); + +/** + * @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; +}; + +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; + +/** + * @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; +}; + +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); + } + + /** + * @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(); + +/** + * @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; + /** + * @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(); + +/** + * @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; + } + }; + 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 +/** + * @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 + ) + ); +}; + +/** + * 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 && "start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } + if ("name" in a && "name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } + if ("index" in a && "index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } + return 0; +}; + + +/***/ }), + +/***/ 356: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +const toSimpleString = str => { + if (`${+str}` === str) { + return str; + } + return JSON.stringify(str); +}; + +/** + * @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})`; + } +}; + +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; +}; + +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; +}; + +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; + + +/***/ }), + +/***/ 24123: +/***/ ((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__(21301); + +const BULK_SIZE = 1000; + +const digestCache = new Map(); + +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 = ""; + } + 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; + } + + /** + * 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 cacheKey; + if (this.hash === undefined) { + // short data for hash, we can use caching + cacheKey = `${this.hashKey}-${encoding}-${this.buffer}`; + const cacheEntry = digestCache.get(cacheKey); + if (cacheEntry !== undefined) return cacheEntry; + this.hash = this.hashFactory(); + } + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + } + const digestResult = this.hash.digest(encoding); + const result = + typeof digestResult === "string" ? digestResult : digestResult.toString(); + if (cacheKey !== undefined) { + digestCache.set(cacheKey, result); + } + 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(); + } + 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"); + } +} + +let crypto = 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(); + default: + if (crypto === undefined) crypto = __webpack_require__(76417); + return new BulkUpdateDecorator( + () => crypto.createHash(algorithm), + algorithm + ); + } +}; + + +/***/ }), + +/***/ 2594: +/***/ ((__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__(31669); + +/** @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); + } + 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; +}; + +exports.createArrayToSetDeprecationSet = name => { + class SetDeprecatedArray extends Set {} + exports.arrayToSetDeprecation(SetDeprecatedArray.prototype, name); + 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) }) + ); +}; + + +/***/ }), + +/***/ 37906: +/***/ ((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)); + } + 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 {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 maxSizeValue = maxSize[key]; + if (typeof maxSizeValue === "number") { + if (size[key] > maxSizeValue) return true; + } + } + return false; +}; + +const isTooSmall = (size, minSize) => { + for (const key of Object.keys(size)) { + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (size[key] < minSizeValue) return true; + } + } + return false; +}; + +const getToSmallTypes = (size, minSize) => { + const types = new Set(); + for (const key of Object.keys(size)) { + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (size[key] < minSizeValue) types.add(key); + } + } + return types; +}; + +const getNumberOfMatchingSizeTypes = (size, types) => { + let i = 0; + for (const key of Object.keys(size)) { + if (types.has(key)) i++; + } + return i; +}; + +const selectiveSizeSum = (size, types) => { + let sum = 0; + for (const key of Object.keys(size)) { + if (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; + } +} + +/** + * @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; + } + } + 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; +}; + +/** + * @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 (initialNodes.length > 0) { + const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); + + const problemTypes = getToSmallTypes(initialGroup.size, 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 = initialGroup.popNodes( + n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + // 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)); + } + } + 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; + } + + // 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 (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 (isTooSmall(rightSize, minSize)) { + addSizeTo(rightSize, group.nodes[right].size); + right--; + } + + if (left - 1 > right) { + // 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 + let best = left - 1; + let bestSimilarity = group.similarities[best]; + for (let i = left; i <= right; i++) { + const similarity = group.similarities[i]; + if (similarity < bestSimilarity) { + best = i; + bestSimilarity = similarity; + } + } + left = best + 1; + right = best; + } + + // 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)); + } + } + } + + // 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 + }; + }); +}; + + +/***/ }), + +/***/ 31670: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sam Chen @chenxsan +*/ + + + +/** + * @param {string} urlAndGlobal the script request + * @returns {string[]} script url and its global variable + */ +module.exports = function extractUrlAndGlobal(urlAndGlobal) { + const index = urlAndGlobal.indexOf("@"); + return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; +}; + + +/***/ }), + +/***/ 38670: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +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 { + /** + * @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; + } +} + +/** + * @template T + */ +class Cycle { + constructor() { + /** @type {Set>} */ + this.nodes = new Set(); + } +} + +/** + * @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); + } + + // 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(); + + // 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]; + + // 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); + } + } + } + + // 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"); + } +}; + + +/***/ }), + +/***/ 93204: +/***/ ((__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__(85622); + +/** @typedef {import("fs").Stats} NodeFsStats */ +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ + +/** @typedef {function(NodeJS.ErrnoException=): void} Callback */ +/** @typedef {function(NodeJS.ErrnoException=, Buffer=): void} BufferCallback */ +/** @typedef {function(NodeJS.ErrnoException=, Buffer|string=): void} BufferOrStringCallback */ +/** @typedef {function(NodeJS.ErrnoException=, string[]=): void} StringArrayCallback */ +/** @typedef {function(NodeJS.ErrnoException=, string=): void} StringCallback */ +/** @typedef {function(NodeJS.ErrnoException=, number=): void} NumberCallback */ +/** @typedef {function(NodeJS.ErrnoException=, NodeFsStats=): void} StatsCallback */ +/** @typedef {function((NodeJS.ErrnoException | Error)=, any=): void} ReadJsonCallback */ + +/** + * @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(): Map} getFileTimeInfoEntries get info about files + * @property {function(): Map} getContextTimeInfoEntries get info about directories + */ + +/** + * @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 {Object} OutputFileSystem + * @property {function(string, Buffer|string, Callback): void} writeFile + * @property {function(string, Callback): void} mkdir + * @property {function(string, StatsCallback): void} stat + * @property {function(string, BufferCallback): void} readFile + * @property {(function(string, string): string)=} join + * @property {(function(string, string): string)=} relative + * @property {(function(string): string)=} dirname + */ + +/** + * @typedef {Object} InputFileSystem + * @property {function(string, BufferCallback): void} readFile + * @property {(function(string, ReadJsonCallback): void)=} readJson + * @property {function(string, BufferOrStringCallback): void} readlink + * @property {function(string, StringArrayCallback): void} readdir + * @property {function(string, StatsCallback): void} stat + * @property {(function(string, StringCallback): 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 {Object} WatchFileSystem + * @property {WatchMethod} watch + */ + +/** + * @typedef {Object} IntermediateFileSystemExtras + * @property {function(string): void} mkdirSync + * @property {function(string): import("fs").WriteStream} 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 (rootPath.startsWith("/")) { + return path.posix.relative(rootPath, targetPath); + } else if (rootPath.length > 1 && rootPath[1] === ":") { + 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; + +/** + * @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 (rootPath.startsWith("/")) { + return path.posix.join(rootPath, filename); + } else if (rootPath.length > 1 && rootPath[1] === ":") { + 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; + +/** + * @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 (absPath.startsWith("/")) { + return path.posix.dirname(absPath); + } else if (absPath.length > 1 && absPath[1] === ":") { + 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; + } + 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; + } + 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; + + +/***/ }), + +/***/ 96236: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const path = __webpack_require__(85622); + +const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; +const SEGMENTS_SPLIT_REGEXP = /([|!])/; +const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; + +/** + * @typedef {Object} MakeRelativePathsCache + * @property {Map>=} relativePaths + */ + +/** + * @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 = path.posix.relative(context, resource); + if (!resource.startsWith("../")) { + resource = "./" + 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 = resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/"); + if (!resource.startsWith("../")) { + resource = "./" + resource; + } + } + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + + // not an absolute path + return maybeAbsolutePath; +}; + +/** + * @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 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); + } + + 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 {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 { + 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; + } + }; + + 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())); + } + } 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; + } + }; + + 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 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 { + 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 getCache = associatedObjectForCache => { + const entry = cache.get(associatedObjectForCache); + if (entry !== undefined) return entry; + /** @type {Map} */ + const map = new Map(); + cache.set(associatedObjectForCache, map); + return map; + }; + + /** + * @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); + +/** + * @param {string} filename the filename which should be undone + * @param {boolean} enforceRelative true returns ./ for empty paths + * @returns {string} repeated ../ to leave the directory of the provided filename to be back on root dir + */ +exports.getUndoPath = (filename, enforceRelative) => { + let depth = -1; + for (const part of filename.split(/[/\\]+/)) { + if (part !== ".") { + depth += part === ".." ? -1 : 1; + } + } + return depth > 0 ? "../".repeat(depth) : enforceRelative ? "./" : ""; +}; + + +/***/ }), + +/***/ 7679: +/***/ ((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__(11315), + CommentCompilationWarning: () => __webpack_require__(28151), + ContextModule: () => __webpack_require__(80207), + "cache/PackFileCacheStrategy": () => + __webpack_require__(46810), + "cache/ResolverCachePlugin": () => __webpack_require__(11740), + "container/ContainerEntryDependency": () => + __webpack_require__(44055), + "container/ContainerEntryModule": () => + __webpack_require__(3234), + "container/ContainerExposedDependency": () => + __webpack_require__(50), + "container/FallbackDependency": () => + __webpack_require__(41061), + "container/FallbackItemDependency": () => + __webpack_require__(33393), + "container/FallbackModule": () => __webpack_require__(95193), + "container/RemoteModule": () => __webpack_require__(581), + "container/RemoteToExternalDependency": () => + __webpack_require__(44637), + "dependencies/AMDDefineDependency": () => + __webpack_require__(76309), + "dependencies/AMDRequireArrayDependency": () => + __webpack_require__(98233), + "dependencies/AMDRequireContextDependency": () => + __webpack_require__(60958), + "dependencies/AMDRequireDependenciesBlock": () => + __webpack_require__(69675), + "dependencies/AMDRequireDependency": () => + __webpack_require__(11311), + "dependencies/AMDRequireItemDependency": () => + __webpack_require__(90377), + "dependencies/CachedConstDependency": () => + __webpack_require__(64177), + "dependencies/CommonJsRequireContextDependency": () => + __webpack_require__(84175), + "dependencies/CommonJsExportRequireDependency": () => + __webpack_require__(76922), + "dependencies/CommonJsExportsDependency": () => + __webpack_require__(9585), + "dependencies/CommonJsFullRequireDependency": () => + __webpack_require__(29496), + "dependencies/CommonJsRequireDependency": () => + __webpack_require__(38604), + "dependencies/CommonJsSelfReferenceDependency": () => + __webpack_require__(69217), + "dependencies/ConstDependency": () => + __webpack_require__(60864), + "dependencies/ContextDependency": () => + __webpack_require__(67840), + "dependencies/ContextElementDependency": () => + __webpack_require__(83853), + "dependencies/CriticalDependencyWarning": () => + __webpack_require__(14190), + "dependencies/DelegatedSourceDependency": () => + __webpack_require__(82766), + "dependencies/DllEntryDependency": () => + __webpack_require__(57839), + "dependencies/EntryDependency": () => + __webpack_require__(41075), + "dependencies/ExportsInfoDependency": () => + __webpack_require__(30474), + "dependencies/HarmonyAcceptDependency": () => + __webpack_require__(38421), + "dependencies/HarmonyAcceptImportDependency": () => + __webpack_require__(35316), + "dependencies/HarmonyCompatibilityDependency": () => + __webpack_require__(56164), + "dependencies/HarmonyExportExpressionDependency": () => + __webpack_require__(22705), + "dependencies/HarmonyExportHeaderDependency": () => + __webpack_require__(67159), + "dependencies/HarmonyExportImportedSpecifierDependency": () => + __webpack_require__(77952), + "dependencies/HarmonyExportSpecifierDependency": () => + __webpack_require__(59042), + "dependencies/HarmonyImportSideEffectDependency": () => + __webpack_require__(76853), + "dependencies/HarmonyImportSpecifierDependency": () => + __webpack_require__(61994), + "dependencies/ImportContextDependency": () => + __webpack_require__(75785), + "dependencies/ImportDependency": () => + __webpack_require__(16727), + "dependencies/ImportEagerDependency": () => + __webpack_require__(91941), + "dependencies/ImportWeakDependency": () => + __webpack_require__(58426), + "dependencies/JsonExportsDependency": () => + __webpack_require__(36986), + "dependencies/LocalModule": () => __webpack_require__(930), + "dependencies/LocalModuleDependency": () => + __webpack_require__(67494), + "dependencies/ModuleDecoratorDependency": () => + __webpack_require__(58969), + "dependencies/ModuleHotAcceptDependency": () => + __webpack_require__(90200), + "dependencies/ModuleHotDeclineDependency": () => + __webpack_require__(72986), + "dependencies/ImportMetaHotAcceptDependency": () => + __webpack_require__(58287), + "dependencies/ImportMetaHotDeclineDependency": () => + __webpack_require__(89911), + "dependencies/ProvidedDependency": () => + __webpack_require__(88915), + "dependencies/PureExpressionDependency": () => + __webpack_require__(24746), + "dependencies/RequireContextDependency": () => + __webpack_require__(98854), + "dependencies/RequireEnsureDependenciesBlock": () => + __webpack_require__(91421), + "dependencies/RequireEnsureDependency": () => + __webpack_require__(975), + "dependencies/RequireEnsureItemDependency": () => + __webpack_require__(56867), + "dependencies/RequireHeaderDependency": () => + __webpack_require__(57010), + "dependencies/RequireIncludeDependency": () => + __webpack_require__(17046), + "dependencies/RequireIncludeDependencyParserPlugin": () => + __webpack_require__(29984), + "dependencies/RequireResolveContextDependency": () => + __webpack_require__(48789), + "dependencies/RequireResolveDependency": () => + __webpack_require__(93172), + "dependencies/RequireResolveHeaderDependency": () => + __webpack_require__(24128), + "dependencies/RuntimeRequirementsDependency": () => + __webpack_require__(75941), + "dependencies/StaticExportsDependency": () => + __webpack_require__(67967), + "dependencies/SystemPlugin": () => __webpack_require__(88768), + "dependencies/UnsupportedDependency": () => + __webpack_require__(41381), + "dependencies/URLDependency": () => __webpack_require__(30990), + "dependencies/WebAssemblyExportImportedDependency": () => + __webpack_require__(18248), + "dependencies/WebAssemblyImportDependency": () => + __webpack_require__(97093), + "dependencies/WorkerDependency": () => + __webpack_require__(73016), + "optimize/ConcatenatedModule": () => + __webpack_require__(1881), + DelegatedModule: () => __webpack_require__(68719), + DependenciesBlock: () => __webpack_require__(21484), + DllModule: () => __webpack_require__(52692), + ExternalModule: () => __webpack_require__(89805), + FileSystemInfo: () => __webpack_require__(13679), + Module: () => __webpack_require__(85887), + ModuleBuildError: () => __webpack_require__(37991), + ModuleError: () => __webpack_require__(11686), + ModuleGraph: () => __webpack_require__(20258), + ModuleParseError: () => __webpack_require__(13110), + ModuleWarning: () => __webpack_require__(92085), + NormalModule: () => __webpack_require__(11026), + RawModule: () => __webpack_require__(82329), + "sharing/ConsumeSharedModule": () => + __webpack_require__(61474), + "sharing/ConsumeSharedFallbackDependency": () => + __webpack_require__(90489), + "sharing/ProvideSharedModule": () => + __webpack_require__(65945), + "sharing/ProvideSharedDependency": () => + __webpack_require__(99355), + "sharing/ProvideForSharedDependency": () => + __webpack_require__(40235), + UnsupportedFeatureWarning: () => __webpack_require__(9532), + "util/LazySet": () => __webpack_require__(59534), + UnhandledSchemeError: () => __webpack_require__(63859), + WebpackError: () => __webpack_require__(68422), + + "util/registerExternalSerializer": () => { + // already registered + } +}; + + +/***/ }), + +/***/ 26522: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { register } = __webpack_require__(99551); + +class ClassSerializer { + constructor(Constructor) { + this.Constructor = Constructor; + this.hash = null; + } + + serialize(obj, context) { + obj.serialize(context); + } + + deserialize(context) { + if (typeof this.Constructor.deserialize === "function") { + return this.Constructor.deserialize(context); + } + const obj = new this.Constructor(); + obj.deserialize(context); + return obj; + } +} + +module.exports = (Constructor, request, name = null) => { + register(Constructor, request, name, new ClassSerializer(Constructor)); +}; + + +/***/ }), + +/***/ 8118: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +/** @template T @typedef {function(): T} FunctionReturning */ + +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memorize = fn => { + let memorized = false; + /** @type {T} */ + let result = undefined; + return () => { + if (memorized) { + return result; + } else { + result = fn(); + memorized = true; + // Allow to clean up memory for fn + // and all dependent resources + fn = undefined; + return result; + } + }; +}; + +module.exports = memorize; + + +/***/ }), + +/***/ 91679: +/***/ ((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); + } + } + 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; + } +}; + + +/***/ }), + +/***/ 86709: +/***/ ((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 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)) { + str += `.${p}`; + } else { + str += `[${JSON.stringify(p)}]`; + } + } + return str; +}; + +module.exports = propertyAccess; + + +/***/ }), + +/***/ 31107: +/***/ ((__unused_webpack_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__(99551); + +const Position = /** @type {TODO} */ __webpack_require__(17496).Position; +const SourceLocation = __webpack_require__(17496).SourceLocation; +const { ValidationError } = __webpack_require__(79286); +const { + CachedSource, + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + ReplaceSource, + SourceMapSource +} = __webpack_require__(55600); + +/** @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 */ + +/** @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()); + } + + /** + * @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()); + } + + /** + * @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; + } + })() +); + +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 {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); + } + + /** + * @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()); + } + })() +); + +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()); + } + })() +); + + +/***/ }), + +/***/ 19655: +/***/ ((__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__(67563); + +/** @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); + } + } + return result || name; + } else { + return runtime || name; + } +}; + +/** + * @param {RuntimeSpec} runtime runtime + * @param {function(string): void} fn functor + * @returns {void} + */ +exports.forEachRuntime = (runtime, fn) => { + if (runtime === undefined) { + fn(undefined); + } else if (typeof runtime === "string") { + fn(runtime); + } else { + for (const r of runtime) { + fn(r); + } + } +}; + +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("+"); +}; + +/** + * @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 + */ +exports.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; + } + } +}; + +/** + * @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; + } +}; + +/** + * @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; + } + 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") { + const set = new SortableSet(); + set.add(b); + return set; + } 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; + } + } +}; + +/** + * @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 undefined; + } 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 {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; +}; + +/** + * @template T + */ +class RuntimeSpecMap { + /** + * @param {RuntimeSpecMap=} clone copy form this + */ + constructor(clone) { + /** @type {Map} */ + this._map = new Map(clone ? clone._map : undefined); + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {T} value + */ + get(runtime) { + const key = getRuntimeKey(runtime); + return this._map.get(key); + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {boolean} true, when the runtime is stored + */ + has(runtime) { + const key = getRuntimeKey(runtime); + return this._map.has(key); + } + + set(runtime, value) { + this._map.set(getRuntimeKey(runtime), value); + } + + delete(runtime) { + this._map.delete(getRuntimeKey(runtime)); + } + + update(runtime, fn) { + const key = getRuntimeKey(runtime); + const oldValue = this._map.get(key); + const newValue = fn(oldValue); + if (newValue !== oldValue) this._map.set(key, newValue); + } + + keys() { + return Array.from(this._map.keys(), keyToRuntime); + } + + values() { + return this._map.values(); + } +} + +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); + } + + has(runtime) { + return this._map.has(getRuntimeKey(runtime)); + } + + [Symbol.iterator]() { + return this._map.values(); + } + + get size() { + return this._map.size; + } +} + +exports.RuntimeSpecSet = RuntimeSpecSet; + + +/***/ }), + +/***/ 60473: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {(string|number|undefined|[])[]} SemVerRange */ + +/** + * @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 */ +/** + * @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 "<" + + // 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; + } + i++; + } else { + // Handles remaining cases + if (aType == "o" && bType == "n") return true; + return bType == "s" || aType == "u"; + } + } +}; +/* eslint-enable eqeqeq */ +exports.versionLt = versionLt; + +/** + * @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])); + } + + // 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 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]; + } + 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 => { + if (range.length === 1) { + return "*"; + } else if (0 in range) { + var str = ""; + var fixCount = range[0]; + 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 {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; + + // 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 + } + + // Handles second column in both tables (version = undefined) + if (versionType == "u") { + if (!isEqual || rangeType != "u") { + return false; + } + } + + // 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; + } + } + + // Handle big-ver + else if (rangeType != "s" && rangeType != "n") { + if (negated || j <= fixCount) return false; + isEqual = false; + j--; + } + + // 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--; + } + + // 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; + +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", + 'if(1===range.length)return"*";if(0 in range){var r="",n=range[0];r+=0==n?">=":-1==n?"<":1==n?"^":2==n?"~":n>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return r}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 { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const BinaryMiddleware = __webpack_require__(7732); +const FileMiddleware = __webpack_require__(40572); +const ObjectMiddleware = __webpack_require__(77815); +const Serializer = __webpack_require__(24754); +const SerializerMiddleware = __webpack_require__(37063); +const SingleItemMiddleware = __webpack_require__(63340); +const internalSerializables = __webpack_require__(7679); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +const { register, registerLoader, registerNotSerializable } = ObjectMiddleware; + +const binaryMiddleware = new BinaryMiddleware(); + +// Expose serialization API +exports.register = register; +exports.registerLoader = registerLoader; +exports.registerNotSerializable = registerNotSerializable; +exports.NOT_SERIALIZABLE = ObjectMiddleware.NOT_SERIALIZABLE; +exports.MEASURE_START_OPERATION = BinaryMiddleware.MEASURE_START_OPERATION; +exports.MEASURE_END_OPERATION = BinaryMiddleware.MEASURE_END_OPERATION; +exports.buffersSerializer = new Serializer([ + new SingleItemMiddleware(), + new ObjectMiddleware(context => { + if (context.write) { + context.writeLazy = value => { + context.write(SerializerMiddleware.createLazy(value, binaryMiddleware)); + }; + } + }), + binaryMiddleware +]); +exports.createFileSerializer = fs => { + const fileMiddleware = new FileMiddleware(fs); + return new Serializer([ + new SingleItemMiddleware(), + new ObjectMiddleware(context => { + if (context.write) { + context.writeLazy = value => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + context.writeSeparate = (value, options) => { + context.write( + SerializerMiddleware.createLazy(value, fileMiddleware, options) + ); + }; + } + }), + binaryMiddleware, + fileMiddleware + ]); +}; + +__webpack_require__(31107); + +// Load internal paths with a relative require +// This allows bundling all internal serializers +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; +}); + + +/***/ }), + +/***/ 84820: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** + * @typedef {Object} GroupOptions + * @property {boolean=} groupChildren + * @property {boolean=} force + * @property {number=} targetGroupCount + */ + +/** + * @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 + */ + +/** + * @template T + * @typedef {Object} ItemWithGroups + * @property {T} item + * @property {Set} groups + */ + +/** + * @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, string]>} */ + const groupConfigMap = new Map(); + for (const item of items) { + 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 group of keys) { + const fullGroup = `${i}:${group}`; + if (!groupConfigMap.has(fullGroup)) { + groupConfigMap.set(fullGroup, [groupConfig, group]); + } + groups.add(fullGroup); + } + } + } + itemsWithGroups.add({ + item, + groups + }); + } + const alreadyGrouped = new Set(); + /** + * @param {Set>} itemsWithGroups input items with groups + * @returns {(T | R)[]} groups items + */ + const runGrouping = itemsWithGroups => { + const totalSize = itemsWithGroups.size; + /** @type {Map>>} */ + const groupMap = new Map(); + for (const entry of itemsWithGroups) { + for (const group of entry.groups) { + if (alreadyGrouped.has(group)) continue; + const list = groupMap.get(group); + if (list === undefined) { + groupMap.set(group, new Set([entry])); + } else { + list.add(entry); + } + } + } + /** @type {Set} */ + const usedGroups = new Set(); + /** @type {(T | R)[]} */ + const results = []; + for (;;) { + let bestGroup = undefined; + let bestGroupSize = -1; + let bestGroupItems = undefined; + let bestGroupOptions = undefined; + for (const [group, items] of groupMap) { + if (items.size === 0) continue; + const [groupConfig, groupKey] = groupConfigMap.get(group); + const options = + groupConfig.getOptions && + groupConfig.getOptions( + groupKey, + Array.from(items, ({ item }) => item) + ); + const force = options && options.force; + if (!force) { + if (bestGroupOptions && bestGroupOptions.force) continue; + if (usedGroups.has(group)) 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 list = groupMap.get(group); + if (list !== undefined) list.delete(item); + if (groupChildren) { + usedGroups.add(group); + } + } + } + groupMap.delete(bestGroup); + + const idx = bestGroup.indexOf(":"); + const configKey = bestGroup.slice(0, idx); + const key = bestGroup.slice(idx + 1); + const groupConfig = groupConfigs[+configKey]; + + const allItems = Array.from(items, ({ item }) => item); + + alreadyGrouped.add(bestGroup); + const children = groupChildren ? runGrouping(items) : allItems; + alreadyGrouped.delete(bestGroup); + + results.push(groupConfig.createGroup(key, children, allItems)); + } + for (const { item } of itemsWithGroups) { + results.push(item); + } + return results; + }; + return runGrouping(itemsWithGroups); +}; + +module.exports = smartGrouping; + + +/***/ }), + +/***/ 4002: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @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 {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; + + +/***/ }), + +/***/ 55959: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { validate } = __webpack_require__(79286); + +/* 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 avaiable.", + devtoolLineToLine: + "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer avaiable." +}; +/* 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.`; + } + + 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" + + " ]" + ); + } + } + } + + return formattedError; + } + } + ); +}; +module.exports = validateSchema; + + +/***/ }), + +/***/ 22681: +/***/ ((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__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); + +class AsyncWasmChunkLoadingRuntimeModule extends RuntimeModule { + constructor({ generateLoadBinaryCode, supportsStreaming }) { + super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + } + + /** + * @returns {string} runtime code + */ + 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 = AsyncWasmChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 60072: +/***/ ((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__(1826); + +/** @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; + } + + /** + * @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(); + } + + /** + * @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; + + +/***/ }), + +/***/ 33838: +/***/ ((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__(55600); +const Generator = __webpack_require__(1826); +const InitFragment = __webpack_require__(51739); +const RuntimeGlobals = __webpack_require__(49404); +const Template = __webpack_require__(92066); +const WebAssemblyImportDependency = __webpack_require__(97093); + +/** @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; + } + + /** + * @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) { + return 40 + module.dependencies.length * 10; + } + + /** + * @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(""); + + 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})` : `)`); + + const source = new RawSource( + `${importsCode}${ + promises.length > 1 + ? Template.asString([ + `${module.moduleArgument}.exports = Promise.all([${promises.join( + ", " + )}]).then(${runtimeTemplate.basicFunction( + `[${promises.join(", ")}]`, + `${importsCompatCode}return ${instantiateCall};` + )})` + ]) + : promises.length === 1 + ? Template.asString([ + `${module.moduleArgument}.exports = Promise.resolve(${ + promises[0] + }).then(${runtimeTemplate.basicFunction( + promises[0], + + `${importsCompatCode}return ${instantiateCall};` + )})` + ]) + : `${importsCompatCode}${module.moduleArgument}.exports = ${instantiateCall}` + }` + ); + return InitFragment.addToSource(source, initFragments, generateContext); + } +} + +module.exports = AsyncWebAssemblyJavascriptGenerator; + + +/***/ }), + +/***/ 13804: +/***/ ((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__(34718); +const Compilation = __webpack_require__(59622); +const Generator = __webpack_require__(1826); +const { tryRunOrWebpackError } = __webpack_require__(89935); +const WebAssemblyImportDependency = __webpack_require__(97093); +const { compareModulesByIdentifier } = __webpack_require__(26296); +const memorize = __webpack_require__(8118); + +/** @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 = memorize(() => + __webpack_require__(60072) +); +const getAsyncWebAssemblyJavascriptGenerator = memorize(() => + __webpack_require__(33838) +); +const getAsyncWebAssemblyParser = memorize(() => + __webpack_require__(20595) +); + +/** + * @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 + */ + +/** + * @typedef {Object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, RenderContext]>} renderModuleContent + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class AsyncWebAssemblyModulesPlugin { + /** + * @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" + ]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @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(); + + 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; + } + ); + } + ); + } + + 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; + + +/***/ }), + +/***/ 20595: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const t = __webpack_require__(77325); +const { decode } = __webpack_require__(81582); +const Parser = __webpack_require__(68214); +const StaticExportsDependency = __webpack_require__(67967); +const WebAssemblyImportDependency = __webpack_require__(97093); + +/** @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 {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"); + } + + // 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; + + +/***/ }), + +/***/ 13475: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const WebpackError = __webpack_require__(68422); + +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 92153: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); +const { compareModulesByIdentifier } = __webpack_require__(26296); +const WebAssemblyUtils = __webpack_require__(41520); + +/** @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; + + 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 + ); + + 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});` + ]), + "}" + ]) + }); + } + } + + 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 { + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent(importObject), + "}," + ]); + } +}; + +class WasmChunkLoadingRuntimeModule extends RuntimeModule { + constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { + super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, chunk, mangleImports } = this; + const { chunkGraph, moduleGraph, outputOptions } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + 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 + } + ); + return Template.asString([ + "// object to store loaded and loading wasm modules", + "var installedWasmModules = {};", + "", + // 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 instanceof Promise && 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 instanceof Promise) {", + 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 = WasmChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 12995: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const formatLocation = __webpack_require__(57261); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(13475); + +/** @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; + } + + 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 = WasmFinalizeExportsPlugin; + + +/***/ }), + +/***/ 35303: +/***/ ((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__(55600); +const Generator = __webpack_require__(1826); +const WebAssemblyUtils = __webpack_require__(41520); + +const t = __webpack_require__(77325); +const { + moduleContextFromModuleAST +} = __webpack_require__(48920); +const { editWithAST, addWithAST } = __webpack_require__(38811); +const { decode } = __webpack_require__(81582); + +const WebAssemblyExportImportedDependency = __webpack_require__(18248); + +/** @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 */ + +/** + * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform + */ + +/** + * @template T + * @param {Function[]} fns transforms + * @returns {Function} composed transform + */ +const compose = (...fns) => { + return fns.reduce( + (prevFn, nextFn) => { + return value => nextFn(prevFn(value)); + }, + value => value + ); +}; + +/** + * Removes the start instruction + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform + */ +const removeStartFunc = state => bin => { + return editWithAST(state.ast, bin, { + Start(path) { + path.remove(); + } + }); +}; + +/** + * Get imported globals + * + * @param {Object} ast Module's AST + * @returns {Array} - nodes + */ +const getImportedGlobals = ast => { + const importedGlobals = []; + + 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; + + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; + } + } + }); + + 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); + } + + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; + +/** + * 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 + */ +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); + + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); + } + + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; + + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; + +/** + * 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); + } +}; + +/** + * 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 = []; + + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = path.node.descr; + + globalType.mutability = "var"; + + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; + + newGlobals.push(t.global(globalType, init)); + + path.remove(); + } + }, + + // 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]; + + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; + + 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); +}; + +/** + * 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 + ); + + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } + } + }); +}; + +/** + * 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}`); + + return t.funcParam(importedGlobal.descr.valtype, id); + }); + + 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))); + } + + for (const instr of additionalInitCode) { + funcBody.push(instr); + } + + 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); + + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); + + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); +}; + +/** + * 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 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"]); + +class WebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; + } + + /** + * @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) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; + } + 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(""); + + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); + + const moduleContext = moduleContextFromModuleAST(ast.body[0]); + + 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 = []; + + const transform = compose( + rewriteExportNames({ + ast, + moduleGraph, + module, + externalExports, + runtime + }), + + removeStartFunc({ ast }), + + rewriteImportedGlobals({ ast, additionalInitCode }), + + rewriteImports({ + ast, + usedDependencyMap + }), + + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); + + const newBin = transform(bin); + + const newBuf = Buffer.from(newBin); + + return new RawSource(newBuf); + } +} + +module.exports = WebAssemblyGenerator; + + +/***/ }), + +/***/ 14073: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const WebpackError = __webpack_require__(68422); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RequestShortener")} RequestShortener */ + +/** + * @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(); + + 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); + } + } + 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; + + Error.captureStackTrace(this, this.constructor); + } +}; + + +/***/ }), + +/***/ 88890: +/***/ ((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__(55600); +const { UsageState } = __webpack_require__(4295); +const Generator = __webpack_require__(1826); +const InitFragment = __webpack_require__(51739); +const RuntimeGlobals = __webpack_require__(49404); +const Template = __webpack_require__(92066); +const ModuleDependency = __webpack_require__(80944); +const WebAssemblyExportImportedDependency = __webpack_require__(18248); +const WebAssemblyImportDependency = __webpack_require__(97093); + +/** @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 TYPES = new Set(["webassembly"]); + +class WebAssemblyJavascriptGenerator 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) { + return 95 + module.dependencies.length * 5; + } + + /** + * @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); + + 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; + } + } + } + } + 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 (!copyAllExports) { + runtimeRequirements.add(RuntimeGlobals.exports); + } + + // 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); + } +} + +module.exports = WebAssemblyJavascriptGenerator; + + +/***/ }), + +/***/ 93813: +/***/ ((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__(1826); +const WebAssemblyExportImportedDependency = __webpack_require__(18248); +const WebAssemblyImportDependency = __webpack_require__(97093); +const { compareModulesByIdentifier } = __webpack_require__(26296); +const memorize = __webpack_require__(8118); +const WebAssemblyInInitialChunkError = __webpack_require__(14073); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("../ModuleTemplate").RenderContext} RenderContext */ + +const getWebAssemblyGenerator = memorize(() => + __webpack_require__(35303) +); +const getWebAssemblyJavascriptGenerator = memorize(() => + __webpack_require__(88890) +); +const getWebAssemblyParser = memorize(() => __webpack_require__(52288)); + +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 + ); + + 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; + + 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) + }); + } + } + + 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 = WebAssemblyModulesPlugin; + + +/***/ }), + +/***/ 52288: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const t = __webpack_require__(77325); +const { + moduleContextFromModuleAST +} = __webpack_require__(48920); +const { decode } = __webpack_require__(81582); +const Parser = __webpack_require__(68214); +const StaticExportsDependency = __webpack_require__(67967); +const WebAssemblyExportImportedDependency = __webpack_require__(18248); +const WebAssemblyImportDependency = __webpack_require__(97093); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); + +/** + * @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; +}; + +/** + * 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; +}; + +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 {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"); + } + + // 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 + ); + + state.module.addDependency(dep); + + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + + state.module.addDependency(new StaticExportsDependency(exports, false)); + + return state; + } +} + +module.exports = WebAssemblyParser; + + +/***/ }), + +/***/ 41520: +/***/ ((__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__(92066); +const WebAssemblyImportDependency = __webpack_require__(97093); + +/** @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 + */ + +const MANGLED_MODULE = "a"; + +/** + * @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; + } + + 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; + + +/***/ }), + +/***/ 93943: +/***/ ((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").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". ' + + 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") { + switch (type) { + case "fetch": { + // TODO webpack 6 remove FetchCompileWasmPlugin + const FetchCompileWasmPlugin = __webpack_require__(89728); + const FetchCompileAsyncWasmPlugin = __webpack_require__(37118); + 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__(98724); + const ReadFileCompileAsyncWasmPlugin = __webpack_require__(82138); + new ReadFileCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + new ReadFileCompileAsyncWasmPlugin().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 + } + } +} + +module.exports = EnableWasmLoadingPlugin; + + +/***/ }), + +/***/ 37118: +/***/ ((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__(49404); +const AsyncWasmChunkLoadingRuntimeModule = __webpack_require__(22681); + +/** @typedef {import("../Compiler")} Compiler */ + +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) || 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 AsyncWasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true + }) + ); + }); + } + ); + } +} + +module.exports = FetchCompileAsyncWasmPlugin; + + +/***/ }), + +/***/ 89728: +/***/ ((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__(49404); +const WasmChunkLoadingRuntimeModule = __webpack_require__(92153); + +/** @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) || 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 + }) + ); + }); + } + ); + } +} + +module.exports = FetchCompileWasmPlugin; + + +/***/ }), + +/***/ 9253: +/***/ ((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__(49404); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(66032); +const { needEntryDeferringCode } = __webpack_require__(21635); + +/** @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) || 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) + ); + }; + RuntimeGlobals.ensureChunkHandlers; + RuntimeGlobals.hmrDownloadUpdateHandlers; + 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.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); + }); + + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "JsonpChunkLoadingPlugin", + (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const withDefer = needEntryDeferringCode(compilation, chunk); + if (withDefer) { + set.add(RuntimeGlobals.startup); + set.add(RuntimeGlobals.startupNoDefault); + set.add(RuntimeGlobals.require); + handler(chunk, set); + } + } + ); + } + ); + } +} + +module.exports = JsonpChunkLoadingPlugin; + + +/***/ }), + +/***/ 66032: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { SyncWaterfallHook } = __webpack_require__(34718); +const Compilation = __webpack_require__(59622); +const RuntimeGlobals = __webpack_require__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); +const chunkHasJs = __webpack_require__(76767).chunkHasJs; +const compileBooleanMatcher = __webpack_require__(356); +const { getEntryInfo, needEntryDeferringCode } = __webpack_require__(21635); + +/** @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; + } + + constructor(runtimeRequirements) { + super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, chunk } = this; + const { + runtimeTemplate, + chunkGraph, + outputOptions: { + globalObject, + chunkLoadingGlobal, + hotUpdateGlobal, + crossOriginLoading, + scriptType + } + } = compilation; + 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 withDefer = needEntryDeferringCode(compilation, chunk); + 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 entries = getEntryInfo(chunkGraph, chunk, c => + chunkHasJs(c, chunkGraph) + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const hasJsMatcher = compileBooleanMatcher( + chunkGraph.getChunkConditionMap(chunk, chunkHasJs) + ); + 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", + "// Promise = chunk loading, 0 = chunk loaded", + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};", + "", + withDefer + ? Template.asString([ + "var deferredModules = [", + Template.indent(entries.map(e => JSON.stringify(e)).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.basicFunction( + "resolve, reject", + [ + `installedChunkData = installedChunks[chunkId] = [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);` + ]), + "} 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( + __webpack_require__(82506) + ) + .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", + "", + withDefer + ? Template.asString([ + `var checkDeferredModules = ${runtimeTemplate.emptyFunction()};` + ]) + : "// no deferred startup", + "", + withDefer || withLoading + ? Template.asString([ + "// install a JSONP callback for chunk loading", + `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( + "parentChunkLoadingFunction, data", + [ + runtimeTemplate.destructureArray( + [ + "chunkIds", + "moreModules", + "runtime", + ...(withDefer ? ["executeModules"] : []) + ], + "data" + ), + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0, resolves = [];", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent( + "resolves.push(installedChunks[chunkId][0]);" + ), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + "for(moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) runtime(__webpack_require__);", + "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", + "while(resolves.length) {", + Template.indent("resolves.shift()();"), + "}", + withDefer + ? Template.asString([ + "", + "// add entry modules from loaded chunk to deferred list", + "if(executeModules) deferredModules.push.apply(deferredModules, executeModules);", + "", + "// run deferred modules when all chunks ready", + "return checkDeferredModules();" + ]) + : "" + ] + )}`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", + "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" + ]) + : "// no jsonp function", + "", + withDefer + ? Template.asString([ + "function checkDeferredModulesImpl() {", + Template.indent([ + "var result;", + "for(var i = 0; i < deferredModules.length; i++) {", + Template.indent([ + "var deferredModule = deferredModules[i];", + "var fulfilled = true;", + "for(var j = 1; j < deferredModule.length; j++) {", + Template.indent([ + "var depId = deferredModule[j];", + "if(installedChunks[depId] !== 0) fulfilled = false;" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferredModules.splice(i--, 1);", + "result = " + + "__webpack_require__(" + + `${RuntimeGlobals.entryModuleId} = deferredModule[0]);` + ]), + "}" + ]), + "}", + "if(deferredModules.length === 0) {", + Template.indent([ + `${RuntimeGlobals.startup}();`, + `${ + RuntimeGlobals.startup + } = ${runtimeTemplate.emptyFunction()};` + ]), + "}", + "return result;" + ]), + "}", + `var startup = ${RuntimeGlobals.startup};`, + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ + "// reset startup function so it can be called again when more startup code is added", + `${ + RuntimeGlobals.startup + } = startup || (${runtimeTemplate.emptyFunction()});`, + "return (checkDeferredModules = checkDeferredModulesImpl)();" + ])};` + ]) + : "// no deferred startup" + ]); + } +} + +module.exports = JsonpChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 21635: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {(string|number)[]} EntryItem */ + +// TODO move to this file to ../javascript/ChunkHelpers.js + +/** + * @param {ChunkGroup} chunkGroup a chunk group + * @returns {Set} chunks + */ +const getAllChunks = chunkGroup => { + const queue = new Set([chunkGroup]); + const chunks = new Set(); + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return chunks; +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk the chunk + * @param {function(Chunk): boolean} chunkFilter the chunk filter function + * @returns {EntryItem[]} serialized entry info: + * inner arrays have this format [module id, ...chunk ids] + */ +exports.getEntryInfo = (chunkGraph, chunk, chunkFilter) => { + return Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ).map(([module, chunkGroup]) => { + const arr = [chunkGraph.getModuleId(module)]; + for (const c of getAllChunks(chunkGroup)) { + if (!chunkFilter(c) && !c.hasRuntime()) continue; + const id = c.id; + if (id === chunk.id) continue; + arr.push(id); + } + return arr; + }); +}; + +/** + * @param {Compilation} compilation the compilation + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when other chunks have this chunk as runtime chunk + */ +exports.needEntryDeferringCode = (compilation, chunk) => { + for (const entrypoint of compilation.entrypoints.values()) { + if (entrypoint.getRuntimeChunk() === chunk) { + if (entrypoint.chunks.length > 1 || entrypoint.chunks[0] !== chunk) + return true; + } + } + for (const entrypoint of compilation.asyncEntrypoints) { + if (entrypoint.getRuntimeChunk() === chunk) { + if (entrypoint.chunks.length > 1 || entrypoint.chunks[0] !== chunk) + return true; + } + } + return false; +}; + + +/***/ }), + +/***/ 45968: +/***/ ((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__(86189); +const EnableChunkLoadingPlugin = __webpack_require__(34726); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(66032); + +/** @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); + } + + /** + * 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; + + +/***/ }), + +/***/ 86128: +/***/ ((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__(31669); +const webpackOptionsSchema = __webpack_require__(1863); +const Compiler = __webpack_require__(11777); +const MultiCompiler = __webpack_require__(73663); +const WebpackOptionsApply = __webpack_require__(44137); +const { + applyWebpackOptionsDefaults, + applyWebpackOptionsBaseDefaults +} = __webpack_require__(27057); +const { getNormalizedWebpackOptions } = __webpack_require__(52975); +const NodeEnvironmentPlugin = __webpack_require__(38857); +const validateSchema = __webpack_require__(55959); + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Stats")} Stats */ + +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} stats + * @returns {void} + */ + +/** + * @param {WebpackOptions[]} childOptions options array + * @returns {MultiCompiler} a multi-compiler + */ +const createMultiCompiler = childOptions => { + const compilers = childOptions.map(options => createCompiler(options)); + const compiler = new MultiCompiler(compilers); + 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 + */ +const createCompiler = rawOptions => { + const options = getNormalizedWebpackOptions(rawOptions); + applyWebpackOptionsBaseDefaults(options); + const compiler = new Compiler(options.context); + compiler.options = 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; +}; + +/** + * @callback WebpackFunctionSingle + * @param {WebpackOptions} options options object + * @param {Callback=} callback callback + * @returns {Compiler} the compiler object + */ + +/** + * @callback WebpackFunctionMulti + * @param {WebpackOptions[]} options options objects + * @param {Callback=} callback callback + * @returns {MultiCompiler} the multi compiler object + */ + +const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ (( + options, + callback +) => { + const create = () => { + validateSchema(webpackOptionsSchema, options); + /** @type {MultiCompiler|Compiler} */ + let compiler; + let watch = false; + /** @type {WatchOptions|WatchOptions[]} */ + let watchOptions; + if (Array.isArray(options)) { + /** @type {MultiCompiler} */ + compiler = createMultiCompiler(options); + watch = options.some(options => options.watch); + watchOptions = options.map(options => options.watchOptions || {}); + } else { + /** @type {Compiler} */ + compiler = createCompiler(options); + watch = options.watch; + watchOptions = options.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 need 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; + + +/***/ }), + +/***/ 56354: +/***/ ((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__(49404); +const StartupChunkDependenciesPlugin = __webpack_require__(23613); +const ImportScriptsChunkLoadingRuntimeModule = __webpack_require__(45936); + +/** @typedef {import("../Compiler")} Compiler */ + +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) || 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; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ImportScriptsChunkLoadingRuntimeModule(set) + ); + }; + 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); + + 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 = ImportScriptsChunkLoadingPlugin; + + +/***/ }), + +/***/ 45936: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(49404); +const RuntimeModule = __webpack_require__(61439); +const Template = __webpack_require__(92066); +const { + getChunkFilenameTemplate +} = __webpack_require__(76767); +const { getUndoPath } = __webpack_require__(96236); + +class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { + chunk, + compilation: { + runtimeTemplate, + outputOptions: { globalObject, chunkLoadingGlobal, hotUpdateGlobal } + } + } = this; + 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 outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath(outputName, false); + 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 = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") + ), + "};", + "", + withLoading + ? Template.asString([ + "// importScripts chunk loading", + `var chunkLoadingCallback = ${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);" + ] + )};`, + `${fn}.i = ${runtimeTemplate.basicFunction("chunkId, promises", [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + `importScripts(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId));` + ]), + "}" + ])};`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", + "chunkLoadingGlobal.push = chunkLoadingCallback;" + ]) + : "// 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(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getChunkUpdateScriptFilename + }(chunkId));`, + 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' + ]), + "}", + "", + Template.getFunctionContent( + __webpack_require__(82506) + ) + .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" + ]); + } +} + +module.exports = ImportScriptsChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 9460: +/***/ ((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__(86189); +const EnableChunkLoadingPlugin = __webpack_require__(34726); + +/** @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; + + +/***/ }), + +/***/ 25899: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.cloneNode = cloneNode; + +function cloneNode(n) { + return Object.assign({}, n); +} + +/***/ }), + +/***/ 77325: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + numberLiteralFromRaw: true, + withLoc: true, + withRaw: true, + funcParam: true, + indexLiteral: true, + memIndexLiteral: true, + instruction: true, + objectInstruction: true, + traverse: true, + signatures: true, + cloneNode: true +}; +Object.defineProperty(exports, "numberLiteralFromRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.numberLiteralFromRaw; + } +})); +Object.defineProperty(exports, "withLoc", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withLoc; + } +})); +Object.defineProperty(exports, "withRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withRaw; + } +})); +Object.defineProperty(exports, "funcParam", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.funcParam; + } +})); +Object.defineProperty(exports, "indexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.indexLiteral; + } +})); +Object.defineProperty(exports, "memIndexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.memIndexLiteral; + } +})); +Object.defineProperty(exports, "instruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.instruction; + } +})); +Object.defineProperty(exports, "objectInstruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.objectInstruction; + } +})); +Object.defineProperty(exports, "traverse", ({ + enumerable: true, + get: function get() { + return _traverse.traverse; + } +})); +Object.defineProperty(exports, "signatures", ({ + enumerable: true, + get: function get() { + return _signatures.signatures; + } +})); +Object.defineProperty(exports, "cloneNode", ({ + enumerable: true, + get: function get() { + return _clone.cloneNode; + } +})); + +var _nodes = __webpack_require__(5600); + +Object.keys(_nodes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _nodes[key]; + } + }); +}); + +var _nodeHelpers = __webpack_require__(4218); + +var _traverse = __webpack_require__(16608); + +var _signatures = __webpack_require__(24143); + +var _utils = __webpack_require__(13892); + +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); + +var _clone = __webpack_require__(25899); + +/***/ }), + +/***/ 4218: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.numberLiteralFromRaw = numberLiteralFromRaw; +exports.instruction = instruction; +exports.objectInstruction = objectInstruction; +exports.withLoc = withLoc; +exports.withRaw = withRaw; +exports.funcParam = funcParam; +exports.indexLiteral = indexLiteral; +exports.memIndexLiteral = memIndexLiteral; + +var _wastParser = __webpack_require__(65130); + +var _nodes = __webpack_require__(5600); + +function numberLiteralFromRaw(rawValue) { + var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32"; + var original = rawValue; // Remove numeric separators _ + + if (typeof rawValue === "string") { + rawValue = rawValue.replace(/_/g, ""); + } + + if (typeof rawValue === "number") { + return (0, _nodes.numberLiteral)(rawValue, String(original)); + } else { + switch (instructionType) { + case "i32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parse32I)(rawValue), String(original)); + } + + case "u32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parseU32)(rawValue), String(original)); + } + + case "i64": + { + return (0, _nodes.longNumberLiteral)((0, _wastParser.parse64I)(rawValue), String(original)); + } + + case "f32": + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse32F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + // f64 + + default: + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + } + } +} + +function instruction(id) { + var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return (0, _nodes.instr)(id, undefined, args, namedArgs); +} + +function objectInstruction(id, object) { + var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + return (0, _nodes.instr)(id, object, args, namedArgs); +} +/** + * Decorators + */ + + +function withLoc(n, end, start) { + var loc = { + start: start, + end: end + }; + n.loc = loc; + return n; +} + +function withRaw(n, raw) { + n.raw = raw; + return n; +} + +function funcParam(valtype, id) { + return { + id: id, + valtype: valtype + }; +} + +function indexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} + +function memIndexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} + +/***/ }), + +/***/ 41570: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPath = createPath; + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +function findParent(_ref, cb) { + var parentPath = _ref.parentPath; + + if (parentPath == null) { + throw new Error("node is root"); + } + + var currentPath = parentPath; + + while (cb(currentPath) !== false) { + // Hit the root node, stop + // $FlowIgnore + if (currentPath.parentPath == null) { + return null; + } // $FlowIgnore + + + currentPath = currentPath.parentPath; + } + + return currentPath.node; +} + +function insertBefore(context, newNode) { + return insert(context, newNode); +} + +function insertAfter(context, newNode) { + return insert(context, newNode, 1); +} + +function insert(_ref2, newNode) { + var node = _ref2.node, + inList = _ref2.inList, + parentPath = _ref2.parentPath, + parentKey = _ref2.parentKey; + var indexOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (!inList) { + throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); + } + + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } + + // $FlowIgnore + var parentList = parentPath.node[parentKey]; + var indexInList = parentList.findIndex(function (n) { + return n === node; + }); + parentList.splice(indexInList + indexOffset, 0, newNode); +} + +function remove(_ref3) { + var node = _ref3.node, + parentKey = _ref3.parentKey, + parentPath = _ref3.parentPath; + + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } + + // $FlowIgnore + var parentNode = parentPath.node; // $FlowIgnore + + var parentProperty = parentNode[parentKey]; + + if (Array.isArray(parentProperty)) { + // $FlowIgnore + parentNode[parentKey] = parentProperty.filter(function (n) { + return n !== node; + }); + } else { + // $FlowIgnore + delete parentNode[parentKey]; + } + + node._deleted = true; +} + +function stop(context) { + context.shouldStop = true; +} + +function replaceWith(context, newNode) { + // $FlowIgnore + var parentNode = context.parentPath.node; // $FlowIgnore + + var parentProperty = parentNode[context.parentKey]; + + if (Array.isArray(parentProperty)) { + var indexInList = parentProperty.findIndex(function (n) { + return n === context.node; + }); + parentProperty.splice(indexInList, 1, newNode); + } else { + // $FlowIgnore + parentNode[context.parentKey] = newNode; + } + + context.node._deleted = true; + context.node = newNode; +} // bind the context to the first argument of node operations + + +function bindNodeOperations(operations, context) { + var keys = Object.keys(operations); + var boundOperations = {}; + keys.forEach(function (key) { + boundOperations[key] = operations[key].bind(null, context); + }); + return boundOperations; +} + +function createPathOperations(context) { + // $FlowIgnore + return bindNodeOperations({ + findParent: findParent, + replaceWith: replaceWith, + remove: remove, + insertBefore: insertBefore, + insertAfter: insertAfter, + stop: stop + }, context); +} + +function createPath(context) { + var path = _extends({}, context); // $FlowIgnore + + + Object.assign(path, createPathOperations(path)); // $FlowIgnore + + return path; +} + +/***/ }), + +/***/ 5600: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.module = _module; +exports.moduleMetadata = moduleMetadata; +exports.moduleNameMetadata = moduleNameMetadata; +exports.functionNameMetadata = functionNameMetadata; +exports.localNameMetadata = localNameMetadata; +exports.binaryModule = binaryModule; +exports.quoteModule = quoteModule; +exports.sectionMetadata = sectionMetadata; +exports.producersSectionMetadata = producersSectionMetadata; +exports.producerMetadata = producerMetadata; +exports.producerMetadataVersionedName = producerMetadataVersionedName; +exports.loopInstruction = loopInstruction; +exports.instr = instr; +exports.ifInstruction = ifInstruction; +exports.stringLiteral = stringLiteral; +exports.numberLiteral = numberLiteral; +exports.longNumberLiteral = longNumberLiteral; +exports.floatLiteral = floatLiteral; +exports.elem = elem; +exports.indexInFuncSection = indexInFuncSection; +exports.valtypeLiteral = valtypeLiteral; +exports.typeInstruction = typeInstruction; +exports.start = start; +exports.globalType = globalType; +exports.leadingComment = leadingComment; +exports.blockComment = blockComment; +exports.data = data; +exports.global = global; +exports.table = table; +exports.memory = memory; +exports.funcImportDescr = funcImportDescr; +exports.moduleImport = moduleImport; +exports.moduleExportDescr = moduleExportDescr; +exports.moduleExport = moduleExport; +exports.limit = limit; +exports.signature = signature; +exports.program = program; +exports.identifier = identifier; +exports.blockInstruction = blockInstruction; +exports.callInstruction = callInstruction; +exports.callIndirectInstruction = callIndirectInstruction; +exports.byteArray = byteArray; +exports.func = func; +exports.internalBrUnless = internalBrUnless; +exports.internalGoto = internalGoto; +exports.internalCallExtern = internalCallExtern; +exports.internalEndAndReturn = internalEndAndReturn; +exports.assertInternalCallExtern = exports.assertInternalGoto = exports.assertInternalBrUnless = exports.assertFunc = exports.assertByteArray = exports.assertCallIndirectInstruction = exports.assertCallInstruction = exports.assertBlockInstruction = exports.assertIdentifier = exports.assertProgram = exports.assertSignature = exports.assertLimit = exports.assertModuleExport = exports.assertModuleExportDescr = exports.assertModuleImport = exports.assertFuncImportDescr = exports.assertMemory = exports.assertTable = exports.assertGlobal = exports.assertData = exports.assertBlockComment = exports.assertLeadingComment = exports.assertGlobalType = exports.assertStart = exports.assertTypeInstruction = exports.assertValtypeLiteral = exports.assertIndexInFuncSection = exports.assertElem = exports.assertFloatLiteral = exports.assertLongNumberLiteral = exports.assertNumberLiteral = exports.assertStringLiteral = exports.assertIfInstruction = exports.assertInstr = exports.assertLoopInstruction = exports.assertProducerMetadataVersionedName = exports.assertProducerMetadata = exports.assertProducersSectionMetadata = exports.assertSectionMetadata = exports.assertQuoteModule = exports.assertBinaryModule = exports.assertLocalNameMetadata = exports.assertFunctionNameMetadata = exports.assertModuleNameMetadata = exports.assertModuleMetadata = exports.assertModule = exports.isIntrinsic = exports.isImportDescr = exports.isNumericLiteral = exports.isExpression = exports.isInstruction = exports.isBlock = exports.isNode = exports.isInternalEndAndReturn = exports.isInternalCallExtern = exports.isInternalGoto = exports.isInternalBrUnless = exports.isFunc = exports.isByteArray = exports.isCallIndirectInstruction = exports.isCallInstruction = exports.isBlockInstruction = exports.isIdentifier = exports.isProgram = exports.isSignature = exports.isLimit = exports.isModuleExport = exports.isModuleExportDescr = exports.isModuleImport = exports.isFuncImportDescr = exports.isMemory = exports.isTable = exports.isGlobal = exports.isData = exports.isBlockComment = exports.isLeadingComment = exports.isGlobalType = exports.isStart = exports.isTypeInstruction = exports.isValtypeLiteral = exports.isIndexInFuncSection = exports.isElem = exports.isFloatLiteral = exports.isLongNumberLiteral = exports.isNumberLiteral = exports.isStringLiteral = exports.isIfInstruction = exports.isInstr = exports.isLoopInstruction = exports.isProducerMetadataVersionedName = exports.isProducerMetadata = exports.isProducersSectionMetadata = exports.isSectionMetadata = exports.isQuoteModule = exports.isBinaryModule = exports.isLocalNameMetadata = exports.isFunctionNameMetadata = exports.isModuleNameMetadata = exports.isModuleMetadata = exports.isModule = void 0; +exports.nodeAndUnionTypes = exports.unionTypesMap = exports.assertInternalEndAndReturn = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +// THIS FILE IS AUTOGENERATED +// see scripts/generateNodeUtils.js +function isTypeOf(t) { + return function (n) { + return n.type === t; + }; +} + +function assertTypeOf(t) { + return function (n) { + return function () { + if (!(n.type === t)) { + throw new Error('n.type === t' + " error: " + (undefined || "unknown")); + } + }(); + }; +} + +function _module(id, fields, metadata) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(fields) === "object" && typeof fields.length !== "undefined")) { + throw new Error('typeof fields === "object" && typeof fields.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Module", + id: id, + fields: fields + }; + + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } + + return node; +} + +function moduleMetadata(sections, functionNames, localNames, producers) { + if (!(_typeof(sections) === "object" && typeof sections.length !== "undefined")) { + throw new Error('typeof sections === "object" && typeof sections.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (functionNames !== null && functionNames !== undefined) { + if (!(_typeof(functionNames) === "object" && typeof functionNames.length !== "undefined")) { + throw new Error('typeof functionNames === "object" && typeof functionNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + if (localNames !== null && localNames !== undefined) { + if (!(_typeof(localNames) === "object" && typeof localNames.length !== "undefined")) { + throw new Error('typeof localNames === "object" && typeof localNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + if (producers !== null && producers !== undefined) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "ModuleMetadata", + sections: sections + }; + + if (typeof functionNames !== "undefined" && functionNames.length > 0) { + node.functionNames = functionNames; + } + + if (typeof localNames !== "undefined" && localNames.length > 0) { + node.localNames = localNames; + } + + if (typeof producers !== "undefined" && producers.length > 0) { + node.producers = producers; + } + + return node; +} + +function moduleNameMetadata(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "ModuleNameMetadata", + value: value + }; + return node; +} + +function functionNameMetadata(value, index) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (!(typeof index === "number")) { + throw new Error('typeof index === "number"' + " error: " + ("Argument index must be of type number, given: " + _typeof(index) || 0)); + } + + var node = { + type: "FunctionNameMetadata", + value: value, + index: index + }; + return node; +} + +function localNameMetadata(value, localIndex, functionIndex) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (!(typeof localIndex === "number")) { + throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); + } + + if (!(typeof functionIndex === "number")) { + throw new Error('typeof functionIndex === "number"' + " error: " + ("Argument functionIndex must be of type number, given: " + _typeof(functionIndex) || 0)); + } + + var node = { + type: "LocalNameMetadata", + value: value, + localIndex: localIndex, + functionIndex: functionIndex + }; + return node; +} + +function binaryModule(id, blob) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(blob) === "object" && typeof blob.length !== "undefined")) { + throw new Error('typeof blob === "object" && typeof blob.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "BinaryModule", + id: id, + blob: blob + }; + return node; +} + +function quoteModule(id, string) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + + if (!(_typeof(string) === "object" && typeof string.length !== "undefined")) { + throw new Error('typeof string === "object" && typeof string.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "QuoteModule", + id: id, + string: string + }; + return node; +} + +function sectionMetadata(section, startOffset, size, vectorOfSize) { + if (!(typeof startOffset === "number")) { + throw new Error('typeof startOffset === "number"' + " error: " + ("Argument startOffset must be of type number, given: " + _typeof(startOffset) || 0)); + } + + var node = { + type: "SectionMetadata", + section: section, + startOffset: startOffset, + size: size, + vectorOfSize: vectorOfSize + }; + return node; +} + +function producersSectionMetadata(producers) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ProducersSectionMetadata", + producers: producers + }; + return node; +} + +function producerMetadata(language, processedBy, sdk) { + if (!(_typeof(language) === "object" && typeof language.length !== "undefined")) { + throw new Error('typeof language === "object" && typeof language.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(processedBy) === "object" && typeof processedBy.length !== "undefined")) { + throw new Error('typeof processedBy === "object" && typeof processedBy.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(sdk) === "object" && typeof sdk.length !== "undefined")) { + throw new Error('typeof sdk === "object" && typeof sdk.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ProducerMetadata", + language: language, + processedBy: processedBy, + sdk: sdk + }; + return node; +} + +function producerMetadataVersionedName(name, version) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + if (!(typeof version === "string")) { + throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); + } + + var node = { + type: "ProducerMetadataVersionedName", + name: name, + version: version + }; + return node; +} + +function loopInstruction(label, resulttype, instr) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "LoopInstruction", + id: "loop", + label: label, + resulttype: resulttype, + instr: instr + }; + return node; +} + +function instr(id, object, args, namedArgs) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + + if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { + throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Instr", + id: id, + args: args + }; + + if (typeof object !== "undefined") { + node.object = object; + } + + if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { + node.namedArgs = namedArgs; + } + + return node; +} + +function ifInstruction(testLabel, test, result, consequent, alternate) { + if (!(_typeof(test) === "object" && typeof test.length !== "undefined")) { + throw new Error('typeof test === "object" && typeof test.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(consequent) === "object" && typeof consequent.length !== "undefined")) { + throw new Error('typeof consequent === "object" && typeof consequent.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(alternate) === "object" && typeof alternate.length !== "undefined")) { + throw new Error('typeof alternate === "object" && typeof alternate.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "IfInstruction", + id: "if", + testLabel: testLabel, + test: test, + result: result, + consequent: consequent, + alternate: alternate + }; + return node; +} + +function stringLiteral(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "StringLiteral", + value: value + }; + return node; +} + +function numberLiteral(value, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } + + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "NumberLiteral", + value: value, + raw: raw + }; + return node; +} + +function longNumberLiteral(value, raw) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "LongNumberLiteral", + value: value, + raw: raw + }; + return node; +} + +function floatLiteral(value, nan, inf, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } + + if (nan !== null && nan !== undefined) { + if (!(typeof nan === "boolean")) { + throw new Error('typeof nan === "boolean"' + " error: " + ("Argument nan must be of type boolean, given: " + _typeof(nan) || 0)); + } + } + + if (inf !== null && inf !== undefined) { + if (!(typeof inf === "boolean")) { + throw new Error('typeof inf === "boolean"' + " error: " + ("Argument inf must be of type boolean, given: " + _typeof(inf) || 0)); + } + } + + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + + var node = { + type: "FloatLiteral", + value: value, + raw: raw + }; + + if (nan === true) { + node.nan = true; + } + + if (inf === true) { + node.inf = true; + } + + return node; +} + +function elem(table, offset, funcs) { + if (!(_typeof(offset) === "object" && typeof offset.length !== "undefined")) { + throw new Error('typeof offset === "object" && typeof offset.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(funcs) === "object" && typeof funcs.length !== "undefined")) { + throw new Error('typeof funcs === "object" && typeof funcs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Elem", + table: table, + offset: offset, + funcs: funcs + }; + return node; +} + +function indexInFuncSection(index) { + var node = { + type: "IndexInFuncSection", + index: index + }; + return node; +} + +function valtypeLiteral(name) { + var node = { + type: "ValtypeLiteral", + name: name + }; + return node; +} + +function typeInstruction(id, functype) { + var node = { + type: "TypeInstruction", + id: id, + functype: functype + }; + return node; +} + +function start(index) { + var node = { + type: "Start", + index: index + }; + return node; +} + +function globalType(valtype, mutability) { + var node = { + type: "GlobalType", + valtype: valtype, + mutability: mutability + }; + return node; +} + +function leadingComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "LeadingComment", + value: value + }; + return node; +} + +function blockComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "BlockComment", + value: value + }; + return node; +} + +function data(memoryIndex, offset, init) { + var node = { + type: "Data", + memoryIndex: memoryIndex, + offset: offset, + init: init + }; + return node; +} + +function global(globalType, init, name) { + if (!(_typeof(init) === "object" && typeof init.length !== "undefined")) { + throw new Error('typeof init === "object" && typeof init.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Global", + globalType: globalType, + init: init, + name: name + }; + return node; +} + +function table(elementType, limits, name, elements) { + if (!(limits.type === "Limit")) { + throw new Error('limits.type === "Limit"' + " error: " + ("Argument limits must be of type Limit, given: " + limits.type || 0)); + } + + if (elements !== null && elements !== undefined) { + if (!(_typeof(elements) === "object" && typeof elements.length !== "undefined")) { + throw new Error('typeof elements === "object" && typeof elements.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "Table", + elementType: elementType, + limits: limits, + name: name + }; + + if (typeof elements !== "undefined" && elements.length > 0) { + node.elements = elements; + } + + return node; +} + +function memory(limits, id) { + var node = { + type: "Memory", + limits: limits, + id: id + }; + return node; +} + +function funcImportDescr(id, signature) { + var node = { + type: "FuncImportDescr", + id: id, + signature: signature + }; + return node; +} + +function moduleImport(module, name, descr) { + if (!(typeof module === "string")) { + throw new Error('typeof module === "string"' + " error: " + ("Argument module must be of type string, given: " + _typeof(module) || 0)); + } + + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleImport", + module: module, + name: name, + descr: descr + }; + return node; +} + +function moduleExportDescr(exportType, id) { + var node = { + type: "ModuleExportDescr", + exportType: exportType, + id: id + }; + return node; +} + +function moduleExport(name, descr) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleExport", + name: name, + descr: descr + }; + return node; +} + +function limit(min, max) { + if (!(typeof min === "number")) { + throw new Error('typeof min === "number"' + " error: " + ("Argument min must be of type number, given: " + _typeof(min) || 0)); + } + + if (max !== null && max !== undefined) { + if (!(typeof max === "number")) { + throw new Error('typeof max === "number"' + " error: " + ("Argument max must be of type number, given: " + _typeof(max) || 0)); + } + } + + var node = { + type: "Limit", + min: min + }; + + if (typeof max !== "undefined") { + node.max = max; + } + + return node; +} + +function signature(params, results) { + if (!(_typeof(params) === "object" && typeof params.length !== "undefined")) { + throw new Error('typeof params === "object" && typeof params.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(results) === "object" && typeof results.length !== "undefined")) { + throw new Error('typeof results === "object" && typeof results.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Signature", + params: params, + results: results + }; + return node; +} + +function program(body) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Program", + body: body + }; + return node; +} + +function identifier(value, raw) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (raw !== null && raw !== undefined) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + } + + var node = { + type: "Identifier", + value: value + }; + + if (typeof raw !== "undefined") { + node.raw = raw; + } + + return node; +} + +function blockInstruction(label, instr, result) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "BlockInstruction", + id: "block", + label: label, + instr: instr, + result: result + }; + return node; +} + +function callInstruction(index, instrArgs, numeric) { + if (instrArgs !== null && instrArgs !== undefined) { + if (!(_typeof(instrArgs) === "object" && typeof instrArgs.length !== "undefined")) { + throw new Error('typeof instrArgs === "object" && typeof instrArgs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallInstruction", + id: "call", + index: index + }; + + if (typeof instrArgs !== "undefined" && instrArgs.length > 0) { + node.instrArgs = instrArgs; + } + + if (typeof numeric !== "undefined") { + node.numeric = numeric; + } + + return node; +} + +function callIndirectInstruction(signature, intrs) { + if (intrs !== null && intrs !== undefined) { + if (!(_typeof(intrs) === "object" && typeof intrs.length !== "undefined")) { + throw new Error('typeof intrs === "object" && typeof intrs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallIndirectInstruction", + id: "call_indirect", + signature: signature + }; + + if (typeof intrs !== "undefined" && intrs.length > 0) { + node.intrs = intrs; + } + + return node; +} + +function byteArray(values) { + if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { + throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ByteArray", + values: values + }; + return node; +} + +function func(name, signature, body, isExternal, metadata) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (isExternal !== null && isExternal !== undefined) { + if (!(typeof isExternal === "boolean")) { + throw new Error('typeof isExternal === "boolean"' + " error: " + ("Argument isExternal must be of type boolean, given: " + _typeof(isExternal) || 0)); + } + } + + var node = { + type: "Func", + name: name, + signature: signature, + body: body + }; + + if (isExternal === true) { + node.isExternal = true; + } + + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } + + return node; +} + +function internalBrUnless(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalBrUnless", + target: target + }; + return node; +} + +function internalGoto(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalGoto", + target: target + }; + return node; +} + +function internalCallExtern(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalCallExtern", + target: target + }; + return node; +} + +function internalEndAndReturn() { + var node = { + type: "InternalEndAndReturn" + }; + return node; +} + +var isModule = isTypeOf("Module"); +exports.isModule = isModule; +var isModuleMetadata = isTypeOf("ModuleMetadata"); +exports.isModuleMetadata = isModuleMetadata; +var isModuleNameMetadata = isTypeOf("ModuleNameMetadata"); +exports.isModuleNameMetadata = isModuleNameMetadata; +var isFunctionNameMetadata = isTypeOf("FunctionNameMetadata"); +exports.isFunctionNameMetadata = isFunctionNameMetadata; +var isLocalNameMetadata = isTypeOf("LocalNameMetadata"); +exports.isLocalNameMetadata = isLocalNameMetadata; +var isBinaryModule = isTypeOf("BinaryModule"); +exports.isBinaryModule = isBinaryModule; +var isQuoteModule = isTypeOf("QuoteModule"); +exports.isQuoteModule = isQuoteModule; +var isSectionMetadata = isTypeOf("SectionMetadata"); +exports.isSectionMetadata = isSectionMetadata; +var isProducersSectionMetadata = isTypeOf("ProducersSectionMetadata"); +exports.isProducersSectionMetadata = isProducersSectionMetadata; +var isProducerMetadata = isTypeOf("ProducerMetadata"); +exports.isProducerMetadata = isProducerMetadata; +var isProducerMetadataVersionedName = isTypeOf("ProducerMetadataVersionedName"); +exports.isProducerMetadataVersionedName = isProducerMetadataVersionedName; +var isLoopInstruction = isTypeOf("LoopInstruction"); +exports.isLoopInstruction = isLoopInstruction; +var isInstr = isTypeOf("Instr"); +exports.isInstr = isInstr; +var isIfInstruction = isTypeOf("IfInstruction"); +exports.isIfInstruction = isIfInstruction; +var isStringLiteral = isTypeOf("StringLiteral"); +exports.isStringLiteral = isStringLiteral; +var isNumberLiteral = isTypeOf("NumberLiteral"); +exports.isNumberLiteral = isNumberLiteral; +var isLongNumberLiteral = isTypeOf("LongNumberLiteral"); +exports.isLongNumberLiteral = isLongNumberLiteral; +var isFloatLiteral = isTypeOf("FloatLiteral"); +exports.isFloatLiteral = isFloatLiteral; +var isElem = isTypeOf("Elem"); +exports.isElem = isElem; +var isIndexInFuncSection = isTypeOf("IndexInFuncSection"); +exports.isIndexInFuncSection = isIndexInFuncSection; +var isValtypeLiteral = isTypeOf("ValtypeLiteral"); +exports.isValtypeLiteral = isValtypeLiteral; +var isTypeInstruction = isTypeOf("TypeInstruction"); +exports.isTypeInstruction = isTypeInstruction; +var isStart = isTypeOf("Start"); +exports.isStart = isStart; +var isGlobalType = isTypeOf("GlobalType"); +exports.isGlobalType = isGlobalType; +var isLeadingComment = isTypeOf("LeadingComment"); +exports.isLeadingComment = isLeadingComment; +var isBlockComment = isTypeOf("BlockComment"); +exports.isBlockComment = isBlockComment; +var isData = isTypeOf("Data"); +exports.isData = isData; +var isGlobal = isTypeOf("Global"); +exports.isGlobal = isGlobal; +var isTable = isTypeOf("Table"); +exports.isTable = isTable; +var isMemory = isTypeOf("Memory"); +exports.isMemory = isMemory; +var isFuncImportDescr = isTypeOf("FuncImportDescr"); +exports.isFuncImportDescr = isFuncImportDescr; +var isModuleImport = isTypeOf("ModuleImport"); +exports.isModuleImport = isModuleImport; +var isModuleExportDescr = isTypeOf("ModuleExportDescr"); +exports.isModuleExportDescr = isModuleExportDescr; +var isModuleExport = isTypeOf("ModuleExport"); +exports.isModuleExport = isModuleExport; +var isLimit = isTypeOf("Limit"); +exports.isLimit = isLimit; +var isSignature = isTypeOf("Signature"); +exports.isSignature = isSignature; +var isProgram = isTypeOf("Program"); +exports.isProgram = isProgram; +var isIdentifier = isTypeOf("Identifier"); +exports.isIdentifier = isIdentifier; +var isBlockInstruction = isTypeOf("BlockInstruction"); +exports.isBlockInstruction = isBlockInstruction; +var isCallInstruction = isTypeOf("CallInstruction"); +exports.isCallInstruction = isCallInstruction; +var isCallIndirectInstruction = isTypeOf("CallIndirectInstruction"); +exports.isCallIndirectInstruction = isCallIndirectInstruction; +var isByteArray = isTypeOf("ByteArray"); +exports.isByteArray = isByteArray; +var isFunc = isTypeOf("Func"); +exports.isFunc = isFunc; +var isInternalBrUnless = isTypeOf("InternalBrUnless"); +exports.isInternalBrUnless = isInternalBrUnless; +var isInternalGoto = isTypeOf("InternalGoto"); +exports.isInternalGoto = isInternalGoto; +var isInternalCallExtern = isTypeOf("InternalCallExtern"); +exports.isInternalCallExtern = isInternalCallExtern; +var isInternalEndAndReturn = isTypeOf("InternalEndAndReturn"); +exports.isInternalEndAndReturn = isInternalEndAndReturn; + +var isNode = function isNode(node) { + return isModule(node) || isModuleMetadata(node) || isModuleNameMetadata(node) || isFunctionNameMetadata(node) || isLocalNameMetadata(node) || isBinaryModule(node) || isQuoteModule(node) || isSectionMetadata(node) || isProducersSectionMetadata(node) || isProducerMetadata(node) || isProducerMetadataVersionedName(node) || isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isElem(node) || isIndexInFuncSection(node) || isValtypeLiteral(node) || isTypeInstruction(node) || isStart(node) || isGlobalType(node) || isLeadingComment(node) || isBlockComment(node) || isData(node) || isGlobal(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node) || isModuleImport(node) || isModuleExportDescr(node) || isModuleExport(node) || isLimit(node) || isSignature(node) || isProgram(node) || isIdentifier(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node) || isByteArray(node) || isFunc(node) || isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isNode = isNode; + +var isBlock = function isBlock(node) { + return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); +}; + +exports.isBlock = isBlock; + +var isInstruction = function isInstruction(node) { + return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); +}; + +exports.isInstruction = isInstruction; + +var isExpression = function isExpression(node) { + return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); +}; + +exports.isExpression = isExpression; + +var isNumericLiteral = function isNumericLiteral(node) { + return isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node); +}; + +exports.isNumericLiteral = isNumericLiteral; + +var isImportDescr = function isImportDescr(node) { + return isGlobalType(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node); +}; + +exports.isImportDescr = isImportDescr; + +var isIntrinsic = function isIntrinsic(node) { + return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isIntrinsic = isIntrinsic; +var assertModule = assertTypeOf("Module"); +exports.assertModule = assertModule; +var assertModuleMetadata = assertTypeOf("ModuleMetadata"); +exports.assertModuleMetadata = assertModuleMetadata; +var assertModuleNameMetadata = assertTypeOf("ModuleNameMetadata"); +exports.assertModuleNameMetadata = assertModuleNameMetadata; +var assertFunctionNameMetadata = assertTypeOf("FunctionNameMetadata"); +exports.assertFunctionNameMetadata = assertFunctionNameMetadata; +var assertLocalNameMetadata = assertTypeOf("LocalNameMetadata"); +exports.assertLocalNameMetadata = assertLocalNameMetadata; +var assertBinaryModule = assertTypeOf("BinaryModule"); +exports.assertBinaryModule = assertBinaryModule; +var assertQuoteModule = assertTypeOf("QuoteModule"); +exports.assertQuoteModule = assertQuoteModule; +var assertSectionMetadata = assertTypeOf("SectionMetadata"); +exports.assertSectionMetadata = assertSectionMetadata; +var assertProducersSectionMetadata = assertTypeOf("ProducersSectionMetadata"); +exports.assertProducersSectionMetadata = assertProducersSectionMetadata; +var assertProducerMetadata = assertTypeOf("ProducerMetadata"); +exports.assertProducerMetadata = assertProducerMetadata; +var assertProducerMetadataVersionedName = assertTypeOf("ProducerMetadataVersionedName"); +exports.assertProducerMetadataVersionedName = assertProducerMetadataVersionedName; +var assertLoopInstruction = assertTypeOf("LoopInstruction"); +exports.assertLoopInstruction = assertLoopInstruction; +var assertInstr = assertTypeOf("Instr"); +exports.assertInstr = assertInstr; +var assertIfInstruction = assertTypeOf("IfInstruction"); +exports.assertIfInstruction = assertIfInstruction; +var assertStringLiteral = assertTypeOf("StringLiteral"); +exports.assertStringLiteral = assertStringLiteral; +var assertNumberLiteral = assertTypeOf("NumberLiteral"); +exports.assertNumberLiteral = assertNumberLiteral; +var assertLongNumberLiteral = assertTypeOf("LongNumberLiteral"); +exports.assertLongNumberLiteral = assertLongNumberLiteral; +var assertFloatLiteral = assertTypeOf("FloatLiteral"); +exports.assertFloatLiteral = assertFloatLiteral; +var assertElem = assertTypeOf("Elem"); +exports.assertElem = assertElem; +var assertIndexInFuncSection = assertTypeOf("IndexInFuncSection"); +exports.assertIndexInFuncSection = assertIndexInFuncSection; +var assertValtypeLiteral = assertTypeOf("ValtypeLiteral"); +exports.assertValtypeLiteral = assertValtypeLiteral; +var assertTypeInstruction = assertTypeOf("TypeInstruction"); +exports.assertTypeInstruction = assertTypeInstruction; +var assertStart = assertTypeOf("Start"); +exports.assertStart = assertStart; +var assertGlobalType = assertTypeOf("GlobalType"); +exports.assertGlobalType = assertGlobalType; +var assertLeadingComment = assertTypeOf("LeadingComment"); +exports.assertLeadingComment = assertLeadingComment; +var assertBlockComment = assertTypeOf("BlockComment"); +exports.assertBlockComment = assertBlockComment; +var assertData = assertTypeOf("Data"); +exports.assertData = assertData; +var assertGlobal = assertTypeOf("Global"); +exports.assertGlobal = assertGlobal; +var assertTable = assertTypeOf("Table"); +exports.assertTable = assertTable; +var assertMemory = assertTypeOf("Memory"); +exports.assertMemory = assertMemory; +var assertFuncImportDescr = assertTypeOf("FuncImportDescr"); +exports.assertFuncImportDescr = assertFuncImportDescr; +var assertModuleImport = assertTypeOf("ModuleImport"); +exports.assertModuleImport = assertModuleImport; +var assertModuleExportDescr = assertTypeOf("ModuleExportDescr"); +exports.assertModuleExportDescr = assertModuleExportDescr; +var assertModuleExport = assertTypeOf("ModuleExport"); +exports.assertModuleExport = assertModuleExport; +var assertLimit = assertTypeOf("Limit"); +exports.assertLimit = assertLimit; +var assertSignature = assertTypeOf("Signature"); +exports.assertSignature = assertSignature; +var assertProgram = assertTypeOf("Program"); +exports.assertProgram = assertProgram; +var assertIdentifier = assertTypeOf("Identifier"); +exports.assertIdentifier = assertIdentifier; +var assertBlockInstruction = assertTypeOf("BlockInstruction"); +exports.assertBlockInstruction = assertBlockInstruction; +var assertCallInstruction = assertTypeOf("CallInstruction"); +exports.assertCallInstruction = assertCallInstruction; +var assertCallIndirectInstruction = assertTypeOf("CallIndirectInstruction"); +exports.assertCallIndirectInstruction = assertCallIndirectInstruction; +var assertByteArray = assertTypeOf("ByteArray"); +exports.assertByteArray = assertByteArray; +var assertFunc = assertTypeOf("Func"); +exports.assertFunc = assertFunc; +var assertInternalBrUnless = assertTypeOf("InternalBrUnless"); +exports.assertInternalBrUnless = assertInternalBrUnless; +var assertInternalGoto = assertTypeOf("InternalGoto"); +exports.assertInternalGoto = assertInternalGoto; +var assertInternalCallExtern = assertTypeOf("InternalCallExtern"); +exports.assertInternalCallExtern = assertInternalCallExtern; +var assertInternalEndAndReturn = assertTypeOf("InternalEndAndReturn"); +exports.assertInternalEndAndReturn = assertInternalEndAndReturn; +var unionTypesMap = { + Module: ["Node"], + ModuleMetadata: ["Node"], + ModuleNameMetadata: ["Node"], + FunctionNameMetadata: ["Node"], + LocalNameMetadata: ["Node"], + BinaryModule: ["Node"], + QuoteModule: ["Node"], + SectionMetadata: ["Node"], + ProducersSectionMetadata: ["Node"], + ProducerMetadata: ["Node"], + ProducerMetadataVersionedName: ["Node"], + LoopInstruction: ["Node", "Block", "Instruction"], + Instr: ["Node", "Expression", "Instruction"], + IfInstruction: ["Node", "Instruction"], + StringLiteral: ["Node", "Expression"], + NumberLiteral: ["Node", "NumericLiteral", "Expression"], + LongNumberLiteral: ["Node", "NumericLiteral", "Expression"], + FloatLiteral: ["Node", "NumericLiteral", "Expression"], + Elem: ["Node"], + IndexInFuncSection: ["Node"], + ValtypeLiteral: ["Node", "Expression"], + TypeInstruction: ["Node", "Instruction"], + Start: ["Node"], + GlobalType: ["Node", "ImportDescr"], + LeadingComment: ["Node"], + BlockComment: ["Node"], + Data: ["Node"], + Global: ["Node"], + Table: ["Node", "ImportDescr"], + Memory: ["Node", "ImportDescr"], + FuncImportDescr: ["Node", "ImportDescr"], + ModuleImport: ["Node"], + ModuleExportDescr: ["Node"], + ModuleExport: ["Node"], + Limit: ["Node"], + Signature: ["Node"], + Program: ["Node"], + Identifier: ["Node", "Expression"], + BlockInstruction: ["Node", "Block", "Instruction"], + CallInstruction: ["Node", "Instruction"], + CallIndirectInstruction: ["Node", "Instruction"], + ByteArray: ["Node"], + Func: ["Node", "Block"], + InternalBrUnless: ["Node", "Intrinsic"], + InternalGoto: ["Node", "Intrinsic"], + InternalCallExtern: ["Node", "Intrinsic"], + InternalEndAndReturn: ["Node", "Intrinsic"] +}; +exports.unionTypesMap = unionTypesMap; +var nodeAndUnionTypes = ["Module", "ModuleMetadata", "ModuleNameMetadata", "FunctionNameMetadata", "LocalNameMetadata", "BinaryModule", "QuoteModule", "SectionMetadata", "ProducersSectionMetadata", "ProducerMetadata", "ProducerMetadataVersionedName", "LoopInstruction", "Instr", "IfInstruction", "StringLiteral", "NumberLiteral", "LongNumberLiteral", "FloatLiteral", "Elem", "IndexInFuncSection", "ValtypeLiteral", "TypeInstruction", "Start", "GlobalType", "LeadingComment", "BlockComment", "Data", "Global", "Table", "Memory", "FuncImportDescr", "ModuleImport", "ModuleExportDescr", "ModuleExport", "Limit", "Signature", "Program", "Identifier", "BlockInstruction", "CallInstruction", "CallIndirectInstruction", "ByteArray", "Func", "InternalBrUnless", "InternalGoto", "InternalCallExtern", "InternalEndAndReturn", "Node", "Block", "Instruction", "Expression", "NumericLiteral", "ImportDescr", "Intrinsic"]; +exports.nodeAndUnionTypes = nodeAndUnionTypes; + +/***/ }), + +/***/ 24143: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.signatures = void 0; + +function sign(input, output) { + return [input, output]; +} + +var u32 = "u32"; +var i32 = "i32"; +var i64 = "i64"; +var f32 = "f32"; +var f64 = "f64"; + +var vector = function vector(t) { + var vecType = [t]; // $FlowIgnore + + vecType.vector = true; + return vecType; +}; + +var controlInstructions = { + unreachable: sign([], []), + nop: sign([], []), + // block ? + // loop ? + // if ? + // if else ? + br: sign([u32], []), + br_if: sign([u32], []), + br_table: sign(vector(u32), []), + return: sign([], []), + call: sign([u32], []), + call_indirect: sign([u32], []) +}; +var parametricInstructions = { + drop: sign([], []), + select: sign([], []) +}; +var variableInstructions = { + get_local: sign([u32], []), + set_local: sign([u32], []), + tee_local: sign([u32], []), + get_global: sign([u32], []), + set_global: sign([u32], []) +}; +var memoryInstructions = { + "i32.load": sign([u32, u32], [i32]), + "i64.load": sign([u32, u32], []), + "f32.load": sign([u32, u32], []), + "f64.load": sign([u32, u32], []), + "i32.load8_s": sign([u32, u32], [i32]), + "i32.load8_u": sign([u32, u32], [i32]), + "i32.load16_s": sign([u32, u32], [i32]), + "i32.load16_u": sign([u32, u32], [i32]), + "i64.load8_s": sign([u32, u32], [i64]), + "i64.load8_u": sign([u32, u32], [i64]), + "i64.load16_s": sign([u32, u32], [i64]), + "i64.load16_u": sign([u32, u32], [i64]), + "i64.load32_s": sign([u32, u32], [i64]), + "i64.load32_u": sign([u32, u32], [i64]), + "i32.store": sign([u32, u32], []), + "i64.store": sign([u32, u32], []), + "f32.store": sign([u32, u32], []), + "f64.store": sign([u32, u32], []), + "i32.store8": sign([u32, u32], []), + "i32.store16": sign([u32, u32], []), + "i64.store8": sign([u32, u32], []), + "i64.store16": sign([u32, u32], []), + "i64.store32": sign([u32, u32], []), + current_memory: sign([], []), + grow_memory: sign([], []) +}; +var numericInstructions = { + "i32.const": sign([i32], [i32]), + "i64.const": sign([i64], [i64]), + "f32.const": sign([f32], [f32]), + "f64.const": sign([f64], [f64]), + "i32.eqz": sign([i32], [i32]), + "i32.eq": sign([i32, i32], [i32]), + "i32.ne": sign([i32, i32], [i32]), + "i32.lt_s": sign([i32, i32], [i32]), + "i32.lt_u": sign([i32, i32], [i32]), + "i32.gt_s": sign([i32, i32], [i32]), + "i32.gt_u": sign([i32, i32], [i32]), + "i32.le_s": sign([i32, i32], [i32]), + "i32.le_u": sign([i32, i32], [i32]), + "i32.ge_s": sign([i32, i32], [i32]), + "i32.ge_u": sign([i32, i32], [i32]), + "i64.eqz": sign([i64], [i64]), + "i64.eq": sign([i64, i64], [i32]), + "i64.ne": sign([i64, i64], [i32]), + "i64.lt_s": sign([i64, i64], [i32]), + "i64.lt_u": sign([i64, i64], [i32]), + "i64.gt_s": sign([i64, i64], [i32]), + "i64.gt_u": sign([i64, i64], [i32]), + "i64.le_s": sign([i64, i64], [i32]), + "i64.le_u": sign([i64, i64], [i32]), + "i64.ge_s": sign([i64, i64], [i32]), + "i64.ge_u": sign([i64, i64], [i32]), + "f32.eq": sign([f32, f32], [i32]), + "f32.ne": sign([f32, f32], [i32]), + "f32.lt": sign([f32, f32], [i32]), + "f32.gt": sign([f32, f32], [i32]), + "f32.le": sign([f32, f32], [i32]), + "f32.ge": sign([f32, f32], [i32]), + "f64.eq": sign([f64, f64], [i32]), + "f64.ne": sign([f64, f64], [i32]), + "f64.lt": sign([f64, f64], [i32]), + "f64.gt": sign([f64, f64], [i32]), + "f64.le": sign([f64, f64], [i32]), + "f64.ge": sign([f64, f64], [i32]), + "i32.clz": sign([i32], [i32]), + "i32.ctz": sign([i32], [i32]), + "i32.popcnt": sign([i32], [i32]), + "i32.add": sign([i32, i32], [i32]), + "i32.sub": sign([i32, i32], [i32]), + "i32.mul": sign([i32, i32], [i32]), + "i32.div_s": sign([i32, i32], [i32]), + "i32.div_u": sign([i32, i32], [i32]), + "i32.rem_s": sign([i32, i32], [i32]), + "i32.rem_u": sign([i32, i32], [i32]), + "i32.and": sign([i32, i32], [i32]), + "i32.or": sign([i32, i32], [i32]), + "i32.xor": sign([i32, i32], [i32]), + "i32.shl": sign([i32, i32], [i32]), + "i32.shr_s": sign([i32, i32], [i32]), + "i32.shr_u": sign([i32, i32], [i32]), + "i32.rotl": sign([i32, i32], [i32]), + "i32.rotr": sign([i32, i32], [i32]), + "i64.clz": sign([i64], [i64]), + "i64.ctz": sign([i64], [i64]), + "i64.popcnt": sign([i64], [i64]), + "i64.add": sign([i64, i64], [i64]), + "i64.sub": sign([i64, i64], [i64]), + "i64.mul": sign([i64, i64], [i64]), + "i64.div_s": sign([i64, i64], [i64]), + "i64.div_u": sign([i64, i64], [i64]), + "i64.rem_s": sign([i64, i64], [i64]), + "i64.rem_u": sign([i64, i64], [i64]), + "i64.and": sign([i64, i64], [i64]), + "i64.or": sign([i64, i64], [i64]), + "i64.xor": sign([i64, i64], [i64]), + "i64.shl": sign([i64, i64], [i64]), + "i64.shr_s": sign([i64, i64], [i64]), + "i64.shr_u": sign([i64, i64], [i64]), + "i64.rotl": sign([i64, i64], [i64]), + "i64.rotr": sign([i64, i64], [i64]), + "f32.abs": sign([f32], [f32]), + "f32.neg": sign([f32], [f32]), + "f32.ceil": sign([f32], [f32]), + "f32.floor": sign([f32], [f32]), + "f32.trunc": sign([f32], [f32]), + "f32.nearest": sign([f32], [f32]), + "f32.sqrt": sign([f32], [f32]), + "f32.add": sign([f32, f32], [f32]), + "f32.sub": sign([f32, f32], [f32]), + "f32.mul": sign([f32, f32], [f32]), + "f32.div": sign([f32, f32], [f32]), + "f32.min": sign([f32, f32], [f32]), + "f32.max": sign([f32, f32], [f32]), + "f32.copysign": sign([f32, f32], [f32]), + "f64.abs": sign([f64], [f64]), + "f64.neg": sign([f64], [f64]), + "f64.ceil": sign([f64], [f64]), + "f64.floor": sign([f64], [f64]), + "f64.trunc": sign([f64], [f64]), + "f64.nearest": sign([f64], [f64]), + "f64.sqrt": sign([f64], [f64]), + "f64.add": sign([f64, f64], [f64]), + "f64.sub": sign([f64, f64], [f64]), + "f64.mul": sign([f64, f64], [f64]), + "f64.div": sign([f64, f64], [f64]), + "f64.min": sign([f64, f64], [f64]), + "f64.max": sign([f64, f64], [f64]), + "f64.copysign": sign([f64, f64], [f64]), + "i32.wrap/i64": sign([i64], [i32]), + "i32.trunc_s/f32": sign([f32], [i32]), + "i32.trunc_u/f32": sign([f32], [i32]), + "i32.trunc_s/f64": sign([f32], [i32]), + "i32.trunc_u/f64": sign([f64], [i32]), + "i64.extend_s/i32": sign([i32], [i64]), + "i64.extend_u/i32": sign([i32], [i64]), + "i64.trunc_s/f32": sign([f32], [i64]), + "i64.trunc_u/f32": sign([f32], [i64]), + "i64.trunc_s/f64": sign([f64], [i64]), + "i64.trunc_u/f64": sign([f64], [i64]), + "f32.convert_s/i32": sign([i32], [f32]), + "f32.convert_u/i32": sign([i32], [f32]), + "f32.convert_s/i64": sign([i64], [f32]), + "f32.convert_u/i64": sign([i64], [f32]), + "f32.demote/f64": sign([f64], [f32]), + "f64.convert_s/i32": sign([i32], [f64]), + "f64.convert_u/i32": sign([i32], [f64]), + "f64.convert_s/i64": sign([i64], [f64]), + "f64.convert_u/i64": sign([i64], [f64]), + "f64.promote/f32": sign([f32], [f64]), + "i32.reinterpret/f32": sign([f32], [i32]), + "i64.reinterpret/f64": sign([f64], [i64]), + "f32.reinterpret/i32": sign([i32], [f32]), + "f64.reinterpret/i64": sign([i64], [f64]) +}; +var signatures = Object.assign({}, controlInstructions, parametricInstructions, variableInstructions, memoryInstructions, numericInstructions); +exports.signatures = signatures; + +/***/ }), + +/***/ 16608: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.traverse = traverse; + +var _nodePath = __webpack_require__(41570); + +var _nodes = __webpack_require__(5600); + +// recursively walks the AST starting at the given node. The callback is invoked for +// and object that has a 'type' property. +function walk(context, callback) { + var stop = false; + + function innerWalk(context, callback) { + if (stop) { + return; + } + + var node = context.node; + + if (node === undefined) { + console.warn("traversing with an empty context"); + return; + } + + if (node._deleted === true) { + return; + } + + var path = (0, _nodePath.createPath)(context); + callback(node.type, path); + + if (path.shouldStop) { + stop = true; + return; + } + + Object.keys(node).forEach(function (prop) { + var value = node[prop]; + + if (value === null || value === undefined) { + return; + } + + var valueAsArray = Array.isArray(value) ? value : [value]; + valueAsArray.forEach(function (childNode) { + if (typeof childNode.type === "string") { + var childContext = { + node: childNode, + parentKey: prop, + parentPath: path, + shouldStop: false, + inList: Array.isArray(value) + }; + innerWalk(childContext, callback); + } + }); + }); + } + + innerWalk(context, callback); +} + +var noop = function noop() {}; + +function traverse(node, visitors) { + var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop; + var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop; + Object.keys(visitors).forEach(function (visitor) { + if (!_nodes.nodeAndUnionTypes.includes(visitor)) { + throw new Error("Unexpected visitor ".concat(visitor)); + } + }); + var context = { + node: node, + inList: false, + shouldStop: false, + parentPath: null, + parentKey: null + }; + walk(context, function (type, path) { + if (typeof visitors[type] === "function") { + before(type, path); + visitors[type](path); + after(type, path); + } + + var unionTypes = _nodes.unionTypesMap[type]; + + if (!unionTypes) { + throw new Error("Unexpected node type ".concat(type)); + } + + unionTypes.forEach(function (unionType) { + if (typeof visitors[unionType] === "function") { + before(unionType, path); + visitors[unionType](path); + after(unionType, path); + } + }); + }); +} + +/***/ }), + +/***/ 13892: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isAnonymous = isAnonymous; +exports.getSectionMetadata = getSectionMetadata; +exports.getSectionMetadatas = getSectionMetadatas; +exports.sortSectionMetadata = sortSectionMetadata; +exports.orderedInsertNode = orderedInsertNode; +exports.assertHasLoc = assertHasLoc; +exports.getEndOfSection = getEndOfSection; +exports.shiftLoc = shiftLoc; +exports.shiftSection = shiftSection; +exports.signatureForOpcode = signatureForOpcode; +exports.getUniqueNameGenerator = getUniqueNameGenerator; +exports.getStartByteOffset = getStartByteOffset; +exports.getEndByteOffset = getEndByteOffset; +exports.getFunctionBeginingByteOffset = getFunctionBeginingByteOffset; +exports.getEndBlockByteOffset = getEndBlockByteOffset; +exports.getStartBlockByteOffset = getStartBlockByteOffset; + +var _signatures = __webpack_require__(24143); + +var _traverse = __webpack_require__(16608); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(24222)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function isAnonymous(ident) { + return ident.raw === ""; +} + +function getSectionMetadata(ast, name) { + var section; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata) { + function SectionMetadata(_x) { + return _SectionMetadata.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata.toString(); + }; + + return SectionMetadata; + }(function (_ref) { + var node = _ref.node; + + if (node.section === name) { + section = node; + } + }) + }); + return section; +} + +function getSectionMetadatas(ast, name) { + var sections = []; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata2) { + function SectionMetadata(_x2) { + return _SectionMetadata2.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata2.toString(); + }; + + return SectionMetadata; + }(function (_ref2) { + var node = _ref2.node; + + if (node.section === name) { + sections.push(node); + } + }) + }); + return sections; +} + +function sortSectionMetadata(m) { + if (m.metadata == null) { + console.warn("sortSectionMetadata: no metadata to sort"); + return; + } // $FlowIgnore + + + m.metadata.sections.sort(function (a, b) { + var aId = _helperWasmBytecode.default.sections[a.section]; + var bId = _helperWasmBytecode.default.sections[b.section]; + + if (typeof aId !== "number" || typeof bId !== "number") { + throw new Error("Section id not found"); + } + + return aId - bId; + }); +} + +function orderedInsertNode(m, n) { + assertHasLoc(n); + var didInsert = false; + + if (n.type === "ModuleExport") { + m.fields.push(n); + return; + } + + m.fields = m.fields.reduce(function (acc, field) { + var fieldEndCol = Infinity; + + if (field.loc != null) { + // $FlowIgnore + fieldEndCol = field.loc.end.column; + } // $FlowIgnore: assertHasLoc ensures that + + + if (didInsert === false && n.loc.start.column < fieldEndCol) { + didInsert = true; + acc.push(n); + } + + acc.push(field); + return acc; + }, []); // Handles empty modules or n is the last element + + if (didInsert === false) { + m.fields.push(n); + } +} + +function assertHasLoc(n) { + if (n.loc == null || n.loc.start == null || n.loc.end == null) { + throw new Error("Internal failure: node (".concat(JSON.stringify(n.type), ") has no location information")); + } +} + +function getEndOfSection(s) { + assertHasLoc(s.size); + return s.startOffset + s.size.value + ( // $FlowIgnore + s.size.loc.end.column - s.size.loc.start.column); +} + +function shiftLoc(node, delta) { + // $FlowIgnore + node.loc.start.column += delta; // $FlowIgnore + + node.loc.end.column += delta; +} + +function shiftSection(ast, node, delta) { + if (node.type !== "SectionMetadata") { + throw new Error("Can not shift node " + JSON.stringify(node.type)); + } + + node.startOffset += delta; + + if (_typeof(node.size.loc) === "object") { + shiftLoc(node.size, delta); + } // Custom sections doesn't have vectorOfSize + + + if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { + shiftLoc(node.vectorOfSize, delta); + } + + var sectionName = node.section; // shift node locations within that section + + (0, _traverse.traverse)(ast, { + Node: function Node(_ref3) { + var node = _ref3.node; + var section = (0, _helperWasmBytecode.getSectionForNode)(node); + + if (section === sectionName && _typeof(node.loc) === "object") { + shiftLoc(node, delta); + } + } + }); +} + +function signatureForOpcode(object, name) { + var opcodeName = name; + + if (object !== undefined && object !== "") { + opcodeName = object + "." + name; + } + + var sign = _signatures.signatures[opcodeName]; + + if (sign == undefined) { + // TODO: Uncomment this when br_table and others has been done + //throw new Error("Invalid opcode: "+opcodeName); + return [object, object]; + } + + return sign[0]; +} + +function getUniqueNameGenerator() { + var inc = {}; + return function () { + var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + + if (!(prefix in inc)) { + inc[prefix] = 0; + } else { + inc[prefix] = inc[prefix] + 1; + } + + return prefix + "_" + inc[prefix]; + }; +} + +function getStartByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.start === "undefined") { + throw new Error( // $FlowIgnore + "Can not get byte offset without loc informations, node: " + String(n.id)); + } + + return n.loc.start.column; +} + +function getEndByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.end === "undefined") { + throw new Error("Can not get byte offset without loc informations, node: " + n.type); + } + + return n.loc.end.column; +} + +function getFunctionBeginingByteOffset(n) { + if (!(n.body.length > 0)) { + throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var _n$body = _slicedToArray(n.body, 1), + firstInstruction = _n$body[0]; + + return getStartByteOffset(firstInstruction); +} + +function getEndBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var lastInstruction; + + if (n.instr) { + // $FlowIgnore + lastInstruction = n.instr[n.instr.length - 1]; + } + + if (n.body) { + // $FlowIgnore + lastInstruction = n.body[n.body.length - 1]; + } + + if (!(_typeof(lastInstruction) === "object")) { + throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(lastInstruction); +} + +function getStartBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var fistInstruction; + + if (n.instr) { + // $FlowIgnore + var _n$instr = _slicedToArray(n.instr, 1); + + fistInstruction = _n$instr[0]; + } + + if (n.body) { + // $FlowIgnore + var _n$body2 = _slicedToArray(n.body, 1); + + fistInstruction = _n$body2[0]; + } + + if (!(_typeof(fistInstruction) === "object")) { + throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(fistInstruction); +} + +/***/ }), + +/***/ 70447: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = parse; + +function parse(input) { + input = input.toUpperCase(); + var splitIndex = input.indexOf("P"); + var mantissa, exponent; + + if (splitIndex !== -1) { + mantissa = input.substring(0, splitIndex); + exponent = parseInt(input.substring(splitIndex + 1)); + } else { + mantissa = input; + exponent = 0; + } + + var dotIndex = mantissa.indexOf("."); + + if (dotIndex !== -1) { + var integerPart = parseInt(mantissa.substring(0, dotIndex), 16); + var sign = Math.sign(integerPart); + integerPart = sign * integerPart; + var fractionLength = mantissa.length - dotIndex - 1; + var fractionalPart = parseInt(mantissa.substring(dotIndex + 1), 16); + var fraction = fractionLength > 0 ? fractionalPart / Math.pow(16, fractionLength) : 0; + + if (sign === 0) { + if (fraction === 0) { + mantissa = sign; + } else { + if (Object.is(sign, -0)) { + mantissa = -fraction; + } else { + mantissa = fraction; + } + } + } else { + mantissa = sign * (integerPart + fraction); + } + } else { + mantissa = parseInt(mantissa, 16); + } + + return mantissa * (splitIndex !== -1 ? Math.pow(2, exponent) : 1); +} + +/***/ }), + +/***/ 26833: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var RuntimeError = +/*#__PURE__*/ +function (_Error) { + _inherits(RuntimeError, _Error); + + function RuntimeError() { + _classCallCheck(this, RuntimeError); + + return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); + } + + return RuntimeError; +}(Error); + +exports.RuntimeError = RuntimeError; + +var CompileError = +/*#__PURE__*/ +function (_Error2) { + _inherits(CompileError, _Error2); + + function CompileError() { + _classCallCheck(this, CompileError); + + return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); + } + + return CompileError; +}(Error); + +exports.CompileError = CompileError; + +var LinkError = +/*#__PURE__*/ +function (_Error3) { + _inherits(LinkError, _Error3); + + function LinkError() { + _classCallCheck(this, LinkError); + + return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); + } + + return LinkError; +}(Error); + +exports.LinkError = LinkError; + +/***/ }), + +/***/ 52877: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.overrideBytesInBuffer = overrideBytesInBuffer; +exports.makeBuffer = makeBuffer; +exports.fromHexdump = fromHexdump; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function concatUint8Arrays() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; + } + + var totalLength = arrays.reduce(function (a, b) { + return a + b.length; + }, 0); + var result = new Uint8Array(totalLength); + var offset = 0; + + for (var _i = 0; _i < arrays.length; _i++) { + var arr = arrays[_i]; + + if (arr instanceof Uint8Array === false) { + throw new Error("arr must be of type Uint8Array"); + } + + result.set(arr, offset); + offset += arr.length; + } + + return result; +} + +function overrideBytesInBuffer(buffer, startLoc, endLoc, newBytes) { + var beforeBytes = buffer.slice(0, startLoc); + var afterBytes = buffer.slice(endLoc, buffer.length); // replacement is empty, we can omit it + + if (newBytes.length === 0) { + return concatUint8Arrays(beforeBytes, afterBytes); + } + + var replacement = Uint8Array.from(newBytes); + return concatUint8Arrays(beforeBytes, replacement, afterBytes); +} + +function makeBuffer() { + for (var _len2 = arguments.length, splitedBytes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + splitedBytes[_key2] = arguments[_key2]; + } + + var bytes = [].concat.apply([], splitedBytes); + return new Uint8Array(bytes).buffer; +} + +function fromHexdump(str) { + var lines = str.split("\n"); // remove any leading left whitespace + + lines = lines.map(function (line) { + return line.trim(); + }); + var bytes = lines.reduce(function (acc, line) { + var cols = line.split(" "); // remove the offset, left column + + cols.shift(); + cols = cols.filter(function (x) { + return x !== ""; + }); + var bytes = cols.map(function (x) { + return parseInt(x, 16); + }); + acc.push.apply(acc, _toConsumableArray(bytes)); + return acc; + }, []); + return Buffer.from(bytes); +} + +/***/ }), + +/***/ 87360: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.codeFrameFromAst = codeFrameFromAst; +exports.codeFrameFromSource = codeFrameFromSource; + +var _wastPrinter = __webpack_require__(97023); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var SHOW_LINES_AROUND_POINTER = 5; + +function repeat(char, nb) { + return Array(nb).fill(char).join(""); +} // TODO(sven): allow arbitrary ast nodes + + +function codeFrameFromAst(ast, loc) { + return codeFrameFromSource((0, _wastPrinter.print)(ast), loc); +} + +function codeFrameFromSource(source, loc) { + var start = loc.start, + end = loc.end; + var length = 1; + + if (_typeof(end) === "object") { + length = end.column - start.column + 1; + } + + return source.split("\n").reduce(function (acc, line, lineNbr) { + if (Math.abs(start.line - lineNbr) < SHOW_LINES_AROUND_POINTER) { + acc += line + "\n"; + } // Add a new line with the pointer padded left + + + if (lineNbr === start.line - 1) { + acc += repeat(" ", start.column - 1); + acc += repeat("^", length); + acc += "\n"; + } + + return acc; + }, ""); +} + +/***/ }), + +/***/ 82194: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.makeTransition = makeTransition; +exports.FSM = void 0; + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var STOP = Symbol("STOP"); + +function makeTransition(regex, nextState) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$n = _ref.n, + n = _ref$n === void 0 ? 1 : _ref$n, + allowedSeparator = _ref.allowedSeparator; + + return function (instance) { + if (allowedSeparator) { + if (instance.input[instance.ptr] === allowedSeparator) { + if (regex.test(instance.input.substring(instance.ptr - 1, instance.ptr))) { + // Consume the separator and stay in current state + return [instance.currentState, 1]; + } else { + return [instance.terminatingState, 0]; + } + } + } + + if (regex.test(instance.input.substring(instance.ptr, instance.ptr + n))) { + return [nextState, n]; + } + + return false; + }; +} + +function combineTransitions(transitions) { + return function () { + var match = false; + var currentTransitions = transitions[this.currentState] || []; + + for (var i = 0; i < currentTransitions.length; ++i) { + match = currentTransitions[i](this); + + if (match !== false) { + break; + } + } + + return match || [this.terminatingState, 0]; + }; +} + +var FSM = +/*#__PURE__*/ +function () { + function FSM(transitions, initialState) { + var terminatingState = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : STOP; + + _classCallCheck(this, FSM); + + this.initialState = initialState; + this.terminatingState = terminatingState; + + if (terminatingState === STOP || !transitions[terminatingState]) { + transitions[terminatingState] = []; + } + + this.transitionFunction = combineTransitions.call(this, transitions); + } + + _createClass(FSM, [{ + key: "run", + value: function run(input) { + this.input = input; + this.ptr = 0; + this.currentState = this.initialState; + var value = ""; + var eatLength, nextState; + + while (this.currentState !== this.terminatingState && this.ptr < this.input.length) { + var _transitionFunction = this.transitionFunction(); + + var _transitionFunction2 = _slicedToArray(_transitionFunction, 2); + + nextState = _transitionFunction2[0]; + eatLength = _transitionFunction2[1]; + value += this.input.substring(this.ptr, this.ptr += eatLength); + this.currentState = nextState; + } + + return value; + } + }]); + + return FSM; +}(); + +exports.FSM = FSM; + +/***/ }), + +/***/ 48920: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.moduleContextFromModuleAST = moduleContextFromModuleAST; +exports.ModuleContext = void 0; + +var _ast = __webpack_require__(77325); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function moduleContextFromModuleAST(m) { + var moduleContext = new ModuleContext(); + + if (!(m.type === "Module")) { + throw new Error('m.type === "Module"' + " error: " + (undefined || "unknown")); + } + + m.fields.forEach(function (field) { + switch (field.type) { + case "Start": + { + moduleContext.setStart(field.index); + break; + } + + case "TypeInstruction": + { + moduleContext.addType(field); + break; + } + + case "Func": + { + moduleContext.addFunction(field); + break; + } + + case "Global": + { + moduleContext.defineGlobal(field); + break; + } + + case "ModuleImport": + { + switch (field.descr.type) { + case "GlobalType": + { + moduleContext.importGlobal(field.descr.valtype, field.descr.mutability); + break; + } + + case "Memory": + { + moduleContext.addMemory(field.descr.limits.min, field.descr.limits.max); + break; + } + + case "FuncImportDescr": + { + moduleContext.importFunction(field.descr); + break; + } + + case "Table": + { + // FIXME(sven): not implemented yet + break; + } + + default: + throw new Error("Unsupported ModuleImport of type " + JSON.stringify(field.descr.type)); + } + + break; + } + + case "Memory": + { + moduleContext.addMemory(field.limits.min, field.limits.max); + break; + } + } + }); + return moduleContext; +} +/** + * Module context for type checking + */ + + +var ModuleContext = +/*#__PURE__*/ +function () { + function ModuleContext() { + _classCallCheck(this, ModuleContext); + + this.funcs = []; + this.funcsOffsetByIdentifier = []; + this.types = []; + this.globals = []; + this.globalsOffsetByIdentifier = []; + this.mems = []; // Current stack frame + + this.locals = []; + this.labels = []; + this.return = []; + this.debugName = "unknown"; + this.start = null; + } + /** + * Set start segment + */ + + + _createClass(ModuleContext, [{ + key: "setStart", + value: function setStart(index) { + this.start = index.value; + } + /** + * Get start function + */ + + }, { + key: "getStart", + value: function getStart() { + return this.start; + } + /** + * Reset the active stack frame + */ + + }, { + key: "newContext", + value: function newContext(debugName, expectedResult) { + this.locals = []; + this.labels = [expectedResult]; + this.return = expectedResult; + this.debugName = debugName; + } + /** + * Functions + */ + + }, { + key: "addFunction", + value: function addFunction(func + /*: Func*/ + ) { + // eslint-disable-next-line prefer-const + var _ref = func.signature || {}, + _ref$params = _ref.params, + args = _ref$params === void 0 ? [] : _ref$params, + _ref$results = _ref.results, + result = _ref$results === void 0 ? [] : _ref$results; + + args = args.map(function (arg) { + return arg.valtype; + }); + this.funcs.push({ + args: args, + result: result + }); + + if (typeof func.name !== "undefined") { + this.funcsOffsetByIdentifier[func.name.value] = this.funcs.length - 1; + } + } + }, { + key: "importFunction", + value: function importFunction(funcimport) { + if ((0, _ast.isSignature)(funcimport.signature)) { + // eslint-disable-next-line prefer-const + var _funcimport$signature = funcimport.signature, + args = _funcimport$signature.params, + result = _funcimport$signature.results; + args = args.map(function (arg) { + return arg.valtype; + }); + this.funcs.push({ + args: args, + result: result + }); + } else { + if (!(0, _ast.isNumberLiteral)(funcimport.signature)) { + throw new Error('isNumberLiteral(funcimport.signature)' + " error: " + (undefined || "unknown")); + } + + var typeId = funcimport.signature.value; + + if (!this.hasType(typeId)) { + throw new Error('this.hasType(typeId)' + " error: " + (undefined || "unknown")); + } + + var signature = this.getType(typeId); + this.funcs.push({ + args: signature.params.map(function (arg) { + return arg.valtype; + }), + result: signature.results + }); + } + + if (typeof funcimport.id !== "undefined") { + // imports are first, we can assume their index in the array + this.funcsOffsetByIdentifier[funcimport.id.value] = this.funcs.length - 1; + } + } + }, { + key: "hasFunction", + value: function hasFunction(index) { + return typeof this.getFunction(index) !== "undefined"; + } + }, { + key: "getFunction", + value: function getFunction(index) { + if (typeof index !== "number") { + throw new Error("getFunction only supported for number index"); + } + + return this.funcs[index]; + } + }, { + key: "getFunctionOffsetByIdentifier", + value: function getFunctionOffsetByIdentifier(name) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown")); + } + + return this.funcsOffsetByIdentifier[name]; + } + /** + * Labels + */ + + }, { + key: "addLabel", + value: function addLabel(result) { + this.labels.unshift(result); + } + }, { + key: "hasLabel", + value: function hasLabel(index) { + return this.labels.length > index && index >= 0; + } + }, { + key: "getLabel", + value: function getLabel(index) { + return this.labels[index]; + } + }, { + key: "popLabel", + value: function popLabel() { + this.labels.shift(); + } + /** + * Locals + */ + + }, { + key: "hasLocal", + value: function hasLocal(index) { + return typeof this.getLocal(index) !== "undefined"; + } + }, { + key: "getLocal", + value: function getLocal(index) { + return this.locals[index]; + } + }, { + key: "addLocal", + value: function addLocal(type) { + this.locals.push(type); + } + /** + * Types + */ + + }, { + key: "addType", + value: function addType(type) { + if (!(type.functype.type === "Signature")) { + throw new Error('type.functype.type === "Signature"' + " error: " + (undefined || "unknown")); + } + + this.types.push(type.functype); + } + }, { + key: "hasType", + value: function hasType(index) { + return this.types[index] !== undefined; + } + }, { + key: "getType", + value: function getType(index) { + return this.types[index]; + } + /** + * Globals + */ + + }, { + key: "hasGlobal", + value: function hasGlobal(index) { + return this.globals.length > index && index >= 0; + } + }, { + key: "getGlobal", + value: function getGlobal(index) { + return this.globals[index].type; + } + }, { + key: "getGlobalOffsetByIdentifier", + value: function getGlobalOffsetByIdentifier(name) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown")); + } + + return this.globalsOffsetByIdentifier[name]; + } + }, { + key: "defineGlobal", + value: function defineGlobal(global + /*: Global*/ + ) { + var type = global.globalType.valtype; + var mutability = global.globalType.mutability; + this.globals.push({ + type: type, + mutability: mutability + }); + + if (typeof global.name !== "undefined") { + this.globalsOffsetByIdentifier[global.name.value] = this.globals.length - 1; + } + } + }, { + key: "importGlobal", + value: function importGlobal(type, mutability) { + this.globals.push({ + type: type, + mutability: mutability + }); + } + }, { + key: "isMutableGlobal", + value: function isMutableGlobal(index) { + return this.globals[index].mutability === "var"; + } + }, { + key: "isImmutableGlobal", + value: function isImmutableGlobal(index) { + return this.globals[index].mutability === "const"; + } + /** + * Memories + */ + + }, { + key: "hasMemory", + value: function hasMemory(index) { + return this.mems.length > index && index >= 0; + } + }, { + key: "addMemory", + value: function addMemory(min, max) { + this.mems.push({ + min: min, + max: max + }); + } + }, { + key: "getMemory", + value: function getMemory(index) { + return this.mems[index]; + } + }]); + + return ModuleContext; +}(); + +exports.ModuleContext = ModuleContext; + +/***/ }), + +/***/ 24222: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "getSectionForNode", ({ + enumerable: true, + get: function get() { + return _section.getSectionForNode; + } +})); +exports.default = void 0; + +var _section = __webpack_require__(8502); + +var illegalop = "illegal"; +var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; +var moduleVersion = [0x01, 0x00, 0x00, 0x00]; + +function invertMap(obj) { + var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { + return k; + }; + var result = {}; + var keys = Object.keys(obj); + + for (var i = 0, length = keys.length; i < length; i++) { + result[keyModifierFn(obj[keys[i]])] = keys[i]; + } + + return result; +} + +function createSymbolObject(name +/*: string */ +, object +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + return { + name: name, + object: object, + numberOfArgs: numberOfArgs + }; +} + +function createSymbol(name +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return { + name: name, + numberOfArgs: numberOfArgs + }; +} + +var types = { + func: 0x60, + result: 0x40 +}; +var exportTypes = { + 0x00: "Func", + 0x01: "Table", + 0x02: "Mem", + 0x03: "Global" +}; +var exportTypesByName = invertMap(exportTypes); +var valtypes = { + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64", + 0x7b: "v128" +}; +var valtypesByString = invertMap(valtypes); +var tableTypes = { + 0x70: "anyfunc" +}; +var blockTypes = Object.assign({}, valtypes, { + // https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype + 0x40: null, + // https://webassembly.github.io/spec/core/binary/types.html#binary-valtype + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64" +}); +var globalTypes = { + 0x00: "const", + 0x01: "var" +}; +var globalTypesByString = invertMap(globalTypes); +var importTypes = { + 0x00: "func", + 0x01: "table", + 0x02: "mem", + 0x03: "global" +}; +var sections = { + custom: 0, + type: 1, + import: 2, + func: 3, + table: 4, + memory: 5, + global: 6, + export: 7, + start: 8, + element: 9, + code: 10, + data: 11 +}; +var symbolsByByte = { + 0x00: createSymbol("unreachable"), + 0x01: createSymbol("nop"), + 0x02: createSymbol("block"), + 0x03: createSymbol("loop"), + 0x04: createSymbol("if"), + 0x05: createSymbol("else"), + 0x06: illegalop, + 0x07: illegalop, + 0x08: illegalop, + 0x09: illegalop, + 0x0a: illegalop, + 0x0b: createSymbol("end"), + 0x0c: createSymbol("br", 1), + 0x0d: createSymbol("br_if", 1), + 0x0e: createSymbol("br_table"), + 0x0f: createSymbol("return"), + 0x10: createSymbol("call", 1), + 0x11: createSymbol("call_indirect", 2), + 0x12: illegalop, + 0x13: illegalop, + 0x14: illegalop, + 0x15: illegalop, + 0x16: illegalop, + 0x17: illegalop, + 0x18: illegalop, + 0x19: illegalop, + 0x1a: createSymbol("drop"), + 0x1b: createSymbol("select"), + 0x1c: illegalop, + 0x1d: illegalop, + 0x1e: illegalop, + 0x1f: illegalop, + 0x20: createSymbol("get_local", 1), + 0x21: createSymbol("set_local", 1), + 0x22: createSymbol("tee_local", 1), + 0x23: createSymbol("get_global", 1), + 0x24: createSymbol("set_global", 1), + 0x25: illegalop, + 0x26: illegalop, + 0x27: illegalop, + 0x28: createSymbolObject("load", "u32", 1), + 0x29: createSymbolObject("load", "u64", 1), + 0x2a: createSymbolObject("load", "f32", 1), + 0x2b: createSymbolObject("load", "f64", 1), + 0x2c: createSymbolObject("load8_s", "u32", 1), + 0x2d: createSymbolObject("load8_u", "u32", 1), + 0x2e: createSymbolObject("load16_s", "u32", 1), + 0x2f: createSymbolObject("load16_u", "u32", 1), + 0x30: createSymbolObject("load8_s", "u64", 1), + 0x31: createSymbolObject("load8_u", "u64", 1), + 0x32: createSymbolObject("load16_s", "u64", 1), + 0x33: createSymbolObject("load16_u", "u64", 1), + 0x34: createSymbolObject("load32_s", "u64", 1), + 0x35: createSymbolObject("load32_u", "u64", 1), + 0x36: createSymbolObject("store", "u32", 1), + 0x37: createSymbolObject("store", "u64", 1), + 0x38: createSymbolObject("store", "f32", 1), + 0x39: createSymbolObject("store", "f64", 1), + 0x3a: createSymbolObject("store8", "u32", 1), + 0x3b: createSymbolObject("store16", "u32", 1), + 0x3c: createSymbolObject("store8", "u64", 1), + 0x3d: createSymbolObject("store16", "u64", 1), + 0x3e: createSymbolObject("store32", "u64", 1), + 0x3f: createSymbolObject("current_memory"), + 0x40: createSymbolObject("grow_memory"), + 0x41: createSymbolObject("const", "i32", 1), + 0x42: createSymbolObject("const", "i64", 1), + 0x43: createSymbolObject("const", "f32", 1), + 0x44: createSymbolObject("const", "f64", 1), + 0x45: createSymbolObject("eqz", "i32"), + 0x46: createSymbolObject("eq", "i32"), + 0x47: createSymbolObject("ne", "i32"), + 0x48: createSymbolObject("lt_s", "i32"), + 0x49: createSymbolObject("lt_u", "i32"), + 0x4a: createSymbolObject("gt_s", "i32"), + 0x4b: createSymbolObject("gt_u", "i32"), + 0x4c: createSymbolObject("le_s", "i32"), + 0x4d: createSymbolObject("le_u", "i32"), + 0x4e: createSymbolObject("ge_s", "i32"), + 0x4f: createSymbolObject("ge_u", "i32"), + 0x50: createSymbolObject("eqz", "i64"), + 0x51: createSymbolObject("eq", "i64"), + 0x52: createSymbolObject("ne", "i64"), + 0x53: createSymbolObject("lt_s", "i64"), + 0x54: createSymbolObject("lt_u", "i64"), + 0x55: createSymbolObject("gt_s", "i64"), + 0x56: createSymbolObject("gt_u", "i64"), + 0x57: createSymbolObject("le_s", "i64"), + 0x58: createSymbolObject("le_u", "i64"), + 0x59: createSymbolObject("ge_s", "i64"), + 0x5a: createSymbolObject("ge_u", "i64"), + 0x5b: createSymbolObject("eq", "f32"), + 0x5c: createSymbolObject("ne", "f32"), + 0x5d: createSymbolObject("lt", "f32"), + 0x5e: createSymbolObject("gt", "f32"), + 0x5f: createSymbolObject("le", "f32"), + 0x60: createSymbolObject("ge", "f32"), + 0x61: createSymbolObject("eq", "f64"), + 0x62: createSymbolObject("ne", "f64"), + 0x63: createSymbolObject("lt", "f64"), + 0x64: createSymbolObject("gt", "f64"), + 0x65: createSymbolObject("le", "f64"), + 0x66: createSymbolObject("ge", "f64"), + 0x67: createSymbolObject("clz", "i32"), + 0x68: createSymbolObject("ctz", "i32"), + 0x69: createSymbolObject("popcnt", "i32"), + 0x6a: createSymbolObject("add", "i32"), + 0x6b: createSymbolObject("sub", "i32"), + 0x6c: createSymbolObject("mul", "i32"), + 0x6d: createSymbolObject("div_s", "i32"), + 0x6e: createSymbolObject("div_u", "i32"), + 0x6f: createSymbolObject("rem_s", "i32"), + 0x70: createSymbolObject("rem_u", "i32"), + 0x71: createSymbolObject("and", "i32"), + 0x72: createSymbolObject("or", "i32"), + 0x73: createSymbolObject("xor", "i32"), + 0x74: createSymbolObject("shl", "i32"), + 0x75: createSymbolObject("shr_s", "i32"), + 0x76: createSymbolObject("shr_u", "i32"), + 0x77: createSymbolObject("rotl", "i32"), + 0x78: createSymbolObject("rotr", "i32"), + 0x79: createSymbolObject("clz", "i64"), + 0x7a: createSymbolObject("ctz", "i64"), + 0x7b: createSymbolObject("popcnt", "i64"), + 0x7c: createSymbolObject("add", "i64"), + 0x7d: createSymbolObject("sub", "i64"), + 0x7e: createSymbolObject("mul", "i64"), + 0x7f: createSymbolObject("div_s", "i64"), + 0x80: createSymbolObject("div_u", "i64"), + 0x81: createSymbolObject("rem_s", "i64"), + 0x82: createSymbolObject("rem_u", "i64"), + 0x83: createSymbolObject("and", "i64"), + 0x84: createSymbolObject("or", "i64"), + 0x85: createSymbolObject("xor", "i64"), + 0x86: createSymbolObject("shl", "i64"), + 0x87: createSymbolObject("shr_s", "i64"), + 0x88: createSymbolObject("shr_u", "i64"), + 0x89: createSymbolObject("rotl", "i64"), + 0x8a: createSymbolObject("rotr", "i64"), + 0x8b: createSymbolObject("abs", "f32"), + 0x8c: createSymbolObject("neg", "f32"), + 0x8d: createSymbolObject("ceil", "f32"), + 0x8e: createSymbolObject("floor", "f32"), + 0x8f: createSymbolObject("trunc", "f32"), + 0x90: createSymbolObject("nearest", "f32"), + 0x91: createSymbolObject("sqrt", "f32"), + 0x92: createSymbolObject("add", "f32"), + 0x93: createSymbolObject("sub", "f32"), + 0x94: createSymbolObject("mul", "f32"), + 0x95: createSymbolObject("div", "f32"), + 0x96: createSymbolObject("min", "f32"), + 0x97: createSymbolObject("max", "f32"), + 0x98: createSymbolObject("copysign", "f32"), + 0x99: createSymbolObject("abs", "f64"), + 0x9a: createSymbolObject("neg", "f64"), + 0x9b: createSymbolObject("ceil", "f64"), + 0x9c: createSymbolObject("floor", "f64"), + 0x9d: createSymbolObject("trunc", "f64"), + 0x9e: createSymbolObject("nearest", "f64"), + 0x9f: createSymbolObject("sqrt", "f64"), + 0xa0: createSymbolObject("add", "f64"), + 0xa1: createSymbolObject("sub", "f64"), + 0xa2: createSymbolObject("mul", "f64"), + 0xa3: createSymbolObject("div", "f64"), + 0xa4: createSymbolObject("min", "f64"), + 0xa5: createSymbolObject("max", "f64"), + 0xa6: createSymbolObject("copysign", "f64"), + 0xa7: createSymbolObject("wrap/i64", "i32"), + 0xa8: createSymbolObject("trunc_s/f32", "i32"), + 0xa9: createSymbolObject("trunc_u/f32", "i32"), + 0xaa: createSymbolObject("trunc_s/f64", "i32"), + 0xab: createSymbolObject("trunc_u/f64", "i32"), + 0xac: createSymbolObject("extend_s/i32", "i64"), + 0xad: createSymbolObject("extend_u/i32", "i64"), + 0xae: createSymbolObject("trunc_s/f32", "i64"), + 0xaf: createSymbolObject("trunc_u/f32", "i64"), + 0xb0: createSymbolObject("trunc_s/f64", "i64"), + 0xb1: createSymbolObject("trunc_u/f64", "i64"), + 0xb2: createSymbolObject("convert_s/i32", "f32"), + 0xb3: createSymbolObject("convert_u/i32", "f32"), + 0xb4: createSymbolObject("convert_s/i64", "f32"), + 0xb5: createSymbolObject("convert_u/i64", "f32"), + 0xb6: createSymbolObject("demote/f64", "f32"), + 0xb7: createSymbolObject("convert_s/i32", "f64"), + 0xb8: createSymbolObject("convert_u/i32", "f64"), + 0xb9: createSymbolObject("convert_s/i64", "f64"), + 0xba: createSymbolObject("convert_u/i64", "f64"), + 0xbb: createSymbolObject("promote/f32", "f64"), + 0xbc: createSymbolObject("reinterpret/f32", "i32"), + 0xbd: createSymbolObject("reinterpret/f64", "i64"), + 0xbe: createSymbolObject("reinterpret/i32", "f32"), + 0xbf: createSymbolObject("reinterpret/i64", "f64") +}; +var symbolsByName = invertMap(symbolsByByte, function (obj) { + if (typeof obj.object === "string") { + return "".concat(obj.object, ".").concat(obj.name); + } + + return obj.name; +}); +var _default = { + symbolsByByte: symbolsByByte, + sections: sections, + magicModuleHeader: magicModuleHeader, + moduleVersion: moduleVersion, + types: types, + valtypes: valtypes, + exportTypes: exportTypes, + blockTypes: blockTypes, + tableTypes: tableTypes, + globalTypes: globalTypes, + importTypes: importTypes, + valtypesByString: valtypesByString, + globalTypesByString: globalTypesByString, + exportTypesByName: exportTypesByName, + symbolsByName: symbolsByName +}; +exports.default = _default; + +/***/ }), + +/***/ 8502: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getSectionForNode = getSectionForNode; + +function getSectionForNode(n) { + switch (n.type) { + case "ModuleImport": + return "import"; + + case "CallInstruction": + case "CallIndirectInstruction": + case "Func": + case "Instr": + return "code"; + + case "ModuleExport": + return "export"; + + case "Start": + return "start"; + + case "TypeInstruction": + return "type"; + + case "IndexInFuncSection": + return "func"; + + case "Global": + return "global"; + // No section + + default: + return; + } +} + +/***/ }), + +/***/ 37892: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createEmptySection = createEmptySection; + +var _wasmGen = __webpack_require__(80353); + +var _helperBuffer = __webpack_require__(52877); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(24222)); + +var t = _interopRequireWildcard(__webpack_require__(77325)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function findLastSection(ast, forSection) { + var targetSectionId = _helperWasmBytecode.default.sections[forSection]; // $FlowIgnore: metadata can not be empty + + var moduleSections = ast.body[0].metadata.sections; + var lastSection; + var lastId = 0; + + for (var i = 0, len = moduleSections.length; i < len; i++) { + var section = moduleSections[i]; // Ignore custom section since they can actually occur everywhere + + if (section.section === "custom") { + continue; + } + + var sectionId = _helperWasmBytecode.default.sections[section.section]; + + if (targetSectionId > lastId && targetSectionId < sectionId) { + return lastSection; + } + + lastId = sectionId; + lastSection = section; + } + + return lastSection; +} + +function createEmptySection(ast, uint8Buffer, section) { + // previous section after which we are going to insert our section + var lastSection = findLastSection(ast, section); + var start, end; + /** + * It's the first section + */ + + if (lastSection == null || lastSection.section === "custom") { + start = 8 + /* wasm header size */ + ; + end = start; + } else { + start = lastSection.startOffset + lastSection.size.value + 1; + end = start; + } // section id + + + start += 1; + var sizeStartLoc = { + line: -1, + column: start + }; + var sizeEndLoc = { + line: -1, + column: start + 1 + }; // 1 byte for the empty vector + + var size = t.withLoc(t.numberLiteralFromRaw(1), sizeEndLoc, sizeStartLoc); + var vectorOfSizeStartLoc = { + line: -1, + column: sizeEndLoc.column + }; + var vectorOfSizeEndLoc = { + line: -1, + column: sizeEndLoc.column + 1 + }; + var vectorOfSize = t.withLoc(t.numberLiteralFromRaw(0), vectorOfSizeEndLoc, vectorOfSizeStartLoc); + var sectionMetadata = t.sectionMetadata(section, start, size, vectorOfSize); + var sectionBytes = (0, _wasmGen.encodeNode)(sectionMetadata); + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start - 1, end, sectionBytes); // Add section into the AST for later lookups + + if (_typeof(ast.body[0].metadata) === "object") { + // $FlowIgnore: metadata can not be empty + ast.body[0].metadata.sections.push(sectionMetadata); + t.sortSectionMetadata(ast.body[0]); + } + /** + * Update AST + */ + // Once we hit our section every that is after needs to be shifted by the delta + + + var deltaBytes = +sectionBytes.length; + var encounteredSection = false; + t.traverse(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + t.shiftSection(ast, path.node, deltaBytes); + } + } + }); + return { + uint8Buffer: uint8Buffer, + sectionMetadata: sectionMetadata + }; +} + +/***/ }), + +/***/ 47020: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "resizeSectionByteSize", ({ + enumerable: true, + get: function get() { + return _resize.resizeSectionByteSize; + } +})); +Object.defineProperty(exports, "resizeSectionVecSize", ({ + enumerable: true, + get: function get() { + return _resize.resizeSectionVecSize; + } +})); +Object.defineProperty(exports, "createEmptySection", ({ + enumerable: true, + get: function get() { + return _create.createEmptySection; + } +})); +Object.defineProperty(exports, "removeSections", ({ + enumerable: true, + get: function get() { + return _remove.removeSections; + } +})); + +var _resize = __webpack_require__(25579); + +var _create = __webpack_require__(37892); + +var _remove = __webpack_require__(33257); + +/***/ }), + +/***/ 33257: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.removeSections = removeSections; + +var _ast = __webpack_require__(77325); + +var _helperBuffer = __webpack_require__(52877); + +function removeSections(ast, uint8Buffer, section) { + var sectionMetadatas = (0, _ast.getSectionMetadatas)(ast, section); + + if (sectionMetadatas.length === 0) { + throw new Error("Section metadata not found"); + } + + return sectionMetadatas.reverse().reduce(function (uint8Buffer, sectionMetadata) { + var startsIncludingId = sectionMetadata.startOffset - 1; + var ends = section === "start" ? sectionMetadata.size.loc.end.column + 1 : sectionMetadata.startOffset + sectionMetadata.size.value + 1; + var delta = -(ends - startsIncludingId); + /** + * update AST + */ + // Once we hit our section every that is after needs to be shifted by the delta + + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return path.remove(); + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, delta); + } + } + }); // replacement is nothing + + var replacement = []; + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, startsIncludingId, ends, replacement); + }, uint8Buffer); +} + +/***/ }), + +/***/ 25579: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.resizeSectionByteSize = resizeSectionByteSize; +exports.resizeSectionVecSize = resizeSectionVecSize; + +var _wasmGen = __webpack_require__(80353); + +var _ast = __webpack_require__(77325); + +var _helperBuffer = __webpack_require__(52877); + +function resizeSectionByteSize(ast, uint8Buffer, section, deltaBytes) { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section); + + if (typeof sectionMetadata === "undefined") { + throw new Error("Section metadata not found"); + } + + if (typeof sectionMetadata.size.loc === "undefined") { + throw new Error("SectionMetadata " + section + " has no loc"); + } // keep old node location to be overriden + + + var start = sectionMetadata.size.loc.start.column; + var end = sectionMetadata.size.loc.end.column; + var newSectionSize = sectionMetadata.size.value + deltaBytes; + var newBytes = (0, _wasmGen.encodeU32)(newSectionSize); + /** + * update AST + */ + + sectionMetadata.size.value = newSectionSize; + var oldu32EncodedLen = end - start; + var newu32EncodedLen = newBytes.length; // the new u32 has a different encoded length + + if (newu32EncodedLen !== oldu32EncodedLen) { + var deltaInSizeEncoding = newu32EncodedLen - oldu32EncodedLen; + sectionMetadata.size.loc.end.column = start + newu32EncodedLen; + deltaBytes += deltaInSizeEncoding; // move the vec size pointer size the section size is now smaller + + sectionMetadata.vectorOfSize.loc.start.column += deltaInSizeEncoding; + sectionMetadata.vectorOfSize.loc.end.column += deltaInSizeEncoding; + } // Once we hit our section every that is after needs to be shifted by the delta + + + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, deltaBytes); + } + } + }); + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes); +} + +function resizeSectionVecSize(ast, uint8Buffer, section, deltaElements) { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section); + + if (typeof sectionMetadata === "undefined") { + throw new Error("Section metadata not found"); + } + + if (typeof sectionMetadata.vectorOfSize.loc === "undefined") { + throw new Error("SectionMetadata " + section + " has no loc"); + } // Section has no vector + + + if (sectionMetadata.vectorOfSize.value === -1) { + return uint8Buffer; + } // keep old node location to be overriden + + + var start = sectionMetadata.vectorOfSize.loc.start.column; + var end = sectionMetadata.vectorOfSize.loc.end.column; + var newValue = sectionMetadata.vectorOfSize.value + deltaElements; + var newBytes = (0, _wasmGen.encodeU32)(newValue); // Update AST + + sectionMetadata.vectorOfSize.value = newValue; + sectionMetadata.vectorOfSize.loc.end.column = start + newBytes.length; + return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes); +} + +/***/ }), + +/***/ 51761: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeF32 = encodeF32; +exports.encodeF64 = encodeF64; +exports.decodeF32 = decodeF32; +exports.decodeF64 = decodeF64; +exports.DOUBLE_PRECISION_MANTISSA = exports.SINGLE_PRECISION_MANTISSA = exports.NUMBER_OF_BYTE_F64 = exports.NUMBER_OF_BYTE_F32 = void 0; + +var _ieee = __webpack_require__(30848); + +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 32/8 + */ +var NUMBER_OF_BYTE_F32 = 4; +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 64/8 + */ + +exports.NUMBER_OF_BYTE_F32 = NUMBER_OF_BYTE_F32; +var NUMBER_OF_BYTE_F64 = 8; +exports.NUMBER_OF_BYTE_F64 = NUMBER_OF_BYTE_F64; +var SINGLE_PRECISION_MANTISSA = 23; +exports.SINGLE_PRECISION_MANTISSA = SINGLE_PRECISION_MANTISSA; +var DOUBLE_PRECISION_MANTISSA = 52; +exports.DOUBLE_PRECISION_MANTISSA = DOUBLE_PRECISION_MANTISSA; + +function encodeF32(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); + return buffer; +} + +function encodeF64(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); + return buffer; +} + +function decodeF32(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); +} + +function decodeF64(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); +} + +/***/ }), + +/***/ 6664: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * bits: Bitwise buffer utilities. The utilities here treat a buffer + * as a little-endian bigint, so the lowest-order bit is bit #0 of + * `buffer[0]`, and the highest-order bit is bit #7 of + * `buffer[buffer.length - 1]`. + */ + +/* + * Modules used + */ + +/* + * Exported bindings + */ + +/** + * Extracts the given number of bits from the buffer at the indicated + * index, returning a simple number as the result. If bits are requested + * that aren't covered by the buffer, the `defaultBit` is used as their + * value. + * + * The `bitLength` must be no more than 32. The `defaultBit` if not + * specified is taken to be `0`. + */ + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extract = extract; +exports.inject = inject; +exports.getSign = getSign; +exports.highOrder = highOrder; + +function extract(buffer, bitIndex, bitLength, defaultBit) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + if (defaultBit === undefined) { + defaultBit = 0; + } else if (defaultBit !== 0 && defaultBit !== 1) { + throw new Error("Bad value for defaultBit."); + } + + var defaultByte = defaultBit * 0xff; + var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but + // if endBit !== 0, then endByte is inclusive. + + var lastBit = bitIndex + bitLength; + var startByte = Math.floor(bitIndex / 8); + var startBit = bitIndex % 8; + var endByte = Math.floor(lastBit / 8); + var endBit = lastBit % 8; + + if (endBit !== 0) { + // `(1 << endBit) - 1` is the mask of all bits up to but not including + // the endBit. + result = get(endByte) & (1 << endBit) - 1; + } + + while (endByte > startByte) { + endByte--; + result = result << 8 | get(endByte); + } + + result >>>= startBit; + return result; + + function get(index) { + var result = buffer[index]; + return result === undefined ? defaultByte : result; + } +} +/** + * Injects the given bits into the given buffer at the given index. Any + * bits in the value beyond the length to set are ignored. + */ + + +function inject(buffer, bitIndex, bitLength, value) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); + + if (bitIndex < 0 || lastByte >= buffer.length) { + throw new Error("Index out of range."); + } // Just keeping it simple, until / unless profiling shows that this + // is a problem. + + + var atByte = Math.floor(bitIndex / 8); + var atBit = bitIndex % 8; + + while (bitLength > 0) { + if (value & 1) { + buffer[atByte] |= 1 << atBit; + } else { + buffer[atByte] &= ~(1 << atBit); + } + + value >>= 1; + bitLength--; + atBit = (atBit + 1) % 8; + + if (atBit === 0) { + atByte++; + } + } +} +/** + * Gets the sign bit of the given buffer. + */ + + +function getSign(buffer) { + return buffer[buffer.length - 1] >>> 7; +} +/** + * Gets the zero-based bit number of the highest-order bit with the + * given value in the given buffer. + * + * If the buffer consists entirely of the other bit value, then this returns + * `-1`. + */ + + +function highOrder(bit, buffer) { + var length = buffer.length; + var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte + + while (length > 0 && buffer[length - 1] === fullyWrongByte) { + length--; + } + + if (length === 0) { + // Degenerate case. The buffer consists entirely of ~bit. + return -1; + } + + var byteToCheck = buffer[length - 1]; + var result = length * 8 - 1; + + for (var i = 7; i > 0; i--) { + if ((byteToCheck >> i & 1) === bit) { + break; + } + + result--; + } + + return result; +} + +/***/ }), + +/***/ 87809: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.alloc = alloc; +exports.free = free; +exports.resize = resize; +exports.readInt = readInt; +exports.readUInt = readUInt; +exports.writeInt64 = writeInt64; +exports.writeUInt64 = writeUInt64; +// Copyright 2012 The Obvious Corporation. + +/* + * bufs: Buffer utilities. + */ + +/* + * Module variables + */ + +/** Pool of buffers, where `bufPool[x].length === x`. */ +var bufPool = []; +/** Maximum length of kept temporary buffers. */ + +var TEMP_BUF_MAXIMUM_LENGTH = 20; +/** Minimum exactly-representable 64-bit int. */ + +var MIN_EXACT_INT64 = -0x8000000000000000; +/** Maximum exactly-representable 64-bit int. */ + +var MAX_EXACT_INT64 = 0x7ffffffffffffc00; +/** Maximum exactly-representable 64-bit uint. */ + +var MAX_EXACT_UINT64 = 0xfffffffffffff800; +/** + * The int value consisting just of a 1 in bit #32 (that is, one more + * than the maximum 32-bit unsigned value). + */ + +var BIT_32 = 0x100000000; +/** + * The int value consisting just of a 1 in bit #64 (that is, one more + * than the maximum 64-bit unsigned value). + */ + +var BIT_64 = 0x10000000000000000; +/* + * Helper functions + */ + +/** + * Masks off all but the lowest bit set of the given number. + */ + +function lowestBit(num) { + return num & -num; +} +/** + * Gets whether trying to add the second number to the first is lossy + * (inexact). The first number is meant to be an accumulated result. + */ + + +function isLossyToAdd(accum, num) { + if (num === 0) { + return false; + } + + var lowBit = lowestBit(num); + var added = accum + lowBit; + + if (added === accum) { + return true; + } + + if (added - lowBit !== accum) { + return true; + } + + return false; +} +/* + * Exported functions + */ + +/** + * Allocates a buffer of the given length, which is initialized + * with all zeroes. This returns a buffer from the pool if it is + * available, or a freshly-allocated buffer if not. + */ + + +function alloc(length) { + var result = bufPool[length]; + + if (result) { + bufPool[length] = undefined; + } else { + result = new Buffer(length); + } + + result.fill(0); + return result; +} +/** + * Releases a buffer back to the pool. + */ + + +function free(buffer) { + var length = buffer.length; + + if (length < TEMP_BUF_MAXIMUM_LENGTH) { + bufPool[length] = buffer; + } +} +/** + * Resizes a buffer, returning a new buffer. Returns the argument if + * the length wouldn't actually change. This function is only safe to + * use if the given buffer was allocated within this module (since + * otherwise the buffer might possibly be shared externally). + */ + + +function resize(buffer, length) { + if (length === buffer.length) { + return buffer; + } + + var newBuf = alloc(length); + buffer.copy(newBuf); + free(buffer); + return newBuf; +} +/** + * Reads an arbitrary signed int from a buffer. + */ + + +function readInt(buffer) { + var length = buffer.length; + var positive = buffer[length - 1] < 0x80; + var result = positive ? 0 : -1; + var lossy = false; // Note: We can't use bit manipulation here, since that stops + // working if the result won't fit in a 32-bit int. + + if (length < 7) { + // Common case which can't possibly be lossy (because the result has + // no more than 48 bits, and loss only happens with 54 or more). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i = length - 1; _i >= 0; _i--) { + var one = buffer[_i]; + result *= 0x100; + + if (isLossyToAdd(result, one)) { + lossy = true; + } + + result += one; + } + } + + return { + value: result, + lossy: lossy + }; +} +/** + * Reads an arbitrary unsigned int from a buffer. + */ + + +function readUInt(buffer) { + var length = buffer.length; + var result = 0; + var lossy = false; // Note: See above in re bit manipulation. + + if (length < 7) { + // Common case which can't possibly be lossy (see above). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i2 = length - 1; _i2 >= 0; _i2--) { + var one = buffer[_i2]; + result *= 0x100; + + if (isLossyToAdd(result, one)) { + lossy = true; + } + + result += one; + } + } + + return { + value: result, + lossy: lossy + }; +} +/** + * Writes a little-endian 64-bit signed int into a buffer. + */ + + +function writeInt64(value, buffer) { + if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) { + throw new Error("Value out of range."); + } + + if (value < 0) { + value += BIT_64; + } + + writeUInt64(value, buffer); +} +/** + * Writes a little-endian 64-bit unsigned int into a buffer. + */ + + +function writeUInt64(value, buffer) { + if (value < 0 || value > MAX_EXACT_UINT64) { + throw new Error("Value out of range."); + } + + var lowWord = value % BIT_32; + var highWord = Math.floor(value / BIT_32); + buffer.writeUInt32LE(lowWord, 0); + buffer.writeUInt32LE(highWord, 4); +} + +/***/ }), + +/***/ 33535: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeInt64 = decodeInt64; +exports.decodeUInt64 = decodeUInt64; +exports.decodeInt32 = decodeInt32; +exports.decodeUInt32 = decodeUInt32; +exports.encodeU32 = encodeU32; +exports.encodeI32 = encodeI32; +exports.encodeI64 = encodeI64; +exports.MAX_NUMBER_OF_BYTE_U64 = exports.MAX_NUMBER_OF_BYTE_U32 = void 0; + +var _leb = _interopRequireDefault(__webpack_require__(88281)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(32/7) + */ +var MAX_NUMBER_OF_BYTE_U32 = 5; +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(64/7) + */ + +exports.MAX_NUMBER_OF_BYTE_U32 = MAX_NUMBER_OF_BYTE_U32; +var MAX_NUMBER_OF_BYTE_U64 = 10; +exports.MAX_NUMBER_OF_BYTE_U64 = MAX_NUMBER_OF_BYTE_U64; + +function decodeInt64(encodedBuffer, index) { + return _leb.default.decodeInt64(encodedBuffer, index); +} + +function decodeUInt64(encodedBuffer, index) { + return _leb.default.decodeUInt64(encodedBuffer, index); +} + +function decodeInt32(encodedBuffer, index) { + return _leb.default.decodeInt32(encodedBuffer, index); +} + +function decodeUInt32(encodedBuffer, index) { + return _leb.default.decodeUInt32(encodedBuffer, index); +} + +function encodeU32(v) { + return _leb.default.encodeUInt32(v); +} + +function encodeI32(v) { + return _leb.default.encodeInt32(v); +} + +function encodeI64(v) { + return _leb.default.encodeInt64(v); +} + +/***/ }), + +/***/ 88281: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * leb: LEB128 utilities. + */ + +/* + * Modules used + */ + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +var bits = _interopRequireWildcard(__webpack_require__(6664)); + +var bufs = _interopRequireWildcard(__webpack_require__(87809)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + * Module variables + */ + +/** The minimum possible 32-bit signed int. */ +var MIN_INT32 = -0x80000000; +/** The maximum possible 32-bit signed int. */ + +var MAX_INT32 = 0x7fffffff; +/** The maximum possible 32-bit unsigned int. */ + +var MAX_UINT32 = 0xffffffff; +/** The minimum possible 64-bit signed int. */ +// const MIN_INT64 = -0x8000000000000000; + +/** + * The maximum possible 64-bit signed int that is representable as a + * JavaScript number. + */ +// const MAX_INT64 = 0x7ffffffffffffc00; + +/** + * The maximum possible 64-bit unsigned int that is representable as a + * JavaScript number. + */ +// const MAX_UINT64 = 0xfffffffffffff800; + +/* + * Helper functions + */ + +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as a signed value. The buffer is + * taken to represent a signed number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order non-sign-matching bit, plus two. For example: + * + * 11111011 01110101 + * high low + * + * The sign bit here is 1 (that is, it's a negative number). The highest + * bit number that doesn't match the sign is bit #10 (where the lowest-order + * bit is bit #0). So, we have to encode at least 12 bits total. + * + * As a special degenerate case, the numbers 0 and -1 each require just one bit. + */ + +function signedBitCount(buffer) { + return bits.highOrder(bits.getSign(buffer) ^ 1, buffer) + 2; +} +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as an unsigned value. The buffer is + * taken to represent an unsigned number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order 1 bit, plus one. For example: + * + * 00011000 01010011 + * high low + * + * The highest-order 1 bit here is bit #12 (where the lowest-order bit + * is bit #0). So, we have to encode at least 13 bits total. + * + * As a special degenerate case, the number 0 requires 1 bit. + */ + + +function unsignedBitCount(buffer) { + var result = bits.highOrder(1, buffer) + 1; + return result ? result : 1; +} +/** + * Common encoder for both signed and unsigned ints. This takes a + * bigint-ish buffer, returning an LEB128-encoded buffer. + */ + + +function encodeBufferCommon(buffer, signed) { + var signBit; + var bitCount; + + if (signed) { + signBit = bits.getSign(buffer); + bitCount = signedBitCount(buffer); + } else { + signBit = 0; + bitCount = unsignedBitCount(buffer); + } + + var byteCount = Math.ceil(bitCount / 7); + var result = bufs.alloc(byteCount); + + for (var i = 0; i < byteCount; i++) { + var payload = bits.extract(buffer, i * 7, 7, signBit); + result[i] = payload | 0x80; + } // Mask off the top bit of the last byte, to indicate the end of the + // encoding. + + + result[byteCount - 1] &= 0x7f; + return result; +} +/** + * Gets the byte-length of the value encoded in the given buffer at + * the given index. + */ + + +function encodedLength(encodedBuffer, index) { + var result = 0; + + while (encodedBuffer[index + result] >= 0x80) { + result++; + } + + result++; // to account for the last byte + + if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives + // throw new Error("integer representation too long"); + } + + return result; +} +/** + * Common decoder for both signed and unsigned ints. This takes an + * LEB128-encoded buffer, returning a bigint-ish buffer. + */ + + +function decodeBufferCommon(encodedBuffer, index, signed) { + index = index === undefined ? 0 : index; + var length = encodedLength(encodedBuffer, index); + var bitLength = length * 7; + var byteLength = Math.ceil(bitLength / 8); + var result = bufs.alloc(byteLength); + var outIndex = 0; + + while (length > 0) { + bits.inject(result, outIndex, 7, encodedBuffer[index]); + outIndex += 7; + index++; + length--; + } + + var signBit; + var signByte; + + if (signed) { + // Sign-extend the last byte. + var lastByte = result[byteLength - 1]; + var endBit = outIndex % 8; + + if (endBit !== 0) { + var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. + + lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff; + } + + signBit = lastByte >> 7; + signByte = signBit * 0xff; + } else { + signBit = 0; + signByte = 0; + } // Slice off any superfluous bytes, that is, ones that add no meaningful + // bits (because the value would be the same if they were removed). + + + while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) { + byteLength--; + } + + result = bufs.resize(result, byteLength); + return { + value: result, + nextIndex: index + }; +} +/* + * Exported bindings + */ + + +function encodeIntBuffer(buffer) { + return encodeBufferCommon(buffer, true); +} + +function decodeIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, true); +} + +function encodeInt32(num) { + var buf = bufs.alloc(4); + buf.writeInt32LE(num, 0); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeInt32(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + var parsed = bufs.readInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value < MIN_INT32 || value > MAX_INT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex + }; +} + +function encodeInt64(num) { + var buf = bufs.alloc(8); + bufs.writeInt64(num, buf); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeInt64(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, false); + + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false + }; +} + +function encodeUIntBuffer(buffer) { + return encodeBufferCommon(buffer, false); +} + +function decodeUIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, false); +} + +function encodeUInt32(num) { + var buf = bufs.alloc(4); + buf.writeUInt32LE(num, 0); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt32(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + var parsed = bufs.readUInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value > MAX_UINT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex + }; +} + +function encodeUInt64(num) { + var buf = bufs.alloc(8); + bufs.writeUInt64(num, buf); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt64(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, true); + + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false + }; +} + +var _default = { + decodeInt32: decodeInt32, + decodeInt64: decodeInt64, + decodeIntBuffer: decodeIntBuffer, + decodeUInt32: decodeUInt32, + decodeUInt64: decodeUInt64, + decodeUIntBuffer: decodeUIntBuffer, + encodeInt32: encodeInt32, + encodeInt64: encodeInt64, + encodeIntBuffer: encodeIntBuffer, + encodeUInt32: encodeUInt32, + encodeUInt64: encodeUInt64, + encodeUIntBuffer: encodeUIntBuffer +}; +exports.default = _default; + +/***/ }), + +/***/ 71583: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + +function con(b) { + if ((b & 0xc0) === 0x80) { + return b & 0x3f; + } else { + throw new Error("invalid UTF-8 encoding"); + } +} + +function code(min, n) { + if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { + throw new Error("invalid UTF-8 encoding"); + } else { + return n; + } +} + +function decode(bytes) { + return _decode(bytes).map(function (x) { + return String.fromCharCode(x); + }).join(""); +} + +function _decode(bytes) { + if (bytes.length === 0) { + return []; + } + /** + * 1 byte + */ + + + { + var _bytes = _toArray(bytes), + b1 = _bytes[0], + bs = _bytes.slice(1); + + if (b1 < 0x80) { + return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); + } + + if (b1 < 0xc0) { + throw new Error("invalid UTF-8 encoding"); + } + } + /** + * 2 bytes + */ + + { + var _bytes2 = _toArray(bytes), + _b = _bytes2[0], + b2 = _bytes2[1], + _bs = _bytes2.slice(2); + + if (_b < 0xe0) { + return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); + } + } + /** + * 3 bytes + */ + + { + var _bytes3 = _toArray(bytes), + _b2 = _bytes3[0], + _b3 = _bytes3[1], + b3 = _bytes3[2], + _bs2 = _bytes3.slice(3); + + if (_b2 < 0xf0) { + return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); + } + } + /** + * 4 bytes + */ + + { + var _bytes4 = _toArray(bytes), + _b4 = _bytes4[0], + _b5 = _bytes4[1], + _b6 = _bytes4[2], + b4 = _bytes4[3], + _bs3 = _bytes4.slice(4); + + if (_b4 < 0xf8) { + return [code(0x10000, (((_b4 & 0x07) << 18) + con(_b5) << 12) + (con(_b6) << 6) + con(b4))].concat(_toConsumableArray(_decode(_bs3))); + } + } + throw new Error("invalid UTF-8 encoding"); +} + +/***/ }), + +/***/ 74273: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encode = encode; + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + +function con(n) { + return 0x80 | n & 0x3f; +} + +function encode(str) { + var arr = str.split("").map(function (x) { + return x.charCodeAt(0); + }); + return _encode(arr); +} + +function _encode(arr) { + if (arr.length === 0) { + return []; + } + + var _arr = _toArray(arr), + n = _arr[0], + ns = _arr.slice(1); + + if (n < 0) { + throw new Error("utf8"); + } + + if (n < 0x80) { + return [n].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x800) { + return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x10000) { + return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x110000) { + return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + throw new Error("utf8"); +} + +/***/ }), + +/***/ 78454: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "decode", ({ + enumerable: true, + get: function get() { + return _decoder.decode; + } +})); +Object.defineProperty(exports, "encode", ({ + enumerable: true, + get: function get() { + return _encoder.encode; + } +})); + +var _decoder = __webpack_require__(71583); + +var _encoder = __webpack_require__(74273); + +/***/ }), + +/***/ 81279: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.applyOperations = applyOperations; + +var _wasmGen = __webpack_require__(80353); + +var _encoder = __webpack_require__(63097); + +var _ast = __webpack_require__(77325); + +var _helperWasmSection = __webpack_require__(47020); + +var _helperBuffer = __webpack_require__(52877); + +var _helperWasmBytecode = __webpack_require__(24222); + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function shiftLocNodeByDelta(node, delta) { + (0, _ast.assertHasLoc)(node); // $FlowIgnore: assertHasLoc ensures that + + node.loc.start.column += delta; // $FlowIgnore: assertHasLoc ensures that + + node.loc.end.column += delta; +} + +function applyUpdate(ast, uint8Buffer, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + oldNode = _ref2[0], + newNode = _ref2[1]; + + var deltaElements = 0; + (0, _ast.assertHasLoc)(oldNode); + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(newNode); + var replacementByteArray = (0, _wasmGen.encodeNode)(newNode); + /** + * Replace new node as bytes + */ + + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.start.column, // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.end.column, replacementByteArray); + /** + * Update function body size if needed + */ + + if (sectionName === "code") { + // Find the parent func + (0, _ast.traverse)(ast, { + Func: function Func(_ref3) { + var node = _ref3.node; + var funcHasThisIntr = node.body.find(function (n) { + return n === newNode; + }) !== undefined; // Update func's body size if needed + + if (funcHasThisIntr === true) { + // These are the old functions locations informations + (0, _ast.assertHasLoc)(node); + var oldNodeSize = (0, _wasmGen.encodeNode)(oldNode).length; + var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize; + + if (bodySizeDeltaBytes !== 0) { + var newValue = node.metadata.bodySize + bodySizeDeltaBytes; + var newByteArray = (0, _encoder.encodeU32)(newValue); // function body size byte + // FIXME(sven): only handles one byte u32 + + var start = node.loc.start.column; + var end = start + 1; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray); + } + } + } + }); + } + /** + * Update section size + */ + + + var deltaBytes = replacementByteArray.length - ( // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.end.column - oldNode.loc.start.column); // Init location informations + + newNode.loc = { + start: { + line: -1, + column: -1 + }, + end: { + line: -1, + column: -1 + } + }; // Update new node end position + // $FlowIgnore: assertHasLoc ensures that + + newNode.loc.start.column = oldNode.loc.start.column; // $FlowIgnore: assertHasLoc ensures that + + newNode.loc.end.column = // $FlowIgnore: assertHasLoc ensures that + oldNode.loc.start.column + replacementByteArray.length; + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyDelete(ast, uint8Buffer, node) { + var deltaElements = -1; // since we removed an element + + (0, _ast.assertHasLoc)(node); + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node); + + if (sectionName === "start") { + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, "start"); + /** + * The start section only contains one element, + * we need to remove the whole section + */ + + uint8Buffer = (0, _helperWasmSection.removeSections)(ast, uint8Buffer, "start"); + + var _deltaBytes = -(sectionMetadata.size.value + 1); + /* section id */ + + + return { + uint8Buffer: uint8Buffer, + deltaBytes: _deltaBytes, + deltaElements: deltaElements + }; + } // replacement is nothing + + + var replacement = []; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that + node.loc.start.column, // $FlowIgnore: assertHasLoc ensures that + node.loc.end.column, replacement); + /** + * Update section + */ + // $FlowIgnore: assertHasLoc ensures that + + var deltaBytes = -(node.loc.end.column - node.loc.start.column); + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyAdd(ast, uint8Buffer, node) { + var deltaElements = +1; // since we added an element + + var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node); + var sectionMetadata = (0, _ast.getSectionMetadata)(ast, sectionName); // Section doesn't exists, we create an empty one + + if (typeof sectionMetadata === "undefined") { + var res = (0, _helperWasmSection.createEmptySection)(ast, uint8Buffer, sectionName); + uint8Buffer = res.uint8Buffer; + sectionMetadata = res.sectionMetadata; + } + /** + * check that the expressions were ended + */ + + + if ((0, _ast.isFunc)(node)) { + // $FlowIgnore + var body = node.body; + + if (body.length === 0 || body[body.length - 1].id !== "end") { + throw new Error("expressions must be ended"); + } + } + + if ((0, _ast.isGlobal)(node)) { + // $FlowIgnore + var body = node.init; + + if (body.length === 0 || body[body.length - 1].id !== "end") { + throw new Error("expressions must be ended"); + } + } + /** + * Add nodes + */ + + + var newByteArray = (0, _wasmGen.encodeNode)(node); // The size of the section doesn't include the storage of the size itself + // we need to manually add it here + + var start = (0, _ast.getEndOfSection)(sectionMetadata); + var end = start; + /** + * Update section + */ + + var deltaBytes = newByteArray.length; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray); + node.loc = { + start: { + line: -1, + column: start + }, + end: { + line: -1, + column: start + deltaBytes + } + }; // for func add the additional metadata in the AST + + if (node.type === "Func") { + // the size is the first byte + // FIXME(sven): handle LEB128 correctly here + var bodySize = newByteArray[0]; + node.metadata = { + bodySize: bodySize + }; + } + + if (node.type !== "IndexInFuncSection") { + (0, _ast.orderedInsertNode)(ast.body[0], node); + } + + return { + uint8Buffer: uint8Buffer, + deltaBytes: deltaBytes, + deltaElements: deltaElements + }; +} + +function applyOperations(ast, uint8Buffer, ops) { + ops.forEach(function (op) { + var state; + var sectionName; + + switch (op.kind) { + case "update": + state = applyUpdate(ast, uint8Buffer, [op.oldNode, op.node]); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + case "delete": + state = applyDelete(ast, uint8Buffer, op.node); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + case "add": + state = applyAdd(ast, uint8Buffer, op.node); + sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node); + break; + + default: + throw new Error("Unknown operation"); + } + /** + * Resize section vec size. + * If the length of the LEB-encoded size changes, this can change + * the byte length of the section and the offset for nodes in the + * section. So we do this first before resizing section byte size + * or shifting following operations' nodes. + */ + + + if (state.deltaElements !== 0 && sectionName !== "start") { + var oldBufferLength = state.uint8Buffer.length; + state.uint8Buffer = (0, _helperWasmSection.resizeSectionVecSize)(ast, state.uint8Buffer, sectionName, state.deltaElements); // Infer bytes added/removed by comparing buffer lengths + + state.deltaBytes += state.uint8Buffer.length - oldBufferLength; + } + /** + * Resize section byte size. + * If the length of the LEB-encoded size changes, this can change + * the offset for nodes in the section. So we do this before + * shifting following operations' nodes. + */ + + + if (state.deltaBytes !== 0 && sectionName !== "start") { + var _oldBufferLength = state.uint8Buffer.length; + state.uint8Buffer = (0, _helperWasmSection.resizeSectionByteSize)(ast, state.uint8Buffer, sectionName, state.deltaBytes); // Infer bytes added/removed by comparing buffer lengths + + state.deltaBytes += state.uint8Buffer.length - _oldBufferLength; + } + /** + * Shift following operation's nodes + */ + + + if (state.deltaBytes !== 0) { + ops.forEach(function (op) { + // We don't need to handle add ops, they are positioning independent + switch (op.kind) { + case "update": + shiftLocNodeByDelta(op.oldNode, state.deltaBytes); + break; + + case "delete": + shiftLocNodeByDelta(op.node, state.deltaBytes); + break; + } + }); + } + + uint8Buffer = state.uint8Buffer; + }); + return uint8Buffer; +} + +/***/ }), + +/***/ 38811: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.edit = edit; +exports.editWithAST = editWithAST; +exports.add = add; +exports.addWithAST = addWithAST; + +var _wasmParser = __webpack_require__(81582); + +var _ast = __webpack_require__(77325); + +var _clone = __webpack_require__(25899); + +var _wasmOpt = __webpack_require__(47608); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(24222)); + +var _apply = __webpack_require__(81279); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function hashNode(node) { + return JSON.stringify(node); +} + +function preprocess(ab) { + var optBin = (0, _wasmOpt.shrinkPaddedLEB128)(new Uint8Array(ab)); + return optBin.buffer; +} + +function sortBySectionOrder(nodes) { + var originalOrder = new Map(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _node = _step.value; + originalOrder.set(_node, originalOrder.size); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + nodes.sort(function (a, b) { + var sectionA = (0, _helperWasmBytecode.getSectionForNode)(a); + var sectionB = (0, _helperWasmBytecode.getSectionForNode)(b); + var aId = _helperWasmBytecode.default.sections[sectionA]; + var bId = _helperWasmBytecode.default.sections[sectionB]; + + if (typeof aId !== "number" || typeof bId !== "number") { + throw new Error("Section id not found"); + } + + if (aId === bId) { + // $FlowIgnore originalOrder is filled for all nodes + return originalOrder.get(a) - originalOrder.get(b); + } + + return aId - bId; + }); +} + +function edit(ab, visitors) { + ab = preprocess(ab); + var ast = (0, _wasmParser.decode)(ab); + return editWithAST(ast, ab, visitors); +} + +function editWithAST(ast, ab, visitors) { + var operations = []; + var uint8Buffer = new Uint8Array(ab); + var nodeBefore; + + function before(type, path) { + nodeBefore = (0, _clone.cloneNode)(path.node); + } + + function after(type, path) { + if (path.node._deleted === true) { + operations.push({ + kind: "delete", + node: path.node + }); // $FlowIgnore + } else if (hashNode(nodeBefore) !== hashNode(path.node)) { + operations.push({ + kind: "update", + oldNode: nodeBefore, + node: path.node + }); + } + } + + (0, _ast.traverse)(ast, visitors, before, after); + uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations); + return uint8Buffer.buffer; +} + +function add(ab, newNodes) { + ab = preprocess(ab); + var ast = (0, _wasmParser.decode)(ab); + return addWithAST(ast, ab, newNodes); +} + +function addWithAST(ast, ab, newNodes) { + // Sort nodes by insertion order + sortBySectionOrder(newNodes); + var uint8Buffer = new Uint8Array(ab); // Map node into operations + + var operations = newNodes.map(function (n) { + return { + kind: "add", + node: n + }; + }); + uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations); + return uint8Buffer.buffer; +} + +/***/ }), + +/***/ 63097: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeVersion = encodeVersion; +exports.encodeHeader = encodeHeader; +exports.encodeU32 = encodeU32; +exports.encodeI32 = encodeI32; +exports.encodeI64 = encodeI64; +exports.encodeVec = encodeVec; +exports.encodeValtype = encodeValtype; +exports.encodeMutability = encodeMutability; +exports.encodeUTF8Vec = encodeUTF8Vec; +exports.encodeLimits = encodeLimits; +exports.encodeModuleImport = encodeModuleImport; +exports.encodeSectionMetadata = encodeSectionMetadata; +exports.encodeCallInstruction = encodeCallInstruction; +exports.encodeCallIndirectInstruction = encodeCallIndirectInstruction; +exports.encodeModuleExport = encodeModuleExport; +exports.encodeTypeInstruction = encodeTypeInstruction; +exports.encodeInstr = encodeInstr; +exports.encodeStringLiteral = encodeStringLiteral; +exports.encodeGlobal = encodeGlobal; +exports.encodeFuncBody = encodeFuncBody; +exports.encodeIndexInFuncSection = encodeIndexInFuncSection; +exports.encodeElem = encodeElem; + +var leb = _interopRequireWildcard(__webpack_require__(33535)); + +var ieee754 = _interopRequireWildcard(__webpack_require__(51761)); + +var utf8 = _interopRequireWildcard(__webpack_require__(78454)); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(24222)); + +var _index = __webpack_require__(80353); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function assertNotIdentifierNode(n) { + if (n.type === "Identifier") { + throw new Error("Unsupported node Identifier"); + } +} + +function encodeVersion(v) { + var bytes = _helperWasmBytecode.default.moduleVersion; + bytes[0] = v; + return bytes; +} + +function encodeHeader() { + return _helperWasmBytecode.default.magicModuleHeader; +} + +function encodeU32(v) { + var uint8view = new Uint8Array(leb.encodeU32(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeI32(v) { + var uint8view = new Uint8Array(leb.encodeI32(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeI64(v) { + var uint8view = new Uint8Array(leb.encodeI64(v)); + + var array = _toConsumableArray(uint8view); + + return array; +} + +function encodeVec(elements) { + var size = encodeU32(elements.length); + return _toConsumableArray(size).concat(_toConsumableArray(elements)); +} + +function encodeValtype(v) { + var byte = _helperWasmBytecode.default.valtypesByString[v]; + + if (typeof byte === "undefined") { + throw new Error("Unknown valtype: " + v); + } + + return parseInt(byte, 10); +} + +function encodeMutability(v) { + var byte = _helperWasmBytecode.default.globalTypesByString[v]; + + if (typeof byte === "undefined") { + throw new Error("Unknown mutability: " + v); + } + + return parseInt(byte, 10); +} + +function encodeUTF8Vec(str) { + return encodeVec(utf8.encode(str)); +} + +function encodeLimits(n) { + var out = []; + + if (typeof n.max === "number") { + out.push(0x01); + out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof + + out.push.apply(out, _toConsumableArray(encodeU32(n.max))); + } else { + out.push(0x00); + out.push.apply(out, _toConsumableArray(encodeU32(n.min))); + } + + return out; +} + +function encodeModuleImport(n) { + var out = []; + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module))); + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name))); + + switch (n.descr.type) { + case "GlobalType": + { + out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists + + out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists + + out.push(encodeMutability(n.descr.mutability)); + break; + } + + case "Memory": + { + out.push(0x02); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits))); + break; + } + + case "Table": + { + out.push(0x01); + out.push(0x70); // element type + // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits))); + break; + } + + case "FuncImportDescr": + { + out.push(0x00); // $FlowIgnore + + assertNotIdentifierNode(n.descr.id); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value))); + break; + } + + default: + throw new Error("Unsupport operation: encode module import of type: " + n.descr.type); + } + + return out; +} + +function encodeSectionMetadata(n) { + var out = []; + var sectionId = _helperWasmBytecode.default.sections[n.section]; + + if (typeof sectionId === "undefined") { + throw new Error("Unknown section: " + n.section); + } + + if (n.section === "start") { + /** + * This is not implemented yet because it's a special case which + * doesn't have a vector in its section. + */ + throw new Error("Unsupported section encoding of type start"); + } + + out.push(sectionId); + out.push.apply(out, _toConsumableArray(encodeU32(n.size.value))); + out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value))); + return out; +} + +function encodeCallInstruction(n) { + var out = []; + assertNotIdentifierNode(n.index); + out.push(0x10); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); + return out; +} + +function encodeCallIndirectInstruction(n) { + var out = []; // $FlowIgnore + + assertNotIdentifierNode(n.index); + out.push(0x11); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte + + out.push(0x00); + return out; +} + +function encodeModuleExport(n) { + var out = []; + assertNotIdentifierNode(n.descr.id); + var exportTypeByteString = _helperWasmBytecode.default.exportTypesByName[n.descr.exportType]; + + if (typeof exportTypeByteString === "undefined") { + throw new Error("Unknown export of type: " + n.descr.exportType); + } + + var exportTypeByte = parseInt(exportTypeByteString, 10); + out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name))); + out.push(exportTypeByte); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value))); + return out; +} + +function encodeTypeInstruction(n) { + var out = [0x60]; + var params = n.functype.params.map(function (x) { + return x.valtype; + }).map(encodeValtype); + var results = n.functype.results.map(encodeValtype); + out.push.apply(out, _toConsumableArray(encodeVec(params))); + out.push.apply(out, _toConsumableArray(encodeVec(results))); + return out; +} + +function encodeInstr(n) { + var out = []; + var instructionName = n.id; + + if (typeof n.object === "string") { + instructionName = "".concat(n.object, ".").concat(String(n.id)); + } + + var byteString = _helperWasmBytecode.default.symbolsByName[instructionName]; + + if (typeof byteString === "undefined") { + throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName)); + } + + var byte = parseInt(byteString, 10); + out.push(byte); + + if (n.args) { + n.args.forEach(function (arg) { + var encoder = encodeU32; // find correct encoder + + if (n.object === "i32") { + encoder = encodeI32; + } + + if (n.object === "i64") { + encoder = encodeI64; + } + + if (n.object === "f32") { + encoder = ieee754.encodeF32; + } + + if (n.object === "f64") { + encoder = ieee754.encodeF64; + } + + if (arg.type === "NumberLiteral" || arg.type === "FloatLiteral" || arg.type === "LongNumberLiteral") { + // $FlowIgnore + out.push.apply(out, _toConsumableArray(encoder(arg.value))); + } else { + throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type)); + } + }); + } + + return out; +} + +function encodeExpr(instrs) { + var out = []; + instrs.forEach(function (instr) { + // $FlowIgnore + var n = (0, _index.encodeNode)(instr); + out.push.apply(out, _toConsumableArray(n)); + }); + return out; +} + +function encodeStringLiteral(n) { + return encodeUTF8Vec(n.value); +} + +function encodeGlobal(n) { + var out = []; + var _n$globalType = n.globalType, + valtype = _n$globalType.valtype, + mutability = _n$globalType.mutability; + out.push(encodeValtype(valtype)); + out.push(encodeMutability(mutability)); + out.push.apply(out, _toConsumableArray(encodeExpr(n.init))); + return out; +} + +function encodeFuncBody(n) { + var out = []; + out.push(-1); // temporary function body size + // FIXME(sven): get the func locals? + + var localBytes = encodeVec([]); + out.push.apply(out, _toConsumableArray(localBytes)); + var funcBodyBytes = encodeExpr(n.body); + out[0] = funcBodyBytes.length + localBytes.length; + out.push.apply(out, _toConsumableArray(funcBodyBytes)); + return out; +} + +function encodeIndexInFuncSection(n) { + assertNotIdentifierNode(n.index); // $FlowIgnore + + return encodeU32(n.index.value); +} + +function encodeElem(n) { + var out = []; + assertNotIdentifierNode(n.table); // $FlowIgnore + + out.push.apply(out, _toConsumableArray(encodeU32(n.table.value))); + out.push.apply(out, _toConsumableArray(encodeExpr(n.offset))); // $FlowIgnore + + var funcs = n.funcs.reduce(function (acc, x) { + return _toConsumableArray(acc).concat(_toConsumableArray(encodeU32(x.value))); + }, []); + out.push.apply(out, _toConsumableArray(encodeVec(funcs))); + return out; +} + +/***/ }), + +/***/ 80353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeNode = encodeNode; +exports.encodeU32 = void 0; + +var encoder = _interopRequireWildcard(__webpack_require__(63097)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function encodeNode(n) { + switch (n.type) { + case "ModuleImport": + // $FlowIgnore: ModuleImport ensure that the node is well formated + return encoder.encodeModuleImport(n); + + case "SectionMetadata": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeSectionMetadata(n); + + case "CallInstruction": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeCallInstruction(n); + + case "CallIndirectInstruction": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeCallIndirectInstruction(n); + + case "TypeInstruction": + return encoder.encodeTypeInstruction(n); + + case "Instr": + // $FlowIgnore + return encoder.encodeInstr(n); + + case "ModuleExport": + // $FlowIgnore: SectionMetadata ensure that the node is well formated + return encoder.encodeModuleExport(n); + + case "Global": + // $FlowIgnore + return encoder.encodeGlobal(n); + + case "Func": + return encoder.encodeFuncBody(n); + + case "IndexInFuncSection": + return encoder.encodeIndexInFuncSection(n); + + case "StringLiteral": + return encoder.encodeStringLiteral(n); + + case "Elem": + return encoder.encodeElem(n); + + default: + throw new Error("Unsupported encoding for node of type: " + JSON.stringify(n.type)); + } +} + +var encodeU32 = encoder.encodeU32; +exports.encodeU32 = encodeU32; + +/***/ }), + +/***/ 47608: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.shrinkPaddedLEB128 = shrinkPaddedLEB128; + +var _wasmParser = __webpack_require__(81582); + +var _leb = __webpack_require__(72691); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var OptimizerError = +/*#__PURE__*/ +function (_Error) { + _inherits(OptimizerError, _Error); + + function OptimizerError(name, initalError) { + var _this; + + _classCallCheck(this, OptimizerError); + + _this = _possibleConstructorReturn(this, (OptimizerError.__proto__ || Object.getPrototypeOf(OptimizerError)).call(this, "Error while optimizing: " + name + ": " + initalError.message)); + _this.stack = initalError.stack; + return _this; + } + + return OptimizerError; +}(Error); + +var decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true +}; + +function shrinkPaddedLEB128(uint8Buffer) { + try { + var ast = (0, _wasmParser.decode)(uint8Buffer.buffer, decoderOpts); + return (0, _leb.shrinkPaddedLEB128)(ast, uint8Buffer); + } catch (e) { + throw new OptimizerError("shrinkPaddedLEB128", e); + } +} + +/***/ }), + +/***/ 72691: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.shrinkPaddedLEB128 = shrinkPaddedLEB128; + +var _ast = __webpack_require__(77325); + +var _encoder = __webpack_require__(63097); + +var _helperBuffer = __webpack_require__(52877); + +function shiftFollowingSections(ast, _ref, deltaInSizeEncoding) { + var section = _ref.section; + // Once we hit our section every that is after needs to be shifted by the delta + var encounteredSection = false; + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(path) { + if (path.node.section === section) { + encounteredSection = true; + return; + } + + if (encounteredSection === true) { + (0, _ast.shiftSection)(ast, path.node, deltaInSizeEncoding); + } + } + }); +} + +function shrinkPaddedLEB128(ast, uint8Buffer) { + (0, _ast.traverse)(ast, { + SectionMetadata: function SectionMetadata(_ref2) { + var node = _ref2.node; + + /** + * Section size + */ + { + var newu32Encoded = (0, _encoder.encodeU32)(node.size.value); + var newu32EncodedLen = newu32Encoded.length; + var start = node.size.loc.start.column; + var end = node.size.loc.end.column; + var oldu32EncodedLen = end - start; + + if (newu32EncodedLen !== oldu32EncodedLen) { + var deltaInSizeEncoding = oldu32EncodedLen - newu32EncodedLen; + uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newu32Encoded); + shiftFollowingSections(ast, node, -deltaInSizeEncoding); + } + } + } + }); + return uint8Buffer; +} + +/***/ }), + +/***/ 70525: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +var _helperApiError = __webpack_require__(26833); + +var ieee754 = _interopRequireWildcard(__webpack_require__(51761)); + +var utf8 = _interopRequireWildcard(__webpack_require__(78454)); + +var t = _interopRequireWildcard(__webpack_require__(77325)); + +var _leb = __webpack_require__(33535); + +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(24222)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function toHex(n) { + return "0x" + Number(n).toString(16); +} + +function byteArrayEq(l, r) { + if (l.length !== r.length) { + return false; + } + + for (var i = 0; i < l.length; i++) { + if (l[i] !== r[i]) { + return false; + } + } + + return true; +} + +function decode(ab, opts) { + var buf = new Uint8Array(ab); + var getUniqueName = t.getUniqueNameGenerator(); + var offset = 0; + + function getPosition() { + return { + line: -1, + column: offset + }; + } + + function dump(b, msg) { + if (opts.dump === false) return; + var pad = "\t\t\t\t\t\t\t\t\t\t"; + var str = ""; + + if (b.length < 5) { + str = b.map(toHex).join(" "); + } else { + str = "..."; + } + + console.log(toHex(offset) + ":\t", str, pad, ";", msg); + } + + function dumpSep(msg) { + if (opts.dump === false) return; + console.log(";", msg); + } + /** + * TODO(sven): we can atually use a same structure + * we are adding incrementally new features + */ + + + var state = { + elementsInFuncSection: [], + elementsInExportSection: [], + elementsInCodeSection: [], + + /** + * Decode memory from: + * - Memory section + */ + memoriesInModule: [], + + /** + * Decoded types from: + * - Type section + */ + typesInModule: [], + + /** + * Decoded functions from: + * - Function section + * - Import section + */ + functionsInModule: [], + + /** + * Decoded tables from: + * - Table section + */ + tablesInModule: [], + + /** + * Decoded globals from: + * - Global section + */ + globalsInModule: [] + }; + + function isEOF() { + return offset >= buf.length; + } + + function eatBytes(n) { + offset = offset + n; + } + + function readBytesAtOffset(_offset, numberOfBytes) { + var arr = []; + + for (var i = 0; i < numberOfBytes; i++) { + arr.push(buf[_offset + i]); + } + + return arr; + } + + function readBytes(numberOfBytes) { + return readBytesAtOffset(offset, numberOfBytes); + } + + function readF64() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64); + var value = ieee754.decodeF64(bytes); + + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; + + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } + + mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + function readF32() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32); + var value = ieee754.decodeF32(bytes); + + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; + + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } + + mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } + + function readUTF8String() { + var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using + // readBytesAtOffset below. This keeps readUTF8String neutral with respect + // to the current offset, just like the other readX functions. + + var strlen = lenu32.value; + dump([strlen], "string length"); + var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen); + var value = utf8.decode(bytes); + return { + value: value, + nextIndex: strlen + lenu32.nextIndex + }; + } + /** + * Decode an unsigned 32bits integer + * + * The length will be handled by the leb librairy, we pass the max number of + * byte. + */ + + + function readU32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + + function readVaruint32() { + // where 32 bits = max 4 bytes + var bytes = readBytes(4); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + + function readVaruint7() { + // where 7 bits = max 1 bytes + var bytes = readBytes(1); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } + /** + * Decode a signed 32bits interger + */ + + + function read32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt32)(buffer); + } + /** + * Decode a signed 64bits integer + */ + + + function read64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt64)(buffer); + } + + function readU64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt64)(buffer); + } + + function readByte() { + return readBytes(1)[0]; + } + + function parseModuleHeader() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } + + var header = readBytes(4); + + if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { + throw new _helperApiError.CompileError("magic header not detected"); + } + + dump(header, "wasm magic header"); + eatBytes(4); + } + + function parseVersion() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } + + var version = readBytes(4); + + if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) { + throw new _helperApiError.CompileError("unknown binary version"); + } + + dump(version, "wasm version"); + eatBytes(4); + } + + function parseVec(cast) { + var u32 = readU32(); + var length = u32.value; + eatBytes(u32.nextIndex); + dump([length], "number"); + + if (length === 0) { + return []; + } + + var elements = []; + + for (var i = 0; i < length; i++) { + var byte = readByte(); + eatBytes(1); + var value = cast(byte); + dump([byte], value); + + if (typeof value === "undefined") { + throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value"); + } + + elements.push(value); + } + + return elements; + } // Type section + // https://webassembly.github.io/spec/binary/modules.html#binary-typesec + + + function parseTypeSection(numberOfTypes) { + var typeInstructionNodes = []; + dump([numberOfTypes], "num types"); + + for (var i = 0; i < numberOfTypes; i++) { + var _startLoc = getPosition(); + + dumpSep("type " + i); + var type = readByte(); + eatBytes(1); + + if (type == _helperWasmBytecode.default.types.func) { + dump([type], "func"); + var paramValtypes = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + var params = paramValtypes.map(function (v) { + return t.funcParam( + /*valtype*/ + v); + }); + var result = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + typeInstructionNodes.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc); + }()); + state.typesInModule.push({ + params: params, + result: result + }); + } else { + throw new Error("Unsupported type: " + toHex(type)); + } + } + + return typeInstructionNodes; + } // Import section + // https://webassembly.github.io/spec/binary/modules.html#binary-importsec + + + function parseImportSection(numberOfImports) { + var imports = []; + + for (var i = 0; i < numberOfImports; i++) { + dumpSep("import header " + i); + + var _startLoc2 = getPosition(); + /** + * Module name + */ + + + var moduleName = readUTF8String(); + eatBytes(moduleName.nextIndex); + dump([], "module name (".concat(moduleName.value, ")")); + /** + * Name + */ + + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "name (".concat(name.value, ")")); + /** + * Import descr + */ + + var descrTypeByte = readByte(); + eatBytes(1); + var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte]; + dump([descrTypeByte], "import kind"); + + if (typeof descrType === "undefined") { + throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte)); + } + + var importDescr = void 0; + + if (descrType === "func") { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } + + var id = getUniqueName("func"); + importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result)); + state.functionsInModule.push({ + id: t.identifier(name.value), + signature: signature, + isExternal: true + }); + } else if (descrType === "global") { + importDescr = parseGlobalType(); + var globalNode = t.global(importDescr, []); + state.globalsInModule.push(globalNode); + } else if (descrType === "table") { + importDescr = parseTableType(i); + } else if (descrType === "mem") { + var memoryNode = parseMemoryType(0); + state.memoriesInModule.push(memoryNode); + importDescr = memoryNode; + } else { + throw new _helperApiError.CompileError("Unsupported import of type: " + descrType); + } + + imports.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2); + }()); + } + + return imports; + } // Function section + // https://webassembly.github.io/spec/binary/modules.html#function-section + + + function parseFuncSection(numberOfFunctions) { + dump([numberOfFunctions], "num funcs"); + + for (var i = 0; i < numberOfFunctions; i++) { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } // preserve anonymous, a name might be resolved later + + + var id = t.withRaw(t.identifier(getUniqueName("func")), ""); + state.functionsInModule.push({ + id: id, + signature: signature, + isExternal: false + }); + } + } // Export section + // https://webassembly.github.io/spec/binary/modules.html#export-section + + + function parseExportSection(numberOfExport) { + dump([numberOfExport], "num exports"); // Parse vector of exports + + for (var i = 0; i < numberOfExport; i++) { + var _startLoc3 = getPosition(); + /** + * Name + */ + + + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "export name (".concat(name.value, ")")); + /** + * exportdescr + */ + + var typeIndex = readByte(); + eatBytes(1); + dump([typeIndex], "export kind"); + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "export index"); + var id = void 0, + signature = void 0; + + if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") { + var func = state.functionsInModule[index]; + + if (typeof func === "undefined") { + throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = func.signature; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { + var table = state.tablesInModule[index]; + + if (typeof table === "undefined") { + throw new _helperApiError.CompileError("unknown table ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { + var memNode = state.memoriesInModule[index]; + + if (typeof memNode === "undefined") { + throw new _helperApiError.CompileError("unknown memory ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { + var global = state.globalsInModule[index]; + + if (typeof global === "undefined") { + throw new _helperApiError.CompileError("unknown global ".concat(index)); + } + + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else { + console.warn("Unsupported export type: " + toHex(typeIndex)); + return; + } + + var endLoc = getPosition(); + state.elementsInExportSection.push({ + name: name.value, + type: _helperWasmBytecode.default.exportTypes[typeIndex], + signature: signature, + id: id, + index: index, + endLoc: endLoc, + startLoc: _startLoc3 + }); + } + } // Code section + // https://webassembly.github.io/spec/binary/modules.html#code-section + + + function parseCodeSection(numberOfFuncs) { + dump([numberOfFuncs], "number functions"); // Parse vector of function + + for (var i = 0; i < numberOfFuncs; i++) { + var _startLoc4 = getPosition(); + + dumpSep("function body " + i); // the u32 size of the function code in bytes + // Ignore it for now + + var bodySizeU32 = readU32(); + eatBytes(bodySizeU32.nextIndex); + dump([bodySizeU32.value], "function body size"); + var code = []; + /** + * Parse locals + */ + + var funcLocalNumU32 = readU32(); + var funcLocalNum = funcLocalNumU32.value; + eatBytes(funcLocalNumU32.nextIndex); + dump([funcLocalNum], "num locals"); + var locals = []; + + for (var _i = 0; _i < funcLocalNum; _i++) { + var _startLoc5 = getPosition(); + + var localCountU32 = readU32(); + var localCount = localCountU32.value; + eatBytes(localCountU32.nextIndex); + dump([localCount], "num local"); + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + var args = []; + + for (var _i2 = 0; _i2 < localCount; _i2++) { + args.push(t.valtypeLiteral(type)); + } + + var localNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); + }(); + + locals.push(localNode); + dump([valtypeByte], type); + + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); + } + } + + code.push.apply(code, locals); // Decode instructions until the end + + parseInstructionBlock(code); + var endLoc = getPosition(); + state.elementsInCodeSection.push({ + code: code, + locals: locals, + endLoc: endLoc, + startLoc: _startLoc4, + bodySize: bodySizeU32.value + }); + } + } + + function parseInstructionBlock(code) { + while (true) { + var _startLoc6 = getPosition(); + + var instructionAlreadyCreated = false; + var instructionByte = readByte(); + eatBytes(1); + + if (instructionByte === 0xfe) { + throw new _helperApiError.CompileError("Atomic instructions are not implemented"); + } + + var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; + + if (typeof instruction === "undefined") { + throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); + } + + if (typeof instruction.object === "string") { + dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); + } else { + dump([instructionByte], instruction.name); + } + /** + * End of the function + */ + + + if (instruction.name === "end") { + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); + }(); + + code.push(node); + break; + } + + var args = []; + + if (instruction.name === "loop") { + var _startLoc7 = getPosition(); + + var blocktypeByte = readByte(); + eatBytes(1); + var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte]; + dump([blocktypeByte], "blocktype"); + + if (typeof blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte)); + } + + var instr = []; + parseInstructionBlock(instr); // preserve anonymous + + var label = t.withRaw(t.identifier(getUniqueName("loop")), ""); + + var loopNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); + }(); + + code.push(loopNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "if") { + var _startLoc8 = getPosition(); + + var _blocktypeByte = readByte(); + + eatBytes(1); + var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; + dump([_blocktypeByte], "blocktype"); + + if (typeof _blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); + } + + var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); + var ifBody = []; + parseInstructionBlock(ifBody); // Defaults to no alternate + + var elseIndex = 0; + + for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { + var _instr = ifBody[elseIndex]; + + if (_instr.type === "Instr" && _instr.id === "else") { + break; + } + } + + var consequentInstr = ifBody.slice(0, elseIndex); + var alternate = ifBody.slice(elseIndex + 1); // wast sugar + + var testInstrs = []; + + var ifNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); + }(); + + code.push(ifNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "block") { + var _startLoc9 = getPosition(); + + var _blocktypeByte2 = readByte(); + + eatBytes(1); + var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; + dump([_blocktypeByte2], "blocktype"); + + if (typeof _blocktype2 === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); + } + + var _instr2 = []; + parseInstructionBlock(_instr2); // preserve anonymous + + var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); + + var blockNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); + }(); + + code.push(blockNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call") { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); + + var callNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6); + }(); + + code.push(callNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call_indirect") { + var _startLoc10 = getPosition(); + + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; + + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")")); + } + + var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []); + + var flagU32 = readU32(); + var flag = flagU32.value; // 0x00 - reserved byte + + eatBytes(flagU32.nextIndex); + + if (flag !== 0) { + throw new _helperApiError.CompileError("zero flag expected"); + } + + code.push(function () { + var endLoc = getPosition(); + return t.withLoc(_callNode, endLoc, _startLoc10); + }()); + instructionAlreadyCreated = true; + } else if (instruction.name === "br_table") { + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + + for (var i = 0; i <= indices; i++) { + var _indexu = readU32(); + + var _index = _indexu.value; + eatBytes(_indexu.nextIndex); + dump([_index], "index"); + args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32")); + } + } else if (instructionByte >= 0x28 && instructionByte <= 0x40) { + /** + * Memory instructions + */ + if (instruction.name === "grow_memory" || instruction.name === "current_memory") { + var _indexU = readU32(); + + var _index2 = _indexU.value; + eatBytes(_indexU.nextIndex); + + if (_index2 !== 0) { + throw new Error("zero flag expected"); + } + + dump([_index2], "index"); + } else { + var aligun32 = readU32(); + var align = aligun32.value; + eatBytes(aligun32.nextIndex); + dump([align], "align"); + var offsetu32 = readU32(); + var _offset2 = offsetu32.value; + eatBytes(offsetu32.nextIndex); + dump([_offset2], "offset"); + } + } else if (instructionByte >= 0x41 && instructionByte <= 0x44) { + /** + * Numeric instructions + */ + if (instruction.object === "i32") { + var value32 = read32(); + var value = value32.value; + eatBytes(value32.nextIndex); + dump([value], "i32 value"); + args.push(t.numberLiteralFromRaw(value)); + } + + if (instruction.object === "u32") { + var valueu32 = readU32(); + var _value = valueu32.value; + eatBytes(valueu32.nextIndex); + dump([_value], "u32 value"); + args.push(t.numberLiteralFromRaw(_value)); + } + + if (instruction.object === "i64") { + var value64 = read64(); + var _value2 = value64.value; + eatBytes(value64.nextIndex); + dump([Number(_value2.toString())], "i64 value"); + var high = _value2.high, + low = _value2.low; + var _node = { + type: "LongNumberLiteral", + value: { + high: high, + low: low + } + }; + args.push(_node); + } + + if (instruction.object === "u64") { + var valueu64 = readU64(); + var _value3 = valueu64.value; + eatBytes(valueu64.nextIndex); + dump([Number(_value3.toString())], "u64 value"); + var _high = _value3.high, + _low = _value3.low; + var _node2 = { + type: "LongNumberLiteral", + value: { + high: _high, + low: _low + } + }; + args.push(_node2); + } + + if (instruction.object === "f32") { + var valuef32 = readF32(); + var _value4 = valuef32.value; + eatBytes(valuef32.nextIndex); + dump([_value4], "f32 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4))); + } + + if (instruction.object === "f64") { + var valuef64 = readF64(); + var _value5 = valuef64.value; + eatBytes(valuef64.nextIndex); + dump([_value5], "f64 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5))); + } + } else { + for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) { + var u32 = readU32(); + eatBytes(u32.nextIndex); + dump([u32.value], "argument " + _i3); + args.push(t.numberLiteralFromRaw(u32.value)); + } + } + + if (instructionAlreadyCreated === false) { + if (typeof instruction.object === "string") { + var _node3 = function () { + var endLoc = getPosition(); + return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6); + }(); + + code.push(_node3); + } else { + var _node4 = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); + }(); + + code.push(_node4); + } + } + } + } // https://webassembly.github.io/spec/core/binary/types.html#limits + + + function parseLimits() { + var limitType = readByte(); + eatBytes(1); + dump([limitType], "limit type"); + var min, max; + + if (limitType === 0x01 || limitType === 0x03 // shared limits + ) { + var u32min = readU32(); + min = parseInt(u32min.value); + eatBytes(u32min.nextIndex); + dump([min], "min"); + var u32max = readU32(); + max = parseInt(u32max.value); + eatBytes(u32max.nextIndex); + dump([max], "max"); + } + + if (limitType === 0x00) { + var _u32min = readU32(); + + min = parseInt(_u32min.value); + eatBytes(_u32min.nextIndex); + dump([min], "min"); + } + + return t.limit(min, max); + } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype + + + function parseTableType(index) { + var name = t.withRaw(t.identifier(getUniqueName("table")), String(index)); + var elementTypeByte = readByte(); + eatBytes(1); + dump([elementTypeByte], "element type"); + var elementType = _helperWasmBytecode.default.tableTypes[elementTypeByte]; + + if (typeof elementType === "undefined") { + throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType)); + } + + var limits = parseLimits(); + return t.table(elementType, limits, name); + } // https://webassembly.github.io/spec/binary/types.html#global-types + + + function parseGlobalType() { + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + dump([valtypeByte], type); + + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte)); + } + + var globalTypeByte = readByte(); + eatBytes(1); + var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte]; + dump([globalTypeByte], "global type (".concat(globalType, ")")); + + if (typeof globalType === "undefined") { + throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte)); + } + + return t.globalType(type, globalType); + } // function parseNameModule() { + // const lenu32 = readVaruint32(); + // eatBytes(lenu32.nextIndex); + // console.log("len", lenu32); + // const strlen = lenu32.value; + // dump([strlen], "string length"); + // const bytes = readBytes(strlen); + // eatBytes(strlen); + // const value = utf8.decode(bytes); + // return [t.moduleNameMetadata(value)]; + // } + // this section contains an array of function names and indices + + + function parseNameSectionFunctions() { + var functionNames = []; + var numberOfFunctionsu32 = readU32(); + var numbeOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); + + for (var i = 0; i < numbeOfFunctions; i++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + functionNames.push(t.functionNameMetadata(name.value, index)); + } + + return functionNames; + } + + function parseNameSectionLocals() { + var localNames = []; + var numbeOfFunctionsu32 = readU32(); + var numbeOfFunctions = numbeOfFunctionsu32.value; + eatBytes(numbeOfFunctionsu32.nextIndex); + + for (var i = 0; i < numbeOfFunctions; i++) { + var functionIndexu32 = readU32(); + var functionIndex = functionIndexu32.value; + eatBytes(functionIndexu32.nextIndex); + var numLocalsu32 = readU32(); + var numLocals = numLocalsu32.value; + eatBytes(numLocalsu32.nextIndex); + + for (var _i4 = 0; _i4 < numLocals; _i4++) { + var localIndexu32 = readU32(); + var localIndex = localIndexu32.value; + eatBytes(localIndexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex)); + } + } + + return localNames; + } // this is a custom section used for name resolution + // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section + + + function parseNameSection(remainingBytes) { + var nameMetadata = []; + var initialOffset = offset; + + while (offset - initialOffset < remainingBytes) { + // name_type + var sectionTypeByte = readVaruint7(); + eatBytes(sectionTypeByte.nextIndex); // name_payload_len + + var subSectionSizeInBytesu32 = readVaruint32(); + eatBytes(subSectionSizeInBytesu32.nextIndex); + + switch (sectionTypeByte.value) { + // case 0: { + // TODO(sven): re-enable that + // Current status: it seems that when we decode the module's name + // no name_payload_len is used. + // + // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section + // + // nameMetadata.push(...parseNameModule()); + // break; + // } + case 1: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions())); + break; + } + + case 2: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals())); + break; + } + + default: + { + // skip unknown subsection + eatBytes(subSectionSizeInBytesu32.value); + } + } + } + + return nameMetadata; + } // this is a custom section used for information about the producers + // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md + + + function parseProducersSection() { + var metadata = t.producersSectionMetadata([]); // field_count + + var sectionTypeByte = readVaruint32(); + eatBytes(sectionTypeByte.nextIndex); + dump([sectionTypeByte.value], "num of producers"); + var fields = { + language: [], + "processed-by": [], + sdk: [] + }; // fields + + for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) { + // field_name + var fieldName = readUTF8String(); + eatBytes(fieldName.nextIndex); // field_value_count + + var valueCount = readVaruint32(); + eatBytes(valueCount.nextIndex); // field_values + + for (var producerI = 0; producerI < valueCount.value; producerI++) { + var producerName = readUTF8String(); + eatBytes(producerName.nextIndex); + var producerVersion = readUTF8String(); + eatBytes(producerVersion.nextIndex); + fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value)); + } + + metadata.producers.push(fields[fieldName.value]); + } + + return metadata; + } + + function parseGlobalSection(numberOfGlobals) { + var globals = []; + dump([numberOfGlobals], "num globals"); + + for (var i = 0; i < numberOfGlobals; i++) { + var _startLoc11 = getPosition(); + + var globalType = parseGlobalType(); + /** + * Global expressions + */ + + var init = []; + parseInstructionBlock(init); + + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.global(globalType, init), endLoc, _startLoc11); + }(); + + globals.push(node); + state.globalsInModule.push(node); + } + + return globals; + } + + function parseElemSection(numberOfElements) { + var elems = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var _startLoc12 = getPosition(); + + var tableindexu32 = readU32(); + var tableindex = tableindexu32.value; + eatBytes(tableindexu32.nextIndex); + dump([tableindex], "table index"); + /** + * Parse instructions + */ + + var instr = []; + parseInstructionBlock(instr); + /** + * Parse ( vector function index ) * + */ + + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + var indexValues = []; + + for (var _i5 = 0; _i5 < indices; _i5++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); + indexValues.push(t.indexLiteral(index)); + } + + var elemNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); + }(); + + elems.push(elemNode); + } + + return elems; + } // https://webassembly.github.io/spec/core/binary/types.html#memory-types + + + function parseMemoryType(i) { + var limits = parseLimits(); + return t.memory(limits, t.indexLiteral(i)); + } // https://webassembly.github.io/spec/binary/modules.html#table-section + + + function parseTableSection(numberOfElements) { + var tables = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var tablesNode = parseTableType(i); + state.tablesInModule.push(tablesNode); + tables.push(tablesNode); + } + + return tables; + } // https://webassembly.github.io/spec/binary/modules.html#memory-section + + + function parseMemorySection(numberOfElements) { + var memories = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var memoryNode = parseMemoryType(i); + state.memoriesInModule.push(memoryNode); + memories.push(memoryNode); + } + + return memories; + } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec + + + function parseStartSection() { + var startLoc = getPosition(); + var u32 = readU32(); + var startFuncIndex = u32.value; + eatBytes(u32.nextIndex); + dump([startFuncIndex], "index"); + return function () { + var endLoc = getPosition(); + return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc); + }(); + } // https://webassembly.github.io/spec/binary/modules.html#data-section + + + function parseDataSection(numberOfElements) { + var dataEntries = []; + dump([numberOfElements], "num elements"); + + for (var i = 0; i < numberOfElements; i++) { + var memoryIndexu32 = readU32(); + var memoryIndex = memoryIndexu32.value; + eatBytes(memoryIndexu32.nextIndex); + dump([memoryIndex], "memory index"); + var instrs = []; + parseInstructionBlock(instrs); + var hasExtraInstrs = instrs.filter(function (i) { + return i.id !== "end"; + }).length !== 1; + + if (hasExtraInstrs) { + throw new _helperApiError.CompileError("data section offset must be a single instruction"); + } + + var bytes = parseVec(function (b) { + return b; + }); + dump([], "init"); + dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); + } + + return dataEntries; + } // https://webassembly.github.io/spec/binary/modules.html#binary-section + + + function parseSection(sectionIndex) { + var sectionId = readByte(); + eatBytes(1); + + if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode.default.sections.custom) { + sectionIndex = sectionId + 1; + } else { + if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); + } + + var nextSectionIndex = sectionIndex; + var startOffset = offset; + var startLoc = getPosition(); + var u32 = readU32(); + var sectionSizeInBytes = u32.value; + eatBytes(u32.nextIndex); + + var sectionSizeInBytesNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); + }(); + + switch (sectionId) { + case _helperWasmBytecode.default.sections.type: + { + dumpSep("section Type"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc13 = getPosition(); + + var _u = readU32(); + + var numberOfTypes = _u.value; + eatBytes(_u.nextIndex); + + var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13); + }()); + + var _nodes = parseTypeSection(numberOfTypes); + + return { + nodes: _nodes, + metadata: _metadata, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.table: + { + dumpSep("section Table"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc14 = getPosition(); + + var _u2 = readU32(); + + var numberOfTable = _u2.value; + eatBytes(_u2.nextIndex); + dump([numberOfTable], "num tables"); + + var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); + }()); + + var _nodes2 = parseTableSection(numberOfTable); + + return { + nodes: _nodes2, + metadata: _metadata2, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.import: + { + dumpSep("section Import"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc15 = getPosition(); + + var numberOfImportsu32 = readU32(); + var numberOfImports = numberOfImportsu32.value; + eatBytes(numberOfImportsu32.nextIndex); + dump([numberOfImports], "number of imports"); + + var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); + }()); + + var _nodes3 = parseImportSection(numberOfImports); + + return { + nodes: _nodes3, + metadata: _metadata3, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.func: + { + dumpSep("section Function"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc16 = getPosition(); + + var numberOfFunctionsu32 = readU32(); + var numberOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); + + var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); + }()); + + parseFuncSection(numberOfFunctions); + var _nodes4 = []; + return { + nodes: _nodes4, + metadata: _metadata4, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.export: + { + dumpSep("section Export"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc17 = getPosition(); + + var _u3 = readU32(); + + var numberOfExport = _u3.value; + eatBytes(_u3.nextIndex); + + var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17); + }()); + + parseExportSection(numberOfExport); + var _nodes5 = []; + return { + nodes: _nodes5, + metadata: _metadata5, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.code: + { + dumpSep("section Code"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc18 = getPosition(); + + var _u4 = readU32(); + + var numberOfFuncs = _u4.value; + eatBytes(_u4.nextIndex); + + var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); + }()); + + if (opts.ignoreCodeSection === true) { + var remainingBytes = sectionSizeInBytes - _u4.nextIndex; + eatBytes(remainingBytes); // eat the entire section + } else { + parseCodeSection(numberOfFuncs); + } + + var _nodes6 = []; + return { + nodes: _nodes6, + metadata: _metadata6, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.start: + { + dumpSep("section Start"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); + + var _nodes7 = [parseStartSection()]; + return { + nodes: _nodes7, + metadata: _metadata7, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.element: + { + dumpSep("section Element"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc19 = getPosition(); + + var numberOfElementsu32 = readU32(); + var numberOfElements = numberOfElementsu32.value; + eatBytes(numberOfElementsu32.nextIndex); + + var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); + }()); + + var _nodes8 = parseElemSection(numberOfElements); + + return { + nodes: _nodes8, + metadata: _metadata8, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.global: + { + dumpSep("section Global"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc20 = getPosition(); + + var numberOfGlobalsu32 = readU32(); + var numberOfGlobals = numberOfGlobalsu32.value; + eatBytes(numberOfGlobalsu32.nextIndex); + + var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); + }()); + + var _nodes9 = parseGlobalSection(numberOfGlobals); + + return { + nodes: _nodes9, + metadata: _metadata9, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.memory: + { + dumpSep("section Memory"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _startLoc21 = getPosition(); + + var _numberOfElementsu = readU32(); + + var _numberOfElements = _numberOfElementsu.value; + eatBytes(_numberOfElementsu.nextIndex); + + var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); + }()); + + var _nodes10 = parseMemorySection(_numberOfElements); + + return { + nodes: _nodes10, + metadata: _metadata10, + nextSectionIndex: nextSectionIndex + }; + } + + case _helperWasmBytecode.default.sections.data: + { + dumpSep("section Data"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + + var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode); + + var _startLoc22 = getPosition(); + + var _numberOfElementsu2 = readU32(); + + var _numberOfElements2 = _numberOfElementsu2.value; + eatBytes(_numberOfElementsu2.nextIndex); + + _metadata11.vectorOfSize = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22); + }(); + + if (opts.ignoreDataSection === true) { + var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex; + + eatBytes(_remainingBytes); // eat the entire section + + dumpSep("ignore data (" + sectionSizeInBytes + " bytes)"); + return { + nodes: [], + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } else { + var _nodes11 = parseDataSection(_numberOfElements2); + + return { + nodes: _nodes11, + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } + } + + case _helperWasmBytecode.default.sections.custom: + { + dumpSep("section Custom"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + var _metadata12 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)]; + var sectionName = readUTF8String(); + eatBytes(sectionName.nextIndex); + dump([], "section name (".concat(sectionName.value, ")")); + + var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex; + + if (sectionName.value === "name") { + var initialOffset = offset; + + try { + _metadata12.push.apply(_metadata12, _toConsumableArray(parseNameSection(_remainingBytes2))); + } catch (e) { + console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (initialOffset + _remainingBytes2)); + } + } else if (sectionName.value === "producers") { + var _initialOffset = offset; + + try { + _metadata12.push(parseProducersSection()); + } catch (e) { + console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (_initialOffset + _remainingBytes2)); + } + } else { + // We don't parse the custom section + eatBytes(_remainingBytes2); + dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)"); + } + + return { + nodes: [], + metadata: _metadata12, + nextSectionIndex: nextSectionIndex + }; + } + } + + throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); + } + + parseModuleHeader(); + parseVersion(); + var moduleFields = []; + var sectionIndex = 0; + var moduleMetadata = { + sections: [], + functionNames: [], + localNames: [], + producers: [] + }; + /** + * All the generate declaration are going to be stored in our state + */ + + while (offset < buf.length) { + var _parseSection = parseSection(sectionIndex), + _nodes12 = _parseSection.nodes, + _metadata13 = _parseSection.metadata, + nextSectionIndex = _parseSection.nextSectionIndex; + + moduleFields.push.apply(moduleFields, _toConsumableArray(_nodes12)); + var metadataArray = Array.isArray(_metadata13) ? _metadata13 : [_metadata13]; + metadataArray.forEach(function (metadataItem) { + if (metadataItem.type === "FunctionNameMetadata") { + moduleMetadata.functionNames.push(metadataItem); + } else if (metadataItem.type === "LocalNameMetadata") { + moduleMetadata.localNames.push(metadataItem); + } else if (metadataItem.type === "ProducersSectionMetadata") { + moduleMetadata.producers.push(metadataItem); + } else { + moduleMetadata.sections.push(metadataItem); + } + }); // Ignore custom section + + if (nextSectionIndex) { + sectionIndex = nextSectionIndex; + } + } + /** + * Transform the state into AST nodes + */ + + + var funcIndex = 0; + state.functionsInModule.forEach(function (func) { + var params = func.signature.params; + var result = func.signature.result; + var body = []; // External functions doesn't provide any code, can skip it here + + if (func.isExternal === true) { + return; + } + + var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex]; + + if (opts.ignoreCodeSection === false) { + if (typeof decodedElementInCodeSection === "undefined") { + throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found"); + } + + body = decodedElementInCodeSection.code; + } + + funcIndex++; + var funcNode = t.func(func.id, t.signature(params, result), body); + + if (func.isExternal === true) { + funcNode.isExternal = func.isExternal; + } // Add function position in the binary if possible + + + if (opts.ignoreCodeSection === false) { + var _startLoc23 = decodedElementInCodeSection.startLoc, + endLoc = decodedElementInCodeSection.endLoc, + bodySize = decodedElementInCodeSection.bodySize; + funcNode = t.withLoc(funcNode, endLoc, _startLoc23); + funcNode.metadata = { + bodySize: bodySize + }; + } + + moduleFields.push(funcNode); + }); + state.elementsInExportSection.forEach(function (moduleExport) { + /** + * If the export has no id, we won't be able to call it from the outside + * so we can omit it + */ + if (moduleExport.id != null) { + moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc)); + } + }); + dumpSep("end of program"); + var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers)); + return t.program([module]); +} + +/***/ }), + +/***/ 81582: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; + +var decoder = _interopRequireWildcard(__webpack_require__(70525)); + +var t = _interopRequireWildcard(__webpack_require__(77325)); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +/** + * TODO(sven): I added initial props, but we should rather fix + * https://github.com/xtuc/webassemblyjs/issues/405 + */ +var defaultDecoderOpts = { + dump: false, + ignoreCodeSection: false, + ignoreDataSection: false, + ignoreCustomNameSection: false +}; // traverses the AST, locating function name metadata, which is then +// used to update index-based identifiers with function names + +function restoreFunctionNames(ast) { + var functionNames = []; + t.traverse(ast, { + FunctionNameMetadata: function FunctionNameMetadata(_ref) { + var node = _ref.node; + functionNames.push({ + name: node.value, + index: node.index + }); + } + }); + + if (functionNames.length === 0) { + return; + } + + t.traverse(ast, { + Func: function (_Func) { + function Func(_x) { + return _Func.apply(this, arguments); + } + + Func.toString = function () { + return _Func.toString(); + }; + + return Func; + }(function (_ref2) { + var node = _ref2.node; + // $FlowIgnore + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + var oldValue = nodeName.value; + nodeName.value = functionName.name; + nodeName.numeric = oldValue; // $FlowIgnore + + delete nodeName.raw; + } + }), + // Also update the reference in the export + ModuleExport: function (_ModuleExport) { + function ModuleExport(_x2) { + return _ModuleExport.apply(this, arguments); + } + + ModuleExport.toString = function () { + return _ModuleExport.toString(); + }; + + return ModuleExport; + }(function (_ref3) { + var node = _ref3.node; + + if (node.descr.exportType === "Func") { + // $FlowIgnore + var nodeName = node.descr.id; + var index = nodeName.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + node.descr.id = t.identifier(functionName.name); + } + } + }), + ModuleImport: function (_ModuleImport) { + function ModuleImport(_x3) { + return _ModuleImport.apply(this, arguments); + } + + ModuleImport.toString = function () { + return _ModuleImport.toString(); + }; + + return ModuleImport; + }(function (_ref4) { + var node = _ref4.node; + + if (node.descr.type === "FuncImportDescr") { + // $FlowIgnore + var indexBasedFunctionName = node.descr.id; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + // $FlowIgnore + node.descr.id = t.identifier(functionName.name); + } + } + }), + CallInstruction: function (_CallInstruction) { + function CallInstruction(_x4) { + return _CallInstruction.apply(this, arguments); + } + + CallInstruction.toString = function () { + return _CallInstruction.toString(); + }; + + return CallInstruction; + }(function (nodePath) { + var node = nodePath.node; + var index = node.index.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + + if (functionName) { + var oldValue = node.index; + node.index = t.identifier(functionName.name); + node.numeric = oldValue; // $FlowIgnore + + delete node.raw; + } + }) + }); +} + +function restoreLocalNames(ast) { + var localNames = []; + t.traverse(ast, { + LocalNameMetadata: function LocalNameMetadata(_ref5) { + var node = _ref5.node; + localNames.push({ + name: node.value, + localIndex: node.localIndex, + functionIndex: node.functionIndex + }); + } + }); + + if (localNames.length === 0) { + return; + } + + t.traverse(ast, { + Func: function (_Func2) { + function Func(_x5) { + return _Func2.apply(this, arguments); + } + + Func.toString = function () { + return _Func2.toString(); + }; + + return Func; + }(function (_ref6) { + var node = _ref6.node; + var signature = node.signature; + + if (signature.type !== "Signature") { + return; + } // $FlowIgnore + + + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var functionIndex = Number(indexBasedFunctionName.replace("func_", "")); + signature.params.forEach(function (param, paramIndex) { + var paramName = localNames.find(function (f) { + return f.localIndex === paramIndex && f.functionIndex === functionIndex; + }); + + if (paramName && paramName.name !== "") { + param.id = paramName.name; + } + }); + }) + }); +} + +function restoreModuleName(ast) { + t.traverse(ast, { + ModuleNameMetadata: function (_ModuleNameMetadata) { + function ModuleNameMetadata(_x6) { + return _ModuleNameMetadata.apply(this, arguments); + } + + ModuleNameMetadata.toString = function () { + return _ModuleNameMetadata.toString(); + }; + + return ModuleNameMetadata; + }(function (moduleNameMetadataPath) { + // update module + t.traverse(ast, { + Module: function (_Module) { + function Module(_x7) { + return _Module.apply(this, arguments); + } + + Module.toString = function () { + return _Module.toString(); + }; + + return Module; + }(function (_ref7) { + var node = _ref7.node; + var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser + + if (name === "") { + name = null; + } + + node.id = name; + }) + }); + }) + }); +} + +function decode(buf, customOpts) { + var opts = Object.assign({}, defaultDecoderOpts, customOpts); + var ast = decoder.decode(buf, opts); + + if (opts.ignoreCustomNameSection === false) { + restoreFunctionNames(ast); + restoreLocalNames(ast); + restoreModuleName(ast); + } + + return ast; +} + +/***/ }), + +/***/ 59830: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parse = parse; + +var _helperCodeFrame = __webpack_require__(87360); + +var t = _interopRequireWildcard(__webpack_require__(77325)); + +var _numberLiterals = __webpack_require__(48709); + +var _stringLiterals = __webpack_require__(62139); + +var _tokenizer = __webpack_require__(63124); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function hasPlugin(name) { + if (name !== "wast") throw new Error("unknow plugin"); + return true; +} + +function isKeyword(token, id) { + return token.type === _tokenizer.tokens.keyword && token.value === id; +} + +function tokenToString(token) { + if (token.type === "keyword") { + return "keyword (".concat(token.value, ")"); + } + + return token.type; +} + +function identifierFromToken(token) { + var _token$loc = token.loc, + end = _token$loc.end, + start = _token$loc.start; + return t.withLoc(t.identifier(token.value), end, start); +} + +function parse(tokensList, source) { + var current = 0; + var getUniqueName = t.getUniqueNameGenerator(); + var state = { + registredExportedElements: [] + }; // But this time we're going to use recursion instead of a `while` loop. So we + // define a `walk` function. + + function walk() { + var token = tokensList[current]; + + function eatToken() { + token = tokensList[++current]; + } + + function getEndLoc() { + var currentToken = token; + + if (typeof currentToken === "undefined") { + var lastToken = tokensList[tokensList.length - 1]; + currentToken = lastToken; + } + + return currentToken.loc.end; + } + + function getStartLoc() { + return token.loc.start; + } + + function eatTokenOfType(type) { + if (token.type !== type) { + throw new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "Assertion error: expected token of type " + type + ", given " + tokenToString(token)); + } + + eatToken(); + } + + function parseExportIndex(token) { + if (token.type === _tokenizer.tokens.identifier) { + var index = identifierFromToken(token); + eatToken(); + return index; + } else if (token.type === _tokenizer.tokens.number) { + var _index = t.numberLiteralFromRaw(token.value); + + eatToken(); + return _index; + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "unknown export index" + ", given " + tokenToString(token)); + }(); + } + } + + function lookaheadAndCheck() { + var len = arguments.length; + + for (var i = 0; i < len; i++) { + var tokenAhead = tokensList[current + i]; + var expectedToken = i < 0 || arguments.length <= i ? undefined : arguments[i]; + + if (tokenAhead.type === "keyword") { + if (isKeyword(tokenAhead, expectedToken) === false) { + return false; + } + } else if (expectedToken !== tokenAhead.type) { + return false; + } + } + + return true; + } // TODO(sven): there is probably a better way to do this + // can refactor it if it get out of hands + + + function maybeIgnoreComment() { + if (typeof token === "undefined") { + // Ignore + return; + } + + while (token.type === _tokenizer.tokens.comment) { + eatToken(); + + if (typeof token === "undefined") { + // Hit the end + break; + } + } + } + /** + * Parses a memory instruction + * + * WAST: + * + * memory: ( memory ? ) + * ( memory ? ( export ) <...> ) + * ( memory ? ( import ) ) + * ( memory ? ( export )* ( data * ) + * memory_sig: ? + * + */ + + + function parseMemory() { + var id = t.identifier(getUniqueName("memory")); + var limits = t.limit(0); + + if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) { + id = t.identifier(token.value); + eatToken(); + } else { + id = t.withRaw(id, ""); // preserve anonymous + } + /** + * Maybe data + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.data)) { + eatToken(); // ( + + eatToken(); // data + // TODO(sven): do something with the data collected here + + var stringInitializer = token.value; + eatTokenOfType(_tokenizer.tokens.string); // Update limits accordingly + + limits = t.limit(stringInitializer.length); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * Maybe export + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token)); + }(); + } + + var _name = token.value; + eatToken(); + state.registredExportedElements.push({ + exportType: "Memory", + name: _name, + id: id + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * Memory signature + */ + + + if (token.type === _tokenizer.tokens.number) { + limits = t.limit((0, _numberLiterals.parse32I)(token.value)); + eatToken(); + + if (token.type === _tokenizer.tokens.number) { + limits.max = (0, _numberLiterals.parse32I)(token.value); + eatToken(); + } + } + + return t.memory(limits, id); + } + /** + * Parses a data section + * https://webassembly.github.io/spec/core/text/modules.html#data-segments + * + * WAST: + * + * data: ( data ? ) + */ + + + function parseData() { + // optional memory index + var memidx = 0; + + if (token.type === _tokenizer.tokens.number) { + memidx = token.value; + eatTokenOfType(_tokenizer.tokens.number); // . + } + + eatTokenOfType(_tokenizer.tokens.openParen); + var offset; + + if (token.type === _tokenizer.tokens.valtype) { + eatTokenOfType(_tokenizer.tokens.valtype); // i32 + + eatTokenOfType(_tokenizer.tokens.dot); // . + + if (token.value !== "const") { + throw new Error("constant expression required"); + } + + eatTokenOfType(_tokenizer.tokens.name); // const + + var numberLiteral = t.numberLiteralFromRaw(token.value, "i32"); + offset = t.objectInstruction("const", "i32", [numberLiteral]); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + eatTokenOfType(_tokenizer.tokens.name); // get_global + + var _numberLiteral = t.numberLiteralFromRaw(token.value, "i32"); + + offset = t.instruction("get_global", [_numberLiteral]); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + var byteArray = (0, _stringLiterals.parseString)(token.value); + eatToken(); // "string" + + return t.data(t.memIndexLiteral(memidx), offset, t.byteArray(byteArray)); + } + /** + * Parses a table instruction + * + * WAST: + * + * table: ( table ? ) + * ( table ? ( export ) <...> ) + * ( table ? ( import ) ) + * ( table ? ( export )* ( elem * ) ) + * + * table_type: ? + * elem_type: anyfunc + * + * elem: ( elem ? (offset * ) * ) + * ( elem ? * ) + */ + + + function parseTable() { + var name = t.identifier(getUniqueName("table")); + var limit = t.limit(0); + var elemIndices = []; + var elemType = "anyfunc"; + + if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) { + name = identifierFromToken(token); + eatToken(); + } else { + name = t.withRaw(name, ""); // preserve anonymous + } + + while (token.type !== _tokenizer.tokens.closeParen) { + /** + * Maybe export + */ + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.elem)) { + eatToken(); // ( + + eatToken(); // elem + + while (token.type === _tokenizer.tokens.identifier) { + elemIndices.push(t.identifier(token.value)); + eatToken(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token)); + }(); + } + + var exportName = token.value; + eatToken(); + state.registredExportedElements.push({ + exportType: "Table", + name: exportName, + id: name + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (isKeyword(token, _tokenizer.keywords.anyfunc)) { + // It's the default value, we can ignore it + eatToken(); // anyfunc + } else if (token.type === _tokenizer.tokens.number) { + /** + * Table type + */ + var min = parseInt(token.value); + eatToken(); + + if (token.type === _tokenizer.tokens.number) { + var max = parseInt(token.value); + eatToken(); + limit = t.limit(min, max); + } else { + limit = t.limit(min); + } + + eatToken(); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token" + ", given " + tokenToString(token)); + }(); + } + } + + if (elemIndices.length > 0) { + return t.table(elemType, limit, name, elemIndices); + } else { + return t.table(elemType, limit, name); + } + } + /** + * Parses an import statement + * + * WAST: + * + * import: ( import ) + * imkind: ( func ? ) + * ( global ? ) + * ( table ? ) + * ( memory ? ) + * + * global_sig: | ( mut ) + */ + + + function parseImport() { + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected a string, " + token.type + " given."); + } + + var moduleName = token.value; + eatToken(); + + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected a string, " + token.type + " given."); + } + + var name = token.value; + eatToken(); + eatTokenOfType(_tokenizer.tokens.openParen); + var descr; + + if (isKeyword(token, _tokenizer.keywords.func)) { + eatToken(); // keyword + + var fnParams = []; + var fnResult = []; + var typeRef; + var fnName = t.identifier(getUniqueName("func")); + + if (token.type === _tokenizer.tokens.identifier) { + fnName = identifierFromToken(token); + eatToken(); + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.type) === true) { + eatToken(); + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.keywords.param) === true) { + eatToken(); + fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam())); + } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult())); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in import of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (typeof fnName === "undefined") { + throw new Error("Imported function must have a name"); + } + + descr = t.funcImportDescr(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult)); + } else if (isKeyword(token, _tokenizer.keywords.global)) { + eatToken(); // keyword + + if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + eatTokenOfType(_tokenizer.tokens.keyword); // mut keyword + + var valtype = token.value; + eatToken(); + descr = t.globalType(valtype, "var"); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + var _valtype = token.value; + eatTokenOfType(_tokenizer.tokens.valtype); + descr = t.globalType(_valtype, "const"); + } + } else if (isKeyword(token, _tokenizer.keywords.memory) === true) { + eatToken(); // Keyword + + descr = parseMemory(); + } else if (isKeyword(token, _tokenizer.keywords.table) === true) { + eatToken(); // Keyword + + descr = parseTable(); + } else { + throw new Error("Unsupported import type: " + tokenToString(token)); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.moduleImport(moduleName, name, descr); + } + /** + * Parses a block instruction + * + * WAST: + * + * expr: ( block ? * ) + * instr: block ? * end ? + * block_sig : ( result * )* + * + */ + + + function parseBlock() { + var label = t.identifier(getUniqueName("block")); + var blockResult = null; + var instr = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatToken(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + instr.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in block body of type" + ", given " + tokenToString(token)); + }(); + } + + maybeIgnoreComment(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.blockInstruction(label, instr, blockResult); + } + /** + * Parses a if instruction + * + * WAST: + * + * expr: + * ( if ? ( then * ) ( else * )? ) + * ( if ? + ( then * ) ( else * )? ) + * + * instr: + * if ? * end ? + * if ? * else ? * end ? + * + * block_sig : ( result * )* + * + */ + + + function parseIf() { + var blockResult = null; + var label = t.identifier(getUniqueName("if")); + var testInstrs = []; + var consequent = []; + var alternate = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + /** + * Block signature + */ + + if (isKeyword(token, _tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatTokenOfType(_tokenizer.tokens.valtype); + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Then + */ + + + if (isKeyword(token, _tokenizer.keywords.then) === true) { + eatToken(); // then + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + consequent.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in consequent body of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Alternate + */ + + + if (isKeyword(token, _tokenizer.keywords.else)) { + eatToken(); // else + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + alternate.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in alternate body of type" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + /** + * Test instruction + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + testInstrs.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + continue; + } + + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in if body" + ", given " + tokenToString(token)); + }(); + } + + return t.ifInstruction(label, testInstrs, blockResult, consequent, alternate); + } + /** + * Parses a loop instruction + * + * WAT: + * + * blockinstr :: 'loop' I:label rt:resulttype (in:instr*) 'end' id? + * + * WAST: + * + * instr :: loop ? * end ? + * expr :: ( loop ? * ) + * block_sig :: ( result * )* + * + */ + + + function parseLoop() { + var label = t.identifier(getUniqueName("loop")); + var blockResult; + var instr = []; + + if (token.type === _tokenizer.tokens.identifier) { + label = identifierFromToken(token); + eatToken(); + } else { + label = t.withRaw(label, ""); // preserve anonymous + } + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + blockResult = token.value; + eatToken(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + instr.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in loop body" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.loopInstruction(label, blockResult, instr); + } + + function parseCallIndirect() { + var typeRef; + var params = []; + var results = []; + var instrs = []; + + while (token.type !== _tokenizer.tokens.closeParen) { + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.type)) { + eatToken(); // ( + + eatToken(); // type + + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) { + eatToken(); // ( + + eatToken(); // param + + /** + * Params can be empty: + * (params)` + */ + + if (token.type !== _tokenizer.tokens.closeParen) { + params.push.apply(params, _toConsumableArray(parseFuncParam())); + } + } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) { + eatToken(); // ( + + eatToken(); // result + + /** + * Results can be empty: + * (result)` + */ + + if (token.type !== _tokenizer.tokens.closeParen) { + results.push.apply(results, _toConsumableArray(parseFuncResult())); + } + } else { + eatTokenOfType(_tokenizer.tokens.openParen); + instrs.push(parseFuncInstr()); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.callIndirectInstruction(typeRef !== undefined ? typeRef : t.signature(params, results), instrs); + } + /** + * Parses an export instruction + * + * WAT: + * + * export: ( export ) + * exkind: ( func ) + * ( global ) + * ( table ) + * ( memory ) + * var: | + * + */ + + + function parseExport() { + if (token.type !== _tokenizer.tokens.string) { + throw new Error("Expected string after export, got: " + token.type); + } + + var name = token.value; + eatToken(); + var moduleExportDescr = parseModuleExportDescr(); + return t.moduleExport(name, moduleExportDescr); + } + + function parseModuleExportDescr() { + var startLoc = getStartLoc(); + var type = ""; + var index; + eatTokenOfType(_tokenizer.tokens.openParen); + + while (token.type !== _tokenizer.tokens.closeParen) { + if (isKeyword(token, _tokenizer.keywords.func)) { + type = "Func"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.table)) { + type = "Table"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.global)) { + type = "Global"; + eatToken(); + index = parseExportIndex(token); + } else if (isKeyword(token, _tokenizer.keywords.memory)) { + type = "Memory"; + eatToken(); + index = parseExportIndex(token); + } + + eatToken(); + } + + if (type === "") { + throw new Error("Unknown export type"); + } + + if (index === undefined) { + throw new Error("Exported function must have a name"); + } + + var node = t.moduleExportDescr(type, index); + var endLoc = getEndLoc(); + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(node, endLoc, startLoc); + } + + function parseModule() { + var name = null; + var isBinary = false; + var isQuote = false; + var moduleFields = []; + + if (token.type === _tokenizer.tokens.identifier) { + name = token.value; + eatToken(); + } + + if (hasPlugin("wast") && token.type === _tokenizer.tokens.name && token.value === "binary") { + eatToken(); + isBinary = true; + } + + if (hasPlugin("wast") && token.type === _tokenizer.tokens.name && token.value === "quote") { + eatToken(); + isQuote = true; + } + + if (isBinary === true) { + var blob = []; + + while (token.type === _tokenizer.tokens.string) { + blob.push(token.value); + eatToken(); + maybeIgnoreComment(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.binaryModule(name, blob); + } + + if (isQuote === true) { + var string = []; + + while (token.type === _tokenizer.tokens.string) { + string.push(token.value); + eatToken(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.quoteModule(name, string); + } + + while (token.type !== _tokenizer.tokens.closeParen) { + moduleFields.push(walk()); + + if (state.registredExportedElements.length > 0) { + state.registredExportedElements.forEach(function (decl) { + moduleFields.push(t.moduleExport(decl.name, t.moduleExportDescr(decl.exportType, decl.id))); + }); + state.registredExportedElements = []; + } + + token = tokensList[current]; + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.module(name, moduleFields); + } + /** + * Parses the arguments of an instruction + */ + + + function parseFuncInstrArguments(signature) { + var args = []; + var namedArgs = {}; + var signaturePtr = 0; + + while (token.type === _tokenizer.tokens.name || isKeyword(token, _tokenizer.keywords.offset)) { + var key = token.value; + eatToken(); + eatTokenOfType(_tokenizer.tokens.equal); + var value = void 0; + + if (token.type === _tokenizer.tokens.number) { + value = t.numberLiteralFromRaw(token.value); + } else { + throw new Error("Unexpected type for argument: " + token.type); + } + + namedArgs[key] = value; + eatToken(); + } // $FlowIgnore + + + var signatureLength = signature.vector ? Infinity : signature.length; + + while (token.type !== _tokenizer.tokens.closeParen && ( // $FlowIgnore + token.type === _tokenizer.tokens.openParen || signaturePtr < signatureLength)) { + if (token.type === _tokenizer.tokens.identifier) { + args.push(t.identifier(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.valtype) { + // Handle locals + args.push(t.valtypeLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.string) { + args.push(t.stringLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + args.push( // TODO(sven): refactor the type signature handling + // https://github.com/xtuc/webassemblyjs/pull/129 is a good start + t.numberLiteralFromRaw(token.value, // $FlowIgnore + signature[signaturePtr] || "f64")); // $FlowIgnore + + if (!signature.vector) { + ++signaturePtr; + } + + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + /** + * Maybe some nested instructions + */ + eatToken(); // Instruction + + if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // $FlowIgnore + args.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in nested instruction" + ", given " + tokenToString(token)); + }(); + } + + if (token.type === _tokenizer.tokens.closeParen) { + eatToken(); + } + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in instruction argument" + ", given " + tokenToString(token)); + }(); + } + } + + return { + args: args, + namedArgs: namedArgs + }; + } + /** + * Parses an instruction + * + * WAT: + * + * instr :: plaininst + * blockinstr + * + * blockinstr :: 'block' I:label rt:resulttype (in:instr*) 'end' id? + * 'loop' I:label rt:resulttype (in:instr*) 'end' id? + * 'if' I:label rt:resulttype (in:instr*) 'else' id? (in2:intr*) 'end' id? + * + * plaininst :: 'unreachable' + * 'nop' + * 'br' l:labelidx + * 'br_if' l:labelidx + * 'br_table' l*:vec(labelidx) ln:labelidx + * 'return' + * 'call' x:funcidx + * 'call_indirect' x, I:typeuse + * + * WAST: + * + * instr: + * + * + * block ? * end ? + * loop ? * end ? + * if ? * end ? + * if ? * else ? * end ? + * + * expr: + * ( ) + * ( + ) + * ( block ? * ) + * ( loop ? * ) + * ( if ? ( then * ) ( else * )? ) + * ( if ? + ( then * ) ( else * )? ) + * + * op: + * unreachable + * nop + * br + * br_if + * br_table + + * return + * call + * call_indirect + * drop + * select + * get_local + * set_local + * tee_local + * get_global + * set_global + * .load((8|16|32)_)? ? ? + * .store(8|16|32)? ? ? + * current_memory + * grow_memory + * .const + * . + * . + * . + * . + * ./ + * + * func_type: ( type )? * * + */ + + + function parseFuncInstr() { + var startLoc = getStartLoc(); + maybeIgnoreComment(); + /** + * A simple instruction + */ + + if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + var _name2 = token.value; + var object; + eatToken(); + + if (token.type === _tokenizer.tokens.dot) { + object = _name2; + eatToken(); + + if (token.type !== _tokenizer.tokens.name) { + throw new TypeError("Unknown token: " + token.type + ", name expected"); + } + + _name2 = token.value; + eatToken(); + } + + if (token.type === _tokenizer.tokens.closeParen) { + var _endLoc = token.loc.end; + + if (typeof object === "undefined") { + return t.withLoc(t.instruction(_name2), _endLoc, startLoc); + } else { + return t.withLoc(t.objectInstruction(_name2, object, []), _endLoc, startLoc); + } + } + + var signature = t.signatureForOpcode(object || "", _name2); + + var _parseFuncInstrArgume = parseFuncInstrArguments(signature), + _args = _parseFuncInstrArgume.args, + _namedArgs = _parseFuncInstrArgume.namedArgs; + + var endLoc = token.loc.end; + + if (typeof object === "undefined") { + return t.withLoc(t.instruction(_name2, _args, _namedArgs), endLoc, startLoc); + } else { + return t.withLoc(t.objectInstruction(_name2, object, _args, _namedArgs), endLoc, startLoc); + } + } else if (isKeyword(token, _tokenizer.keywords.loop)) { + /** + * Else a instruction with a keyword (loop or block) + */ + eatToken(); // keyword + + return parseLoop(); + } else if (isKeyword(token, _tokenizer.keywords.block)) { + eatToken(); // keyword + + return parseBlock(); + } else if (isKeyword(token, _tokenizer.keywords.call_indirect)) { + eatToken(); // keyword + + return parseCallIndirect(); + } else if (isKeyword(token, _tokenizer.keywords.call)) { + eatToken(); // keyword + + var index; + + if (token.type === _tokenizer.tokens.identifier) { + index = identifierFromToken(token); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + index = t.indexLiteral(token.value); + eatToken(); + } + + var instrArgs = []; // Nested instruction + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + instrArgs.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (typeof index === "undefined") { + throw new Error("Missing argument in call instruciton"); + } + + if (instrArgs.length > 0) { + return t.callInstruction(index, instrArgs); + } else { + return t.callInstruction(index); + } + } else if (isKeyword(token, _tokenizer.keywords.if)) { + eatToken(); // Keyword + + return parseIf(); + } else if (isKeyword(token, _tokenizer.keywords.module) && hasPlugin("wast")) { + eatToken(); // In WAST you can have a module as an instruction's argument + // we will cast it into a instruction to not break the flow + // $FlowIgnore + + var module = parseModule(); + return module; + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected instruction in function body" + ", given " + tokenToString(token)); + }(); + } + } + /* + * Parses a function + * + * WAT: + * + * functype :: ( 'func' t1:vec(param) t2:vec(result) ) + * param :: ( 'param' id? t:valtype ) + * result :: ( 'result' t:valtype ) + * + * WAST: + * + * func :: ( func ? * * ) + * ( func ? ( export ) <...> ) + * ( func ? ( import ) ) + * func_sig :: ( type )? * * + * param :: ( param * ) | ( param ) + * result :: ( result * ) + * local :: ( local * ) | ( local ) + * + */ + + + function parseFunc() { + var fnName = t.identifier(getUniqueName("func")); + var typeRef; + var fnBody = []; + var fnParams = []; + var fnResult = []; // name + + if (token.type === _tokenizer.tokens.identifier) { + fnName = identifierFromToken(token); + eatToken(); + } else { + fnName = t.withRaw(fnName, ""); // preserve anonymous + } + + maybeIgnoreComment(); + + while (token.type === _tokenizer.tokens.openParen || token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + // Instructions without parens + if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) { + fnBody.push(parseFuncInstr()); + continue; + } + + eatToken(); + + if (lookaheadAndCheck(_tokenizer.keywords.param) === true) { + eatToken(); + fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam())); + } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) { + eatToken(); + fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult())); + } else if (lookaheadAndCheck(_tokenizer.keywords.export) === true) { + eatToken(); + parseFuncExport(fnName); + } else if (lookaheadAndCheck(_tokenizer.keywords.type) === true) { + eatToken(); + typeRef = parseTypeReference(); + } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === "keyword" // is any keyword + ) { + // Instruction + fnBody.push(parseFuncInstr()); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in func body" + ", given " + tokenToString(token)); + }(); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.func(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult), fnBody); + } + /** + * Parses shorthand export in func + * + * export :: ( export ) + */ + + + function parseFuncExport(funcId) { + if (token.type !== _tokenizer.tokens.string) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Function export expected a string" + ", given " + tokenToString(token)); + }(); + } + + var name = token.value; + eatToken(); + /** + * Func export shorthand, we trait it as a syntaxic sugar. + * A export ModuleField will be added later. + * + * We give the anonymous function a generated name and export it. + */ + + var id = t.identifier(funcId.value); + state.registredExportedElements.push({ + exportType: "Func", + name: name, + id: id + }); + } + /** + * Parses a type instruction + * + * WAST: + * + * typedef: ( type ? ( func * * ) ) + */ + + + function parseType() { + var id; + var params = []; + var result = []; + + if (token.type === _tokenizer.tokens.identifier) { + id = identifierFromToken(token); + eatToken(); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) { + eatToken(); // ( + + eatToken(); // func + + if (token.type === _tokenizer.tokens.closeParen) { + eatToken(); // function with an empty signature, we can abort here + + return t.typeInstruction(id, t.signature([], [])); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) { + eatToken(); // ( + + eatToken(); // param + + params = parseFuncParam(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) { + eatToken(); // ( + + eatToken(); // result + + result = parseFuncResult(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.typeInstruction(id, t.signature(params, result)); + } + /** + * Parses a function result + * + * WAST: + * + * result :: ( result * ) + */ + + + function parseFuncResult() { + var results = []; + + while (token.type !== _tokenizer.tokens.closeParen) { + if (token.type !== _tokenizer.tokens.valtype) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unexpected token in func result" + ", given " + tokenToString(token)); + }(); + } + + var valtype = token.value; + eatToken(); + results.push(valtype); + } + + return results; + } + /** + * Parses a type reference + * + */ + + + function parseTypeReference() { + var ref; + + if (token.type === _tokenizer.tokens.identifier) { + ref = identifierFromToken(token); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + ref = t.numberLiteralFromRaw(token.value); + eatToken(); + } + + return ref; + } + /** + * Parses a global instruction + * + * WAST: + * + * global: ( global ? * ) + * ( global ? ( export ) <...> ) + * ( global ? ( import ) ) + * + * global_sig: | ( mut ) + * + */ + + + function parseGlobal() { + var name = t.identifier(getUniqueName("global")); + var type; // Keep informations in case of a shorthand import + + var importing = null; + maybeIgnoreComment(); + + if (token.type === _tokenizer.tokens.identifier) { + name = identifierFromToken(token); + eatToken(); + } else { + name = t.withRaw(name, ""); // preserve anonymous + } + /** + * maybe export + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) { + eatToken(); // ( + + eatToken(); // export + + var exportName = token.value; + eatTokenOfType(_tokenizer.tokens.string); + state.registredExportedElements.push({ + exportType: "Global", + name: exportName, + id: name + }); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * maybe import + */ + + + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.import)) { + eatToken(); // ( + + eatToken(); // import + + var moduleName = token.value; + eatTokenOfType(_tokenizer.tokens.string); + var _name3 = token.value; + eatTokenOfType(_tokenizer.tokens.string); + importing = { + module: moduleName, + name: _name3, + descr: undefined + }; + eatTokenOfType(_tokenizer.tokens.closeParen); + } + /** + * global_sig + */ + + + if (token.type === _tokenizer.tokens.valtype) { + type = t.globalType(token.value, "const"); + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + if (isKeyword(token, _tokenizer.keywords.mut) === false) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unsupported global type, expected mut" + ", given " + tokenToString(token)); + }(); + } + + eatToken(); // mut + + type = t.globalType(token.value, "var"); + eatToken(); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + if (type === undefined) { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Could not determine global type" + ", given " + tokenToString(token)); + }(); + } + + maybeIgnoreComment(); + var init = []; + + if (importing != null) { + importing.descr = type; + init.push(t.moduleImport(importing.module, importing.name, importing.descr)); + } + /** + * instr* + */ + + + while (token.type === _tokenizer.tokens.openParen) { + eatToken(); + init.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.global(type, init, name); + } + /** + * Parses a function param + * + * WAST: + * + * param :: ( param * ) | ( param ) + */ + + + function parseFuncParam() { + var params = []; + var id; + var valtype; + + if (token.type === _tokenizer.tokens.identifier) { + id = token.value; + eatToken(); + } + + if (token.type === _tokenizer.tokens.valtype) { + valtype = token.value; + eatToken(); + params.push({ + id: id, + valtype: valtype + }); + /** + * Shorthand notation for multiple anonymous parameters + * @see https://webassembly.github.io/spec/core/text/types.html#function-types + * @see https://github.com/xtuc/webassemblyjs/issues/6 + */ + + if (id === undefined) { + while (token.type === _tokenizer.tokens.valtype) { + valtype = token.value; + eatToken(); + params.push({ + id: undefined, + valtype: valtype + }); + } + } + } else {// ignore + } + + return params; + } + /** + * Parses an element segments instruction + * + * WAST: + * + * elem: ( elem ? (offset * ) * ) + * ( elem ? * ) + * + * var: | + */ + + + function parseElem() { + var tableIndex = t.indexLiteral(0); + var offset = []; + var funcs = []; + + if (token.type === _tokenizer.tokens.identifier) { + tableIndex = identifierFromToken(token); + eatToken(); + } + + if (token.type === _tokenizer.tokens.number) { + tableIndex = t.indexLiteral(token.value); + eatToken(); + } + + while (token.type !== _tokenizer.tokens.closeParen) { + if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.offset)) { + eatToken(); // ( + + eatToken(); // offset + + while (token.type !== _tokenizer.tokens.closeParen) { + eatTokenOfType(_tokenizer.tokens.openParen); + offset.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + eatTokenOfType(_tokenizer.tokens.closeParen); + } else if (token.type === _tokenizer.tokens.identifier) { + funcs.push(t.identifier(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.number) { + funcs.push(t.indexLiteral(token.value)); + eatToken(); + } else if (token.type === _tokenizer.tokens.openParen) { + eatToken(); // ( + + offset.push(parseFuncInstr()); + eatTokenOfType(_tokenizer.tokens.closeParen); + } else { + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unsupported token in elem" + ", given " + tokenToString(token)); + }(); + } + } + + return t.elem(tableIndex, offset, funcs); + } + /** + * Parses the start instruction in a module + * + * WAST: + * + * start: ( start ) + * var: | + * + * WAT: + * start ::= ‘(’ ‘start’ x:funcidx ‘)’ + */ + + + function parseStart() { + if (token.type === _tokenizer.tokens.identifier) { + var index = identifierFromToken(token); + eatToken(); + return t.start(index); + } + + if (token.type === _tokenizer.tokens.number) { + var _index2 = t.indexLiteral(token.value); + + eatToken(); + return t.start(_index2); + } + + throw new Error("Unknown start, token: " + tokenToString(token)); + } + + if (token.type === _tokenizer.tokens.openParen) { + eatToken(); + var startLoc = getStartLoc(); + + if (isKeyword(token, _tokenizer.keywords.export)) { + eatToken(); + var node = parseExport(); + + var _endLoc2 = getEndLoc(); + + return t.withLoc(node, _endLoc2, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.loop)) { + eatToken(); + + var _node = parseLoop(); + + var _endLoc3 = getEndLoc(); + + return t.withLoc(_node, _endLoc3, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.func)) { + eatToken(); + + var _node2 = parseFunc(); + + var _endLoc4 = getEndLoc(); + + maybeIgnoreComment(); + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node2, _endLoc4, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.module)) { + eatToken(); + + var _node3 = parseModule(); + + var _endLoc5 = getEndLoc(); + + return t.withLoc(_node3, _endLoc5, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.import)) { + eatToken(); + + var _node4 = parseImport(); + + var _endLoc6 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node4, _endLoc6, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.block)) { + eatToken(); + + var _node5 = parseBlock(); + + var _endLoc7 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node5, _endLoc7, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.memory)) { + eatToken(); + + var _node6 = parseMemory(); + + var _endLoc8 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node6, _endLoc8, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.data)) { + eatToken(); + + var _node7 = parseData(); + + var _endLoc9 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node7, _endLoc9, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.table)) { + eatToken(); + + var _node8 = parseTable(); + + var _endLoc10 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node8, _endLoc10, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.global)) { + eatToken(); + + var _node9 = parseGlobal(); + + var _endLoc11 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node9, _endLoc11, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.type)) { + eatToken(); + + var _node10 = parseType(); + + var _endLoc12 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node10, _endLoc12, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.start)) { + eatToken(); + + var _node11 = parseStart(); + + var _endLoc13 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node11, _endLoc13, startLoc); + } + + if (isKeyword(token, _tokenizer.keywords.elem)) { + eatToken(); + + var _node12 = parseElem(); + + var _endLoc14 = getEndLoc(); + + eatTokenOfType(_tokenizer.tokens.closeParen); + return t.withLoc(_node12, _endLoc14, startLoc); + } + + var instruction = parseFuncInstr(); + var endLoc = getEndLoc(); + maybeIgnoreComment(); + + if (_typeof(instruction) === "object") { + if (typeof token !== "undefined") { + eatTokenOfType(_tokenizer.tokens.closeParen); + } + + return t.withLoc(instruction, endLoc, startLoc); + } + } + + if (token.type === _tokenizer.tokens.comment) { + var _startLoc = getStartLoc(); + + var builder = token.opts.type === "leading" ? t.leadingComment : t.blockComment; + + var _node13 = builder(token.value); + + eatToken(); // comment + + var _endLoc15 = getEndLoc(); + + return t.withLoc(_node13, _endLoc15, _startLoc); + } + + throw function () { + return new Error("\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + "\n" + "Unknown token" + ", given " + tokenToString(token)); + }(); + } + + var body = []; + + while (current < tokensList.length) { + body.push(walk()); + } + + return t.program(body); +} + +/***/ }), + +/***/ 65130: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + parse: true +}; +exports.parse = parse; + +var parser = _interopRequireWildcard(__webpack_require__(59830)); + +var _tokenizer = __webpack_require__(63124); + +var _numberLiterals = __webpack_require__(48709); + +Object.keys(_numberLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numberLiterals[key]; + } + }); +}); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function parse(source) { + var tokens = (0, _tokenizer.tokenize)(source); // We pass the source here to show code frames + + var ast = parser.parse(tokens, source); + return ast; +} + +/***/ }), + +/***/ 48709: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parse32F = parse32F; +exports.parse64F = parse64F; +exports.parse32I = parse32I; +exports.parseU32 = parseU32; +exports.parse64I = parse64I; +exports.isInfLiteral = isInfLiteral; +exports.isNanLiteral = isNanLiteral; + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +var _floatingPointHexParser = _interopRequireDefault(__webpack_require__(70447)); + +var _helperApiError = __webpack_require__(26833); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse32F(sourceString) { + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + if (isInfLiteral(sourceString)) { + return sourceString[0] === "-" ? -1 : 1; + } + + if (isNanLiteral(sourceString)) { + return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x400000); + } + + return parseFloat(sourceString); +} + +function parse64F(sourceString) { + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + if (isInfLiteral(sourceString)) { + return sourceString[0] === "-" ? -1 : 1; + } + + if (isNanLiteral(sourceString)) { + return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x8000000000000); + } + + if (isHexLiteral(sourceString)) { + return (0, _floatingPointHexParser.default)(sourceString); + } + + return parseFloat(sourceString); +} + +function parse32I(sourceString) { + var value = 0; + + if (isHexLiteral(sourceString)) { + value = ~~parseInt(sourceString, 16); + } else if (isDecimalExponentLiteral(sourceString)) { + throw new Error("This number literal format is yet to be implemented."); + } else { + value = parseInt(sourceString, 10); + } + + return value; +} + +function parseU32(sourceString) { + var value = parse32I(sourceString); + + if (value < 0) { + throw new _helperApiError.CompileError("Illegal value for u32: " + sourceString); + } + + return value; +} + +function parse64I(sourceString) { + var long; + + if (isHexLiteral(sourceString)) { + long = _long.default.fromString(sourceString, false, 16); + } else if (isDecimalExponentLiteral(sourceString)) { + throw new Error("This number literal format is yet to be implemented."); + } else { + long = _long.default.fromString(sourceString); + } + + return { + high: long.high, + low: long.low + }; +} + +var NAN_WORD = /^\+?-?nan/; +var INF_WORD = /^\+?-?inf/; + +function isInfLiteral(sourceString) { + return INF_WORD.test(sourceString.toLowerCase()); +} + +function isNanLiteral(sourceString) { + return NAN_WORD.test(sourceString.toLowerCase()); +} + +function isDecimalExponentLiteral(sourceString) { + return !isHexLiteral(sourceString) && sourceString.toUpperCase().includes("E"); +} + +function isHexLiteral(sourceString) { + return sourceString.substring(0, 2).toUpperCase() === "0X" || sourceString.substring(0, 3).toUpperCase() === "-0X"; +} + +/***/ }), + +/***/ 62139: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parseString = parseString; +// string literal characters cannot contain control codes +var CONTROL_CODES = [0, // null +7, // bell +8, // backspace +9, // horizontal +10, // line feed +11, // vertical tab +12, // form feed +13, // carriage return +26, // Control-Z +27, // escape +127 // delete +]; // escaped sequences can either be a two character hex value, or one of the +// following single character codes + +function decodeControlCharacter(char) { + switch (char) { + case "t": + return 0x09; + + case "n": + return 0x0a; + + case "r": + return 0x0d; + + case '"': + return 0x22; + + case "′": + return 0x27; + + case "\\": + return 0x5c; + } + + return -1; +} + +var ESCAPE_CHAR = 92; // backslash + +var QUOTE_CHAR = 34; // backslash +// parse string as per the spec: +// https://webassembly.github.io/spec/core/multipage/text/values.html#text-string + +function parseString(value) { + var byteArray = []; + var index = 0; + + while (index < value.length) { + var charCode = value.charCodeAt(index); + + if (CONTROL_CODES.indexOf(charCode) !== -1) { + throw new Error("ASCII control characters are not permitted within string literals"); + } + + if (charCode === QUOTE_CHAR) { + throw new Error("quotes are not permitted within string literals"); + } + + if (charCode === ESCAPE_CHAR) { + var firstChar = value.substr(index + 1, 1); + var decodedControlChar = decodeControlCharacter(firstChar); + + if (decodedControlChar !== -1) { + // single character escaped values, e.g. \r + byteArray.push(decodedControlChar); + index += 2; + } else { + // hex escaped values, e.g. \2a + var hexValue = value.substr(index + 1, 2); + + if (!/^[0-9A-F]{2}$/i.test(hexValue)) { + throw new Error("invalid character encoding"); + } + + byteArray.push(parseInt(hexValue, 16)); + index += 3; + } + } else { + // ASCII encoded values + byteArray.push(charCode); + index++; + } + } + + return byteArray; +} + +/***/ }), + +/***/ 63124: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.tokenize = tokenize; +exports.tokens = exports.keywords = void 0; + +var _helperFsm = __webpack_require__(82194); + +var _helperCodeFrame = __webpack_require__(87360); + +// eslint-disable-next-line +function getCodeFrame(source, line, column) { + var loc = { + start: { + line: line, + column: column + } + }; + return "\n" + (0, _helperCodeFrame.codeFrameFromSource)(source, loc) + "\n"; +} + +var WHITESPACE = /\s/; +var PARENS = /\(|\)/; +var LETTERS = /[a-z0-9_/]/i; +var idchar = /[a-z0-9!#$%&*+./:<=>?@\\[\]^_`|~-]/i; +var valtypes = ["i32", "i64", "f32", "f64"]; +var NUMBERS = /[0-9|.|_]/; +var NUMBER_KEYWORDS = /nan|inf/; + +function isNewLine(char) { + return char.charCodeAt(0) === 10 || char.charCodeAt(0) === 13; +} + +function Token(type, value, start, end) { + var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var token = { + type: type, + value: value, + loc: { + start: start, + end: end + } + }; + + if (Object.keys(opts).length > 0) { + // $FlowIgnore + token["opts"] = opts; + } + + return token; +} + +var tokenTypes = { + openParen: "openParen", + closeParen: "closeParen", + number: "number", + string: "string", + name: "name", + identifier: "identifier", + valtype: "valtype", + dot: "dot", + comment: "comment", + equal: "equal", + keyword: "keyword" +}; +var keywords = { + module: "module", + func: "func", + param: "param", + result: "result", + export: "export", + loop: "loop", + block: "block", + if: "if", + then: "then", + else: "else", + call: "call", + call_indirect: "call_indirect", + import: "import", + memory: "memory", + table: "table", + global: "global", + anyfunc: "anyfunc", + mut: "mut", + data: "data", + type: "type", + elem: "elem", + start: "start", + offset: "offset" +}; +exports.keywords = keywords; +var NUMERIC_SEPARATOR = "_"; +/** + * Build the FSM for number literals + */ + +var numberLiteralFSM = new _helperFsm.FSM({ + START: [(0, _helperFsm.makeTransition)(/-|\+/, "AFTER_SIGN"), (0, _helperFsm.makeTransition)(/nan:0x/, "NAN_HEX", { + n: 6 + }), (0, _helperFsm.makeTransition)(/nan|inf/, "STOP", { + n: 3 + }), (0, _helperFsm.makeTransition)(/0x/, "HEX", { + n: 2 + }), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC"), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC")], + AFTER_SIGN: [(0, _helperFsm.makeTransition)(/nan:0x/, "NAN_HEX", { + n: 6 + }), (0, _helperFsm.makeTransition)(/nan|inf/, "STOP", { + n: 3 + }), (0, _helperFsm.makeTransition)(/0x/, "HEX", { + n: 2 + }), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC"), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC")], + DEC_FRAC: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC_FRAC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/e|E/, "DEC_SIGNED_EXP")], + DEC: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/\./, "DEC_FRAC"), (0, _helperFsm.makeTransition)(/e|E/, "DEC_SIGNED_EXP")], + DEC_SIGNED_EXP: [(0, _helperFsm.makeTransition)(/\+|-/, "DEC_EXP"), (0, _helperFsm.makeTransition)(/[0-9]/, "DEC_EXP")], + DEC_EXP: [(0, _helperFsm.makeTransition)(/[0-9]/, "DEC_EXP", { + allowedSeparator: NUMERIC_SEPARATOR + })], + HEX: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "HEX", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/\./, "HEX_FRAC"), (0, _helperFsm.makeTransition)(/p|P/, "HEX_SIGNED_EXP")], + HEX_FRAC: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "HEX_FRAC", { + allowedSeparator: NUMERIC_SEPARATOR + }), (0, _helperFsm.makeTransition)(/p|P|/, "HEX_SIGNED_EXP")], + HEX_SIGNED_EXP: [(0, _helperFsm.makeTransition)(/[0-9|+|-]/, "HEX_EXP")], + HEX_EXP: [(0, _helperFsm.makeTransition)(/[0-9]/, "HEX_EXP", { + allowedSeparator: NUMERIC_SEPARATOR + })], + NAN_HEX: [(0, _helperFsm.makeTransition)(/[0-9|A-F|a-f]/, "NAN_HEX", { + allowedSeparator: NUMERIC_SEPARATOR + })], + STOP: [] +}, "START", "STOP"); + +function tokenize(input) { + var current = 0; + var char = input[current]; // Used by SourceLocation + + var column = 1; + var line = 1; + var tokens = []; + /** + * Creates a pushToken function for a given type + */ + + function pushToken(type) { + return function (v) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var startColumn = opts.startColumn || column - String(v).length; + delete opts.startColumn; + var endColumn = opts.endColumn || startColumn + String(v).length - 1; + delete opts.endColumn; + var start = { + line: line, + column: startColumn + }; + var end = { + line: line, + column: endColumn + }; + tokens.push(Token(type, v, start, end, opts)); + }; + } + /** + * Functions to save newly encountered tokens + */ + + + var pushCloseParenToken = pushToken(tokenTypes.closeParen); + var pushOpenParenToken = pushToken(tokenTypes.openParen); + var pushNumberToken = pushToken(tokenTypes.number); + var pushValtypeToken = pushToken(tokenTypes.valtype); + var pushNameToken = pushToken(tokenTypes.name); + var pushIdentifierToken = pushToken(tokenTypes.identifier); + var pushKeywordToken = pushToken(tokenTypes.keyword); + var pushDotToken = pushToken(tokenTypes.dot); + var pushStringToken = pushToken(tokenTypes.string); + var pushCommentToken = pushToken(tokenTypes.comment); + var pushEqualToken = pushToken(tokenTypes.equal); + /** + * Can be used to look at the next character(s). + * + * The default behavior `lookahead()` simply returns the next character without consuming it. + * Letters are always returned in lowercase. + * + * @param {number} length How many characters to query. Default = 1 + * @param {number} offset How many characters to skip forward from current one. Default = 1 + * + */ + + function lookahead() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return input.substring(current + offset, current + offset + length).toLowerCase(); + } + /** + * Advances the cursor in the input by a certain amount + * + * @param {number} amount How many characters to consume. Default = 1 + */ + + + function eatCharacter() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + column += amount; + current += amount; + char = input[current]; + } + + while (current < input.length) { + // ;; + if (char === ";" && lookahead() === ";") { + var startColumn = column; + eatCharacter(2); + var text = ""; + + while (!isNewLine(char)) { + text += char; + eatCharacter(); + + if (char === undefined) { + break; + } + } + + var endColumn = column; + pushCommentToken(text, { + type: "leading", + startColumn: startColumn, + endColumn: endColumn + }); + continue; + } // (; + + + if (char === "(" && lookahead() === ";") { + var _startColumn = column; + eatCharacter(2); + var _text = ""; // ;) + + while (true) { + char = input[current]; + + if (char === ";" && lookahead() === ")") { + eatCharacter(2); + break; + } + + _text += char; + eatCharacter(); + + if (isNewLine(char)) { + line++; + column = 0; + } + } + + var _endColumn = column; + pushCommentToken(_text, { + type: "block", + startColumn: _startColumn, + endColumn: _endColumn + }); + continue; + } + + if (char === "(") { + pushOpenParenToken(char); + eatCharacter(); + continue; + } + + if (char === "=") { + pushEqualToken(char); + eatCharacter(); + continue; + } + + if (char === ")") { + pushCloseParenToken(char); + eatCharacter(); + continue; + } + + if (isNewLine(char)) { + line++; + eatCharacter(); + column = 0; + continue; + } + + if (WHITESPACE.test(char)) { + eatCharacter(); + continue; + } + + if (char === "$") { + var _startColumn2 = column; + eatCharacter(); + var value = ""; + + while (idchar.test(char)) { + value += char; + eatCharacter(); + } + + var _endColumn2 = column; + pushIdentifierToken(value, { + startColumn: _startColumn2, + endColumn: _endColumn2 + }); + continue; + } + + if (NUMBERS.test(char) || NUMBER_KEYWORDS.test(lookahead(3, 0)) || char === "-" || char === "+") { + var _startColumn3 = column; + + var _value = numberLiteralFSM.run(input.slice(current)); + + if (_value === "") { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + pushNumberToken(_value, { + startColumn: _startColumn3 + }); + eatCharacter(_value.length); + + if (char && !PARENS.test(char) && !WHITESPACE.test(char)) { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + continue; + } + + if (char === '"') { + var _startColumn4 = column; + var _value2 = ""; + eatCharacter(); // " + + while (char !== '"') { + if (isNewLine(char)) { + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + _value2 += char; + eatCharacter(); // char + } + + eatCharacter(); // " + + var _endColumn3 = column; + pushStringToken(_value2, { + startColumn: _startColumn4, + endColumn: _endColumn3 + }); + continue; + } + + if (LETTERS.test(char)) { + var _value3 = ""; + var _startColumn5 = column; + + while (char && LETTERS.test(char)) { + _value3 += char; + eatCharacter(); + } + /* + * Handle MemberAccess + */ + + + if (char === ".") { + var dotStartColumn = column; + + if (valtypes.indexOf(_value3) !== -1) { + pushValtypeToken(_value3, { + startColumn: _startColumn5 + }); + } else { + pushNameToken(_value3); + } + + eatCharacter(); + _value3 = ""; + var nameStartColumn = column; + + while (LETTERS.test(char)) { + _value3 += char; + eatCharacter(); + } + + pushDotToken(".", { + startColumn: dotStartColumn + }); + pushNameToken(_value3, { + startColumn: nameStartColumn + }); + continue; + } + /* + * Handle keywords + */ + // $FlowIgnore + + + if (typeof keywords[_value3] === "string") { + pushKeywordToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + /* + * Handle types + */ + + + if (valtypes.indexOf(_value3) !== -1) { + pushValtypeToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + /* + * Handle literals + */ + + + pushNameToken(_value3, { + startColumn: _startColumn5 + }); + continue; + } + + throw new Error(getCodeFrame(input, line, column) + "Unexpected character " + JSON.stringify(char)); + } + + return tokens; +} + +var tokens = tokenTypes; +exports.tokens = tokens; + +/***/ }), + +/***/ 97023: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.print = print; + +var _ast = __webpack_require__(77325); + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +var compact = false; +var space = " "; + +var quote = function quote(str) { + return "\"".concat(str, "\""); +}; + +function indent(nb) { + return Array(nb).fill(space + space).join(""); +} // TODO(sven): allow arbitrary ast nodes + + +function print(n) { + if (n.type === "Program") { + return printProgram(n, 0); + } else { + throw new Error("Unsupported node in print of type: " + String(n.type)); + } +} + +function printProgram(n, depth) { + return n.body.reduce(function (acc, child) { + if (child.type === "Module") { + acc += printModule(child, depth + 1); + } + + if (child.type === "Func") { + acc += printFunc(child, depth + 1); + } + + if (child.type === "BlockComment") { + acc += printBlockComment(child); + } + + if (child.type === "LeadingComment") { + acc += printLeadingComment(child); + } + + if (compact === false) { + acc += "\n"; + } + + return acc; + }, ""); +} + +function printTypeInstruction(n) { + var out = ""; + out += "("; + out += "type"; + out += space; + + if (n.id != null) { + out += printIndex(n.id); + out += space; + } + + out += "("; + out += "func"; + n.functype.params.forEach(function (param) { + out += space; + out += "("; + out += "param"; + out += space; + out += printFuncParam(param); + out += ")"; + }); + n.functype.results.forEach(function (result) { + out += space; + out += "("; + out += "result"; + out += space; + out += result; + out += ")"; + }); + out += ")"; // func + + out += ")"; + return out; +} + +function printModule(n, depth) { + var out = "("; + out += "module"; + + if (typeof n.id === "string") { + out += space; + out += n.id; + } + + if (compact === false) { + out += "\n"; + } else { + out += space; + } + + n.fields.forEach(function (field) { + if (compact === false) { + out += indent(depth); + } + + switch (field.type) { + case "Func": + { + out += printFunc(field, depth + 1); + break; + } + + case "TypeInstruction": + { + out += printTypeInstruction(field); + break; + } + + case "Table": + { + out += printTable(field); + break; + } + + case "Global": + { + out += printGlobal(field, depth + 1); + break; + } + + case "ModuleExport": + { + out += printModuleExport(field); + break; + } + + case "ModuleImport": + { + out += printModuleImport(field); + break; + } + + case "Memory": + { + out += printMemory(field); + break; + } + + case "BlockComment": + { + out += printBlockComment(field); + break; + } + + case "LeadingComment": + { + out += printLeadingComment(field); + break; + } + + case "Start": + { + out += printStart(field); + break; + } + + case "Elem": + { + out += printElem(field, depth); + break; + } + + case "Data": + { + out += printData(field, depth); + break; + } + + default: + throw new Error("Unsupported node in printModule: " + String(field.type)); + } + + if (compact === false) { + out += "\n"; + } + }); + out += ")"; + return out; +} + +function printData(n, depth) { + var out = ""; + out += "("; + out += "data"; + out += space; + out += printIndex(n.memoryIndex); + out += space; + out += printInstruction(n.offset, depth); + out += space; + out += '"'; + n.init.values.forEach(function (byte) { + // Avoid non-displayable characters + if (byte <= 31 || byte == 34 || byte == 92 || byte >= 127) { + out += "\\"; + out += ("00" + byte.toString(16)).substr(-2); + } else if (byte > 255) { + throw new Error("Unsupported byte in data segment: " + byte); + } else { + out += String.fromCharCode(byte); + } + }); + out += '"'; + out += ")"; + return out; +} + +function printElem(n, depth) { + var out = ""; + out += "("; + out += "elem"; + out += space; + out += printIndex(n.table); + + var _n$offset = _slicedToArray(n.offset, 1), + firstOffset = _n$offset[0]; + + out += space; + out += "("; + out += "offset"; + out += space; + out += printInstruction(firstOffset, depth); + out += ")"; + n.funcs.forEach(function (func) { + out += space; + out += printIndex(func); + }); + out += ")"; + return out; +} + +function printStart(n) { + var out = ""; + out += "("; + out += "start"; + out += space; + out += printIndex(n.index); + out += ")"; + return out; +} + +function printLeadingComment(n) { + // Don't print leading comments in compact mode + if (compact === true) { + return ""; + } + + var out = ""; + out += ";;"; + out += n.value; + out += "\n"; + return out; +} + +function printBlockComment(n) { + // Don't print block comments in compact mode + if (compact === true) { + return ""; + } + + var out = ""; + out += "(;"; + out += n.value; + out += ";)"; + out += "\n"; + return out; +} + +function printSignature(n) { + var out = ""; + n.params.forEach(function (param) { + out += space; + out += "("; + out += "param"; + out += space; + out += printFuncParam(param); + out += ")"; + }); + n.results.forEach(function (result) { + out += space; + out += "("; + out += "result"; + out += space; + out += result; + out += ")"; + }); + return out; +} + +function printModuleImportDescr(n) { + var out = ""; + + if (n.type === "FuncImportDescr") { + out += "("; + out += "func"; + + if ((0, _ast.isAnonymous)(n.id) === false) { + out += space; + out += printIdentifier(n.id); + } + + out += printSignature(n.signature); + out += ")"; + } + + if (n.type === "GlobalType") { + out += "("; + out += "global"; + out += space; + out += printGlobalType(n); + out += ")"; + } + + if (n.type === "Table") { + out += printTable(n); + } + + return out; +} + +function printModuleImport(n) { + var out = ""; + out += "("; + out += "import"; + out += space; + out += quote(n.module); + out += space; + out += quote(n.name); + out += space; + out += printModuleImportDescr(n.descr); + out += ")"; + return out; +} + +function printGlobalType(n) { + var out = ""; + + if (n.mutability === "var") { + out += "("; + out += "mut"; + out += space; + out += n.valtype; + out += ")"; + } else { + out += n.valtype; + } + + return out; +} + +function printGlobal(n, depth) { + var out = ""; + out += "("; + out += "global"; + out += space; + + if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) { + out += printIdentifier(n.name); + out += space; + } + + out += printGlobalType(n.globalType); + out += space; + n.init.forEach(function (i) { + out += printInstruction(i, depth + 1); + }); + out += ")"; + return out; +} + +function printTable(n) { + var out = ""; + out += "("; + out += "table"; + out += space; + + if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) { + out += printIdentifier(n.name); + out += space; + } + + out += printLimit(n.limits); + out += space; + out += n.elementType; + out += ")"; + return out; +} + +function printFuncParam(n) { + var out = ""; + + if (typeof n.id === "string") { + out += "$" + n.id; + out += space; + } + + out += n.valtype; + return out; +} + +function printFunc(n, depth) { + var out = ""; + out += "("; + out += "func"; + + if (n.name != null) { + if (n.name.type === "Identifier" && (0, _ast.isAnonymous)(n.name) === false) { + out += space; + out += printIdentifier(n.name); + } + } + + if (n.signature.type === "Signature") { + out += printSignature(n.signature); + } else { + var index = n.signature; + out += space; + out += "("; + out += "type"; + out += space; + out += printIndex(index); + out += ")"; + } + + if (n.body.length > 0) { + // func is empty since we ignore the default end instruction + if (n.body.length === 1 && n.body[0].id === "end") { + out += ")"; + return out; + } + + if (compact === false) { + out += "\n"; + } + + n.body.forEach(function (i) { + if (i.id !== "end") { + out += indent(depth); + out += printInstruction(i, depth); + + if (compact === false) { + out += "\n"; + } + } + }); + out += indent(depth - 1) + ")"; + } else { + out += ")"; + } + + return out; +} + +function printInstruction(n, depth) { + switch (n.type) { + case "Instr": + // $FlowIgnore + return printGenericInstruction(n, depth + 1); + + case "BlockInstruction": + // $FlowIgnore + return printBlockInstruction(n, depth + 1); + + case "IfInstruction": + // $FlowIgnore + return printIfInstruction(n, depth + 1); + + case "CallInstruction": + // $FlowIgnore + return printCallInstruction(n, depth + 1); + + case "CallIndirectInstruction": + // $FlowIgnore + return printCallIndirectIntruction(n, depth + 1); + + case "LoopInstruction": + // $FlowIgnore + return printLoopInstruction(n, depth + 1); + + default: + throw new Error("Unsupported instruction: " + JSON.stringify(n.type)); + } +} + +function printCallIndirectIntruction(n, depth) { + var out = ""; + out += "("; + out += "call_indirect"; + + if (n.signature.type === "Signature") { + out += printSignature(n.signature); + } else if (n.signature.type === "Identifier") { + out += space; + out += "("; + out += "type"; + out += space; + out += printIdentifier(n.signature); + out += ")"; + } else { + throw new Error("CallIndirectInstruction: unsupported signature " + JSON.stringify(n.signature.type)); + } + + out += space; + + if (n.intrs != null) { + // $FlowIgnore + n.intrs.forEach(function (i, index) { + // $FlowIgnore + out += printInstruction(i, depth + 1); // $FlowIgnore + + if (index !== n.intrs.length - 1) { + out += space; + } + }); + } + + out += ")"; + return out; +} + +function printLoopInstruction(n, depth) { + var out = ""; + out += "("; + out += "loop"; + + if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) { + out += space; + out += printIdentifier(n.label); + } + + if (typeof n.resulttype === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.resulttype; + out += ")"; + } + + if (n.instr.length > 0) { + n.instr.forEach(function (e) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(e, depth + 1); + }); + + if (compact === false) { + out += "\n"; + out += indent(depth - 1); + } + } + + out += ")"; + return out; +} + +function printCallInstruction(n, depth) { + var out = ""; + out += "("; + out += "call"; + out += space; + out += printIndex(n.index); + + if (_typeof(n.instrArgs) === "object") { + // $FlowIgnore + n.instrArgs.forEach(function (arg) { + out += space; + out += printFuncInstructionArg(arg, depth + 1); + }); + } + + out += ")"; + return out; +} + +function printIfInstruction(n, depth) { + var out = ""; + out += "("; + out += "if"; + + if (n.testLabel != null && (0, _ast.isAnonymous)(n.testLabel) === false) { + out += space; + out += printIdentifier(n.testLabel); + } + + if (typeof n.result === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.result; + out += ")"; + } + + if (n.test.length > 0) { + out += space; + n.test.forEach(function (i) { + out += printInstruction(i, depth + 1); + }); + } + + if (n.consequent.length > 0) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += "("; + out += "then"; + depth++; + n.consequent.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + depth--; + + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += ")"; + } else { + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += "("; + out += "then"; + out += ")"; + } + + if (n.alternate.length > 0) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += "("; + out += "else"; + depth++; + n.alternate.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + depth--; + + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += ")"; + } else { + if (compact === false) { + out += "\n"; + out += indent(depth); + } + + out += "("; + out += "else"; + out += ")"; + } + + if (compact === false) { + out += "\n"; + out += indent(depth - 1); + } + + out += ")"; + return out; +} + +function printBlockInstruction(n, depth) { + var out = ""; + out += "("; + out += "block"; + + if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) { + out += space; + out += printIdentifier(n.label); + } + + if (typeof n.result === "string") { + out += space; + out += "("; + out += "result"; + out += space; + out += n.result; + out += ")"; + } + + if (n.instr.length > 0) { + n.instr.forEach(function (i) { + if (compact === false) { + out += "\n"; + } + + out += indent(depth); + out += printInstruction(i, depth + 1); + }); + + if (compact === false) { + out += "\n"; + } + + out += indent(depth - 1); + out += ")"; + } else { + out += ")"; + } + + return out; +} + +function printGenericInstruction(n, depth) { + var out = ""; + out += "("; + + if (typeof n.object === "string") { + out += n.object; + out += "."; + } + + out += n.id; + n.args.forEach(function (arg) { + out += space; + out += printFuncInstructionArg(arg, depth + 1); + }); + out += ")"; + return out; +} + +function printLongNumberLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + var _n$value = n.value, + low = _n$value.low, + high = _n$value.high; + var v = new _long.default(low, high); + return v.toString(); +} + +function printFloatLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + return String(n.value); +} + +function printFuncInstructionArg(n, depth) { + var out = ""; + + if (n.type === "NumberLiteral") { + out += printNumberLiteral(n); + } + + if (n.type === "LongNumberLiteral") { + out += printLongNumberLiteral(n); + } + + if (n.type === "Identifier" && (0, _ast.isAnonymous)(n) === false) { + out += printIdentifier(n); + } + + if (n.type === "ValtypeLiteral") { + out += n.name; + } + + if (n.type === "FloatLiteral") { + out += printFloatLiteral(n); + } + + if ((0, _ast.isInstruction)(n)) { + out += printInstruction(n, depth + 1); + } + + return out; +} + +function printNumberLiteral(n) { + if (typeof n.raw === "string") { + return n.raw; + } + + return String(n.value); +} + +function printModuleExport(n) { + var out = ""; + out += "("; + out += "export"; + out += space; + out += quote(n.name); + + if (n.descr.exportType === "Func") { + out += space; + out += "("; + out += "func"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Global") { + out += space; + out += "("; + out += "global"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Memory" || n.descr.exportType === "Mem") { + out += space; + out += "("; + out += "memory"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else if (n.descr.exportType === "Table") { + out += space; + out += "("; + out += "table"; + out += space; + out += printIndex(n.descr.id); + out += ")"; + } else { + throw new Error("printModuleExport: unknown type: " + n.descr.exportType); + } + + out += ")"; + return out; +} + +function printIdentifier(n) { + return "$" + n.value; +} + +function printIndex(n) { + if (n.type === "Identifier") { + return printIdentifier(n); + } else if (n.type === "NumberLiteral") { + return printNumberLiteral(n); + } else { + throw new Error("Unsupported index: " + n.type); + } +} + +function printMemory(n) { + var out = ""; + out += "("; + out += "memory"; + + if (n.id != null) { + out += space; + out += printIndex(n.id); + out += space; + } + + out += printLimit(n.limits); + out += ")"; + return out; +} + +function printLimit(n) { + var out = ""; + out += n.min + ""; + + if (n.max != null) { + out += space; + out += String(n.max); + } + + return out; +} + +/***/ }), + +/***/ 17496: +/***/ (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), + 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, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (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), 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. + allowImportExportEverywhere: false, + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: false, + // 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_VAR = SCOPE_TOP | SCOPE_FUNCTION, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128; + + 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; + + // 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 = {}; + + // 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; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { 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 }; + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; + prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 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 = {}; + 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) { return true } // '[' + if (context) { return false } + + if (nextCh === 123) { return true } // '{' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } + 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; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) + }; + + // 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.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && 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 refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(true, refDestructuringErrors); + if (this.type === types._in || (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; } + } + 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) { + 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); + + 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 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; + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$1.parseClassElement = function(constructorAllowsSuper) { + var this$1 = this; + + if (this.eat(types.semi)) { return null } + + var method = this.startNode(); + var tryContextual = function (k, noLineBreak) { + if ( noLineBreak === void 0 ) noLineBreak = false; + + var start = this$1.start, startLoc = this$1.startLoc; + if (!this$1.eatContextual(k)) { return false } + if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } + if (method.key) { this$1.unexpected(); } + method.computed = false; + method.key = this$1.startNodeAt(start, startLoc); + method.key.name = k; + this$1.finishNode(method.key, "Identifier"); + return false + }; + + method.kind = "method"; + method.static = tryContextual("static"); + var isGenerator = this.eat(types.star); + var isAsync = false; + if (!isGenerator) { + if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + } else if (tryContextual("get")) { + method.kind = "get"; + } else if (tryContextual("set")) { + method.kind = "set"; + } + } + if (!method.key) { this.parsePropertyName(method); } + var key = method.key; + var allowsDirectSuper = false; + if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || + key.type === "Literal" && key.value === "constructor")) { + if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } + 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"); } + method.kind = "constructor"; + allowsDirectSuper = constructorAllowsSuper; + } else if (method.static && key.type === "Identifier" && key.name === "prototype") { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); + if (method.kind === "get" && method.value.params.length !== 0) + { this.raiseRecoverable(method.value.start, "getter should have no params"); } + if (method.kind === "set" && method.value.params.length !== 1) + { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } + if (method.kind === "set" && method.value.params[0].type === "RestElement") + { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } + return method + }; + + pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + return this.finishNode(method, "MethodDefinition") + }; + + 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() : null; + }; + + // 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); + } + }; + + // A recursive descent parser operates by defining functions for all + + var pp$3 = 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$3.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$3.parseExpression = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(noIn, 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(noIn, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(noIn) } + // 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; } + var left = this.parseMaybeConditional(noIn, 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(noIn); + 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$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(noIn, 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(noIn); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$3.parseExprOps = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) + }; + + // 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$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.type.binop; + if (prec != null && (!noIn || 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), startPos, startLoc, prec, noIn); + 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, noIn) + } + } + return left + }; + + pp$3.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$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { + expr = this.parseAwait(); + 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); + 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 { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors); + 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 (!sawUnary && this.eat(types.starstar)) + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + else + { return expr } + }; + + // Parse call, dot, and `[]`-subscript expressions. + + pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + } + return result + }; + + pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + 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); + + 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$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { + 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; + node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); + node.computed = !!computed; + if (computed) { this.expect(types.bracketR); } + 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) + } + 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$3.parseExprAtom = function(refDestructuringErrors) { + // 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)) + { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + 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); + 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: + 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$3.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$3.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$3.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.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$3.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$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val + }; + + pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + 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.start, innerEndLoc = this.startLoc; + 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) + } + + 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$3.parseParenItem = function(item) { + return item + }; + + pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) + }; + + // 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$3.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.inNonArrowFunction) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } + 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); + 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$3.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$3.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$3.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$3.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$3.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$3.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$3.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$3.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$3.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); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$3.parseArrowExpression = function(node, params, isAsync) { + 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); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + 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$3.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$3.checkParams = function(node, allowDuplicates) { + var nameHash = {}; + 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$3.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$3.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.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$3.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 + }; + + // Parses yield expression inside generator. + + pp$3.parseYield = function(noIn) { + 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(noIn); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = 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$4.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$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$5 = 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 = []; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$5.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$5.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$5.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$5.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$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$5.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$5.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$6 = Parser.prototype; + + pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$6.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$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$6.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // 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$7 = Parser.prototype; + + pp$7.initialContext = function() { + return [types$1.b_stat] + }; + + pp$7.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$7.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$7.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; } + }; + + // 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; + }; + + // 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" : ""); + 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). + + pp$9.curContext = function() { + return this.context[this.context.length - 1] + }; + + // 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 >= 0xe000) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return (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]-------+ +*/ + +const STORAGE_MODE_IDLE = 0; +const STORAGE_MODE_SYNC = 1; +const STORAGE_MODE_ASYNC = 2; + +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; + + /** @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(); + } + 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); + } + + _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; + } + } + + _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 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); + } + + 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); + } +}; + + +/***/ }), + +/***/ 36154: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const basename = __webpack_require__(17117).basename; + +/** @typedef {import("./Resolver")} Resolver */ + +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 + ); + }); + } +}; + + +/***/ }), + +/***/ 13134: +/***/ ((module) => { + +"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 */ + +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; + } + + /** + * @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); + + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 85774: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DescriptionFileUtils = __webpack_require__(18641); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +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 {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); + } + ); + } + ); + } + ); + } +}; + + +/***/ }), + +/***/ 18641: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const forEachBail = __webpack_require__(55426); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ + +/** + * @typedef {Object} DescriptionFileInfo + * @property {any=} content + * @property {string} path + * @property {string} directory + */ + +/** + * @callback ErrorFirstCallback + * @param {Error|null=} error + * @param {DescriptionFileInfo=} result + */ + +/** + * @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 (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 {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]; + } +} + +/** + * @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); +} + +exports.loadDescriptionFile = loadDescriptionFile; +exports.getField = getField; +exports.cdUp = cdUp; + + +/***/ }), + +/***/ 61827: +/***/ ((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 */ + +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 + ); + }); + } + ); + } +}; + + +/***/ }), + +/***/ 98169: +/***/ ((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__(85622); +const DescriptionFileUtils = __webpack_require__(18641); +const forEachBail = __webpack_require__(55426); +const { processExportsField } = __webpack_require__(94340); +const { parseIdentifier } = __webpack_require__(98623); +const { checkExportsFieldTarget } = __webpack_require__(69821); + +/** @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 + }; + + resolver.doResolve( + target, + obj, + "using exports field: " + p, + resolveContext, + callback + ); + }, + (err, result) => callback(err, result || null) + ); + }); + } +}; + + +/***/ }), + +/***/ 9412: +/***/ ((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 */ + +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 + ); + }); + }); + } +}; + + +/***/ }), + +/***/ 41031: +/***/ ((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__(85622); +const DescriptionFileUtils = __webpack_require__(18641); +const forEachBail = __webpack_require__(55426); +const { processImportsField } = __webpack_require__(94340); +const { parseIdentifier } = __webpack_require__(98623); + +/** @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(); + } + + /** + * @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) 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.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) + ); + }); + } +}; + + +/***/ }), + +/***/ 11399: +/***/ ((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); + } + + 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); + } + ); + } +}; + + +/***/ }), + +/***/ 90522: +/***/ ((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 */ + +module.exports = class JoinRequestPlugin { + /** + * @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("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); + }); + } +}; + + +/***/ }), + +/***/ 50098: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./Resolver")} Resolver */ + +module.exports = class LogInfoPlugin { + constructor(source) { + this.source = source; + } + + /** + * @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(); + }); + } +}; + + +/***/ }), + +/***/ 18425: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const path = __webpack_require__(85622); +const DescriptionFileUtils = __webpack_require__(18641); + +/** @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 + ); + + 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 + ); + }); + } +}; + + +/***/ }), + +/***/ 44964: +/***/ ((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__(55426); +const getPaths = __webpack_require__(17117); + +/** @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; + } + + /** + * @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 + ); + } + ); + } +}; + + +/***/ }), + +/***/ 39803: +/***/ ((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 */ + +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 {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 + ); + }); + } +}; + + +/***/ }), + +/***/ 76354: +/***/ ((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 */ + +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); + }); + } +}; + + +/***/ }), + +/***/ 95204: +/***/ ((module) => { + +"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 */ + +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); + }); + } +}; + + +/***/ }), + +/***/ 63321: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maël Nison @arcanis +*/ + + + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** + * @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; + } + + /** + * @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); + } + + 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); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 7675: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __webpack_require__(34718); +const createInnerContext = __webpack_require__(710); +const { parseIdentifier } = __webpack_require__(98623); +const { + normalize, + cachedJoin: join, + getType, + PathType +} = __webpack_require__(69821); + +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ + +/** + * @typedef {Object} FileSystemStats + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile + */ + +/** + * @typedef {Object} FileSystemDirent + * @property {Buffer | string} name + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile + */ + +/** + * @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 {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 + */ + +/** + * @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 + */ + +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ + +/** + * String with special formatting + * @typedef {string} StackEntry + */ + +/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ + +/** + * 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 */ + +/** + * @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 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; + } + + /** + * @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; + } + + /** + * @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; + } + + /** + * @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); + } + ); + } + ); + } + } + + doResolve(hook, request, message, resolveContext, callback) { + const stackEntry = Resolver.createStackEntry(hook, request); + + 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); + + 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(); + } + } + + /** + * @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; + + [part.request, part.query, part.fragment] = parsedIdentifier; + + 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); + } + } + + return part; + } + + isModule(path) { + return getType(path) === PathType.Normal; + } + + isPrivate(path) { + return getType(path) === PathType.Internal; + } + + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path) { + return path.endsWith("/"); + } + + join(path, request) { + return join(path, request); + } + + normalize(path) { + return normalize(path); + } +} + +module.exports = Resolver; + + +/***/ }), + +/***/ 1453: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const versions = __webpack_require__(61765).versions; +const Resolver = __webpack_require__(7675); +const { getType, PathType } = __webpack_require__(69821); + +const SyncAsyncFileSystemDecorator = __webpack_require__(83908); + +const AliasFieldPlugin = __webpack_require__(94469); +const AliasPlugin = __webpack_require__(42673); +const AppendPlugin = __webpack_require__(72405); +const ConditionalPlugin = __webpack_require__(13134); +const DescriptionFilePlugin = __webpack_require__(85774); +const DirectoryExistsPlugin = __webpack_require__(61827); +const ExportsFieldPlugin = __webpack_require__(98169); +const FileExistsPlugin = __webpack_require__(9412); +const ImportsFieldPlugin = __webpack_require__(41031); +const JoinRequestPartPlugin = __webpack_require__(11399); +const JoinRequestPlugin = __webpack_require__(90522); +const MainFieldPlugin = __webpack_require__(18425); +const ModulesInHierachicDirectoriesPlugin = __webpack_require__(44964); +const ModulesInRootPlugin = __webpack_require__(39803); +const NextPlugin = __webpack_require__(76354); +const ParsePlugin = __webpack_require__(95204); +const PnpPlugin = __webpack_require__(63321); +const RestrictionsPlugin = __webpack_require__(94620); +const ResultPlugin = __webpack_require__(47775); +const RootsPlugin = __webpack_require__(8068); +const SelfReferencePlugin = __webpack_require__(24887); +const SymlinkPlugin = __webpack_require__(69476); +const TryNextPlugin = __webpack_require__(73771); +const UnsafeCachePlugin = __webpack_require__(57943); +const UseFilePlugin = __webpack_require__(81190); + +/** @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} 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 + */ + +/** + * @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 + */ + +/** + * @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__(97289); // eslint-disable-line node/no-missing-require + } + + return option || null; +} + +/** + * @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) || []; +} + +/** + * @param {UserResolveOptions} options input options + * @returns {ResolveOptions} output options + */ +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 + }); + } + } + + 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 || false, + 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, + restrictions: new Set(options.restrictions) + }; +} + +/** + * @param {UserResolveOptions} options resolve options + * @returns {Resolver} created resolver + */ +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, + symlinks, + unsafeCache, + resolver: customResolver, + restrictions, + roots + } = normalizedOptions; + + const plugins = userPlugins.slice(); + + const resolver = customResolver + ? customResolver + : new Resolver(fileSystem, normalizedOptions); + + //// 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"); + + // 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")); + + // 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 (roots.size > 0) { + plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); + } + if (!preferRelative) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + + // internal + importsFields.forEach(importsField => { + plugins.push( + new ImportsFieldPlugin( + "internal", + conditionNames, + importsField, + "relative", + "internal-resolve" + ) + ); + }); + + // raw-module + exportsFields.forEach(exportsField => { + plugins.push( + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") + ); + }); + modules.forEach(item => { + if (Array.isArray(item)) { + plugins.push( + new ModulesInHierachicDirectoriesPlugin("raw-module", item, "module") + ); + if (item.includes("node_modules") && pnpApi) { + plugins.push( + new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") + ); + } + } 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" + ) + ); + }); + 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")); + + // 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" + ) + ); + } + + // directory + plugins.push( + new DirectoryExistsPlugin("directory", "undescribed-existing-directory") + ); + + 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" + ) + ); + }); + + // 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")); + + // 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")); + }); + + // 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")); + } + + // resolved + if (restrictions.size > 0) { + plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); + } + plugins.push(new ResultPlugin(resolver.hooks.resolved)); + + //// RESOLVER //// + + for (const plugin of plugins) { + if (typeof plugin === "function") { + plugin.call(resolver, resolver); + } else { + plugin.apply(resolver); + } + } + + return resolver; +}; + +/** + * 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); + + 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 result; +} + + +/***/ }), + +/***/ 94620: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +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; + } + + /** + * @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); + } + } + } + + callback(); + }); + } +}; + + +/***/ }), + +/***/ 47775: +/***/ ((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 */ + +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); + }); + } + ); + } +}; + + +/***/ }), + +/***/ 8068: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const forEachBail = __webpack_require__(55426); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +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; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + + 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 = RootsPlugin; + + +/***/ }), + +/***/ 24887: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DescriptionFileUtils = __webpack_require__(18641); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const slashCode = "/".charCodeAt(0); + +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; + } + + /** + * @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(); + + 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(); + } + }); + } +}; + + +/***/ }), + +/***/ 69476: +/***/ ((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__(55426); +const getPaths = __webpack_require__(17117); +const { getType, PathType } = __webpack_require__(69821); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class SymlinkPlugin { + /** + * @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("SymlinkPlugin", (request, resolveContext, callback) => { + if (request.ignoreSymlinks) return callback(); + const pathsResult = getPaths(request.path); + const pathSeqments = pathsResult.seqments; + const paths = pathsResult.paths; + + 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 + ); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 83908: +/***/ ((module) => { + +"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); + } + + this.stat = (arg, options, callback) => { + let result; + try { + result = fs.statSync(arg, options); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.statSync = (arg, options) => fs.statSync(arg, options); + + 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 = SyncAsyncFileSystemDecorator; + + +/***/ }), + +/***/ 73771: +/***/ ((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 */ + +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 + ); + }); + } +}; + + +/***/ }), + +/***/ 57943: +/***/ ((module) => { + +"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 */ +/** @typedef {{[k: string]: any}} Cache */ + +function getCacheId(request, withContext) { + return JSON.stringify({ + context: withContext ? request.context : "", + path: request.path, + query: request.query, + fragment: request.fragment, + request: request.request + }); +} + +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; + } + + /** + * @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(); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 81190: +/***/ ((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 */ + +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; + } + + /** + * @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 + ); + }); + } +}; + + +/***/ }), + +/***/ 710: +/***/ ((module) => { + +"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; +}; + + +/***/ }), + +/***/ 55426: +/***/ ((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()); +}; + + +/***/ }), + +/***/ 98361: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) + return request.__innerRequest; + 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); +}; + + +/***/ }), + +/***/ 17117: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +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.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; +}; + + +/***/ }), + +/***/ 27480: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const fs = __webpack_require__(82161); +const CachedInputFileSystem = __webpack_require__(26785); +const ResolverFactory = __webpack_require__(1453); + +/** @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 nodeFileSystem = new CachedInputFileSystem(fs, 4000); + +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); + }; +} + +/** + * @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__(36154); + }, + get LogInfoPlugin() { + return __webpack_require__(50098); + }, + get forEachBail() { + return __webpack_require__(55426); + } +}); + + +/***/ }), + +/***/ 94340: +/***/ ((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} 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. + +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 + ); +}; + +/** + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processImportsField = function processImportsField( + importsField +) { + return createFieldProcessor( + buildImportsFieldPathTree(importsField), + assertImportsFieldRequest, + assertImportTarget + ); +}; + +/** + * @param {PathTreeNode} treeRoot root + * @param {(s: string) => void} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor + */ +function createFieldProcessor(treeRoot, assertRequest, assertTarget) { + return function fieldProcessor(request, conditionNames) { + assertRequest(request); + + const match = findMatch(request, treeRoot); + + if (match === null) return []; + + /** @type {DirectMapping|null} */ + let direct = null; + const [mapping, remainRequestIndex] = match; + + if (isConditionalMapping(mapping)) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames + ); + + // matching not found + if (direct === null) return []; + } else { + direct = /** @type {DirectMapping} */ (mapping); + } + + const remainingRequest = + remainRequestIndex !== request.length + ? request.slice(remainRequestIndex) + : undefined; + + return directMapping( + remainingRequest, + direct, + conditionNames, + assertTarget + ); + }; +} + +/** + * @param {string} request 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"); + } +} + +/** + * @param {string} request 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"); + } +} + +/** + * @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 "/"` + ); + } +} + +/** + * @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 "/"` + ); + } +} + +/** + * Trying to match request to field + * @param {string} request request + * @param {PathTreeNode} treeRoot path tree root + * @returns {[MappingValue, number]|null} match or null + */ +function findMatch(request, treeRoot) { + if (request.length === 1) { + const value = treeRoot.files.get("*root*"); + + return value ? [value, 1] : null; + } + + if (treeRoot.children === null && treeRoot.folder === null) { + const value = treeRoot.files.get(request); + + return value ? [value, request.length] : null; + } + + let node = treeRoot; + let lastNonSlashIndex = 0; + let slashIndex = request.indexOf("/", 2); + + /** @type {[MappingValue, number]|null} */ + let lastFolderMatch = null; + + while (slashIndex !== -1) { + const folder = request.slice(lastNonSlashIndex, slashIndex); + + const folderMapping = node.folder; + if (folderMapping) { + if (lastFolderMatch) { + lastFolderMatch[0] = folderMapping; + lastFolderMatch[1] = lastNonSlashIndex; + } else { + lastFolderMatch = [folderMapping, lastNonSlashIndex || 2]; + } + } + + if (node.children === null) return lastFolderMatch; + + const newNode = node.children.get(folder); + + if (!newNode) { + const value = node.folder; + + return value ? [value, lastNonSlashIndex] : null; + } + + node = newNode; + lastNonSlashIndex = slashIndex + 1; + slashIndex = request.indexOf("/", lastNonSlashIndex); + } + + const value = node.files.get( + lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request + ); + + if (value) { + return [value, request.length]; + } + + const folderMapping = node.folder; + if (folderMapping) { + return [folderMapping, lastNonSlashIndex || 2]; + } + + 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) + ); +} + +/** + * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {DirectMapping|null} dirrectMapping_ direct export + * @param {Set} conditionNames condition names + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string[]} mapping result + */ +function directMapping( + remainingRequest, + dirrectMapping_, + conditionNames, + assert +) { + if (dirrectMapping_ === null) return []; + + const expectFolder = remainingRequest !== undefined; + + if (typeof dirrectMapping_ === "string") { + assert(dirrectMapping_, expectFolder); + + return expectFolder + ? [`${dirrectMapping_}${remainingRequest}`] + : [dirrectMapping_]; + } + + const targets = []; + + for (const exp of dirrectMapping_) { + if (typeof exp === "string") { + assert(exp, expectFolder); + targets.push(expectFolder ? `${exp}${remainingRequest}` : exp); + continue; + } + + const mapping = conditionalMapping(exp, conditionNames); + if (!mapping) continue; + const innerExports = directMapping( + remainingRequest, + mapping, + conditionNames, + assert + ); + for (const innerExport of innerExports) { + targets.push(innerExport); + } + } + + return targets; +} + +/** + * @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; + } + + 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, + files: new Map() + }; +} + +/** + * 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 === 2 && path === "./") { + root.folder = target; + return; + } + + let node = root; + // It is safe to store # and ./ as a part of file + // because mapping works like string concatenation + // so typical path tree can looks like + // root + // - files: ["./a.js", "./b.js"] + // - children: + // node1: + // - files: ["a.js", "b.js"] + let lastNonSlashIndex = 0; + // This is safe for "imports" field + // since specifiers "#" and "#/" are disallowed and + // should be asserted before "walking" + let slashIndex = path.indexOf("/", 2); + + 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.files.set( + lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path, + target + ); + } else { + node.folder = target; + } +} + +/** + * @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("*root*", field); + + return root; + } else if (Array.isArray(field)) { + root.files.set("*root*", 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++; + } + + root.files.set("*root*", field); + return root; + } + + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key + )})` + ); + } + + if (key.length === 1) { + root.files.set("*root*", 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, field[key]); + } + + return root; +} + +/** + * @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, field[key]); + } + + return root; +} + + +/***/ }), + +/***/ 98623: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + +/** + * @param {string} identifier identifier + * @returns {[string, string, string]|null} parsed identifier + */ +function parseIdentifier(identifier) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); + + if (!match) return null; + + return [ + match[1].replace(/\0(.)/g, "$1"), + match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + match[3] || "" + ]; +} + +module.exports.parseIdentifier = parseIdentifier; + + +/***/ }), + +/***/ 69821: +/***/ ((__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__(85622); + +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; + +/** + * @enum {number} + */ +const PathType = Object.freeze({ + Empty: 0, + Normal: 1, + Relative: 2, + AbsoluteWin: 3, + AbsolutePosix: 4, + Internal: 5 +}); +exports.PathType = PathType; + +/** + * @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; + +/** + * @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; + +/** + * @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; + + +/***/ }), + +/***/ 16938: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + 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. +*/ + + +const Variable = __webpack_require__(17631); + +/** + * @class Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {Number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {String?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @class ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +module.exports = { + ParameterDefinition, + Definition +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 74902: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + 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. +*/ + +/** + * 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 + */ + + +/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ + +const assert = __webpack_require__(42357); + +const ScopeManager = __webpack_require__(46321); +const Referencer = __webpack_require__(31927); +const Reference = __webpack_require__(97474); +const Variable = __webpack_require__(17631); +const Scope = __webpack_require__(56605).Scope; +const version = __webpack_require__(21386)/* .version */ .i8; + +/** + * 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" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target - Options + * @param {Object} override - Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * 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); + } + + for (const key in override) { + if (Object.prototype.hasOwnProperty.call(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + 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); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +module.exports = { + + /** @name module:escope.version */ + version, + + /** @name module:escope.Reference */ + Reference, + + /** @name module:escope.Variable */ + Variable, + + /** @name module:escope.Scope */ + Scope, + + /** @name module:escope.ScopeManager */ + ScopeManager, + analyze +}; + + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 87869: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + 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-undefined */ + +const Syntax = __webpack_require__(40379).Syntax; +const esrecurse = __webpack_require__(10277); + +/** + * 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; + + 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 = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // 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); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // 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... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +module.exports = PatternVisitor; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 97474: +/***/ ((module) => { + +"use strict"; +/* + 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. +*/ + + +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; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * 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()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * 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); + } + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * 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; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +module.exports = Reference; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 31927: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + 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 Syntax = __webpack_require__(40379).Syntax; +const esrecurse = __webpack_require__(10277); +const Reference = __webpack_require__(97474); +const Variable = __webpack_require__(17631); +const PatternVisitor = __webpack_require__(87869); +const definition = __webpack_require__(16938); +const assert = __webpack_require__(42357); + +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) { + + // 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); + } +} + +// 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 + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +// 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; + } + + 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; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + 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 + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + 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. + + if (node.type === Syntax.FunctionDeclaration) { + + // 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 that = this; + + /** + * 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 + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // 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 + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + 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 + )); + } + + this.visit(node.superClass); + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + 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); + } + + 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); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + 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); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + 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, !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); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.__isNodejsScope()) { + + // 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); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this + + ContinueStatement() {} // eslint-disable-line class-methods-use-this + + LabeledStatement(node) { + this.visit(node.body); + } + + 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); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + 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); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + 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); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + 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."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + 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); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this + + // do nothing. + } +} + +module.exports = Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 46321: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + 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 */ + +const Scope = __webpack_require__(56605); +const assert = __webpack_require__(42357); + +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(); + } + + __useDirective() { + return this.__options.directive; + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isNodejsScope() { + return this.__options.nodejsScope; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + 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) || []; + } + + /** + * 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; + } + + const scopes = this.__get(node); + + 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]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + 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); + } + + /** + * 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); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + 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 + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __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)); + } + + __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; + } +} + +module.exports = ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 56605: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + 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 Syntax = __webpack_require__(40379).Syntax; + +const Reference = __webpack_require__(97474); +const Variable = __webpack_require__(17631); +const Definition = __webpack_require__(16938).Definition; +const assert = __webpack_require__(42357); + +/** + * 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; + + // 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; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager - scope manager + * @param {Scope} scope - scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * 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") + ); +} + +/** + * @class Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * 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); + } + + 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; + } + + 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); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + 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); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + 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; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + 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; + + return true; + } + + __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); + + if (variables === null || variables === undefined) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (variables.indexOf(variable) === -1) { + variables.push(variable); + } + } + + __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); + } + } + + __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) { + + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __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; + + 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; + } + + /** + * 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; + } + + 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 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: [] + }; + } + + __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); + } + } + + // 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 + )); + + } + + this.implicit.left = this.__left; + + 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); + } +} + +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; + } +} + +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + 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; + + return this.upper; + } +} + +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); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + 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; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __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) { + + // 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 : */ + + +/***/ }), + +/***/ 17631: +/***/ ((module) => { + +"use strict"; +/* + 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. +*/ + + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ +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 = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +module.exports = Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ 10277: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + 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__(19449); + + 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 || {}; + + 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; + } + } + + /* 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; + } + + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } + + 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); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = __webpack_require__(12029).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 : */ + + +/***/ }), + +/***/ 19449: +/***/ ((__unused_webpack_module, exports) => { + +/* + 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; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + 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; + } + + 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 = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + 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; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + 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); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // 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; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // 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; + + 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; + }; + + // 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); + }; + + // 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; + } + + 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; + } + + 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; + + this.__initialize(root, visitor); + + 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)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + 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 + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + 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; + } + + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + 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; + + // 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.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, 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); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + 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; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + 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); + + 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 + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + 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); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + 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]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + 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)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + 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; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + 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.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 : */ + + +/***/ }), + +/***/ 83798: +/***/ ((module) => { + +"use strict"; + + +class LoadingLoaderError extends Error { + constructor(message) { + super(message); + this.name = "LoaderRunnerError"; + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = LoadingLoaderError; + + +/***/ }), + +/***/ 67578: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +var fs = __webpack_require__(35747); +var readFile = fs.readFile.bind(fs); +var loadLoader = __webpack_require__(63395); + +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 { + 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); + } + 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); + } + +} + +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); + } + + // 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); + } + } + ); + }); +} + +function processResource(options, loaderContext, callback) { + // set loader index to last loader + loaderContext.loaderIndex = loaderContext.loaders.length - 1; + + var resourcePath = loaderContext.resourcePath; + if(resourcePath) { + loaderContext.addDependency(resourcePath); + options.readResource(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 readResource = 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("!"); + } + }); + 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; + } + }); + + // finish loader context + if(Object.preventExtensions) { + Object.preventExtensions(loaderContext); + } + + var processOptions = { + resourceBuffer: null, + readResource: readResource + }; + 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 + }); + }); +}; + + +/***/ }), + +/***/ 63395: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var LoaderLoadingError = __webpack_require__(83798); +var url; + +module.exports = function loadLoader(loader, callback) { + if(loader.type === "module") { + try { + if(url === undefined) url = __webpack_require__(78835); + 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(); +} + + +/***/ }), + +/***/ 11060: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = __webpack_require__(53243) + + +/***/ }), + +/***/ 19338: +/***/ ((__unused_webpack_module, 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__(11060) +var extname = __webpack_require__(85622).extname + +/** + * Module variables. + * @private + */ + +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) + +// 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 +} + +/** + * 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 + } + + // 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +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 + } + + // mime -> extensions + extensions[type] = exts + + // 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) + + 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 + } + }) +} + + +/***/ }), + +/***/ 17683: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const path = __webpack_require__(85622); +const findUp = __webpack_require__(14442); + +const pkgDir = async cwd => { + const filePath = await findUp('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; + +module.exports = pkgDir; + +module.exports.sync = cwd => { + const filePath = findUp.sync('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; + + +/***/ }), + +/***/ 79882: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ + + + +var randomBytes = __webpack_require__(79822); + +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B)-' + UID + '-(\\d+)__@"', 'g'); + +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; + +var RESERVED_SYMBOLS = ['*', 'async']; + +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; +} + +function generateUID() { + var bytes = randomBytes(UID_LENGTH); + var result = ''; + for(var i=0; i arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); + + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } + + // arrow functions + return serializedFn; + } + + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } + + var str; + + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0) { + return str; + } + + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } + + if (type === 'D') { + return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; + } + + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } + + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } + + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } + + if (type === 'A') { + return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")"; + } + + if (type === 'U') { + return 'undefined' + } + + if (type === 'I') { + return infinities[valueIndex]; + } + + if (type === 'B') { + return "BigInt(\"" + bigInts[valueIndex] + "\")"; + } + + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); +} + + +/***/ }), + +/***/ 28339: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +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; + } +} + +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; + + +/***/ }), + +/***/ 82890: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +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; + + +/***/ }), + +/***/ 97681: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +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 + }); + } +} + +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; + + +/***/ }), + +/***/ 45146: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +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; +} + +AsyncSeriesHook.prototype = null; + +module.exports = AsyncSeriesHook; + + +/***/ }), + +/***/ 5463: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +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; +} + +AsyncSeriesLoopHook.prototype = null; + +module.exports = AsyncSeriesLoopHook; + + +/***/ }), + +/***/ 73448: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +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 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; + + +/***/ }), + +/***/ 36591: +/***/ ((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__(31669); + +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; + } + + 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; + } +} + +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; + + +/***/ }), + +/***/ 85572: +/***/ ((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; + } + + 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; + } + + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); + } + + /** + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options + */ + 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); + } + } + + 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; + } + + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; + } + + 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; + } + + 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; + } + + 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}]`; + } + + getInterceptor(idx) { + return `_interceptors[${idx}]`; + } +} + +module.exports = HookCodeFactory; + + +/***/ }), + +/***/ 81647: +/***/ ((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__(31669); + +const defaultFactory = (key, hook) => hook; + +class HookMap { + constructor(factory, name = undefined) { + this._map = new Map(); + this.name = name; + this._factory = factory; + this._interceptors = []; + } + + get(key) { + return this._map.get(key); + } + + 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 + ) + ); + } +} + +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; + + +/***/ }), + +/***/ 63708: +/***/ ((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__(36591); + +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); + } + } + + 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 = MultiHook; + + +/***/ }), + +/***/ 98034: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +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 factory = new SyncBailHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; + +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; +} + +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; + + +/***/ }), + +/***/ 35079: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +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); +}; + +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; +} + +SyncHook.prototype = null; + +module.exports = SyncHook; + + +/***/ }), + +/***/ 66953: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +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; + + +/***/ }), + +/***/ 92878: +/***/ ((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__(36591); +const HookCodeFactory = __webpack_require__(85572); + +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 + }); + } +} + +const factory = new SyncWaterfallHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +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; +} + +SyncWaterfallHook.prototype = null; + +module.exports = SyncWaterfallHook; + + +/***/ }), + +/***/ 34718: +/***/ ((__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__(35079); +exports.SyncBailHook = __webpack_require__(98034); +exports.SyncWaterfallHook = __webpack_require__(92878); +exports.SyncLoopHook = __webpack_require__(66953); +exports.AsyncParallelHook = __webpack_require__(82890); +exports.AsyncParallelBailHook = __webpack_require__(28339); +exports.AsyncSeriesHook = __webpack_require__(45146); +exports.AsyncSeriesBailHook = __webpack_require__(97681); +exports.AsyncSeriesLoopHook = __webpack_require__(5463); +exports.AsyncSeriesWaterfallHook = __webpack_require__(73448); +exports.HookMap = __webpack_require__(81647); +exports.MultiHook = __webpack_require__(63708); + + +/***/ }), + +/***/ 4214: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const plugin = __webpack_require__(28251); + +module.exports = plugin.default; + +/***/ }), + +/***/ 28251: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; + +var path = _interopRequireWildcard(__webpack_require__(85622)); + +var os = _interopRequireWildcard(__webpack_require__(12087)); + +var _sourceMap = __webpack_require__(96241); + +var _schemaUtils = __webpack_require__(79286); + +var _serializeJavascript = _interopRequireDefault(__webpack_require__(79882)); + +var terserPackageJson = _interopRequireWildcard(__webpack_require__(77861)); + +var _pLimit = _interopRequireDefault(__webpack_require__(18884)); + +var _jestWorker = _interopRequireDefault(__webpack_require__(59733)); + +var schema = _interopRequireWildcard(__webpack_require__(8128)); + +var _minify = __webpack_require__(83393); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; } + +/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ + +/** @typedef {import("webpack").Compiler} Compiler */ + +/** @typedef {import("webpack").Compilation} Compilation */ + +/** @typedef {import("webpack").Rules} Rules */ + +/** @typedef {import("webpack").Source} Source */ + +/** @typedef {import("webpack").WebpackError} WebpackError */ + +/** @typedef {import("webpack").Asset} Asset */ + +/** @typedef {import("webpack").AssetInfo} AssetInfo */ + +/** @typedef {import("terser").ECMA} TerserECMA */ + +/** @typedef {import("terser").MinifyOptions} TerserMinifyOptions */ + +/** @typedef {import("jest-worker").default} JestWorker */ + +/** @typedef {import("source-map").RawSourceMap} SourceMapRawSourceMap */ + +/** @typedef {import("./minify.js").InternalMinifyOptions} InternalMinifyOptions */ + +/** @typedef {import("./minify.js").InternalMinifyResult} InternalMinifyResult */ + +/** @typedef {JestWorker & { transform: (options: string) => InternalMinifyResult, minify: (options: InternalMinifyOptions) => InternalMinifyResult }} MinifyWorker */ + +/** @typedef {Object. | TerserMinifyOptions} MinifyOptions */ + +/** + * @callback ExtractCommentsFunction + * @param {any} astNode + * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment + * @returns {boolean} + */ + +/** + * @typedef {boolean | string | RegExp | ExtractCommentsFunction} ExtractCommentsCondition + */ + +/** + * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename + */ + +/** + * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner + */ + +/** + * @typedef {Object} ExtractCommentsObject + * @property {ExtractCommentsCondition} condition + * @property {ExtractCommentsFilename} filename + * @property {ExtractCommentsBanner} banner + */ + +/** + * @callback CustomMinifyFunction + * @param {Object.} file + * @param {SourceMapRawSourceMap} sourceMap + * @param {MinifyOptions} minifyOptions + */ + +/** + * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions + */ + +/** + * @typedef {Object} TerserPluginOptions + * @property {Rules} [test] + * @property {Rules} [include] + * @property {Rules} [exclude] + * @property {MinifyOptions} [terserOptions] + * @property {ExtractCommentsOptions} [extractComments] + * @property {boolean} [parallel] + * @property {CustomMinifyFunction} [minify] + */ +class TerserPlugin { + /** + * @param {TerserPluginOptions} options + */ + constructor(options = {}) { + (0, _schemaUtils.validate)( + /** @type {Schema} */ + schema, options, { + name: 'Terser Plugin', + baseDataPath: 'options' + }); + const { + minify, + terserOptions = {}, + test = /\.[cm]?js(\?.*)?$/i, + extractComments = true, + parallel = true, + include, + exclude + } = options; + this.options = { + test, + extractComments, + parallel, + include, + exclude, + minify, + terserOptions + }; + } + /** + * @private + * @param {any} input + * @returns {boolean} + */ + + + static isSourceMap(input) { + // All required options for `new SourceMapConsumer(...options)` + // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap + return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string'); + } + /** + * @private + * @param {Error & { line: number, col: number}} error + * @param {string} file + * @param {Compilation["requestShortener"]} [requestShortener] + * @param {SourceMapConsumer} [sourceMap] + * @returns {WebpackError} + */ + + + static buildError(error, file, requestShortener, sourceMap) { + if (error.line) { + const original = sourceMap && sourceMap.originalPositionFor({ + line: error.line, + column: error.col + }); + + if (original && original.source && requestShortener) { + return new Error(`${file} from Terser\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split('\n').slice(1).join('\n')}` : ''}`); + } + + return new Error(`${file} from Terser\n${error.message} [${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split('\n').slice(1).join('\n')}` : ''}`); + } + + if (error.stack) { + return new Error(`${file} from Terser\n${error.stack}`); + } + + return new Error(`${file} from Terser\n${error.message}`); + } + /** + * @private + * @param {boolean} parallel + * @returns {number} + */ + + + static getAvailableNumberOfCores(parallel) { + // In some cases cpus() returns undefined + // https://github.com/nodejs/node/issues/19022 + const cpus = os.cpus() || { + length: 1 + }; + return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); + } + /** + * @param {Compiler} compiler + * @param {Compilation} compilation + * @param {Record} assets + * @param {{availableNumberOfCores: number}} optimizeOptions + * @returns {Promise} + */ + + + async optimize(compiler, compilation, assets, optimizeOptions) { + const cache = compilation.getCache('TerserWebpackPlugin'); + let numberOfAssetsForMinify = 0; + const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => { + const { + info + } = compilation.getAsset(name); // Skip double minimize assets from child compilation + + if (info.minimized) { + return false; + } + + if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined + undefined, this.options)(name)) { + return false; + } + + return true; + }).map(async name => { + const { + info, + source + } = compilation.getAsset(name); + const eTag = cache.getLazyHashedEtag(source); + const cacheItem = cache.getItemCache(name, eTag); + const output = await cacheItem.getPromise(); + + if (!output) { + numberOfAssetsForMinify += 1; + } + + return { + name, + info, + inputSource: source, + output, + cacheItem + }; + })); + /** @type {undefined | (() => MinifyWorker)} */ + + let getWorker; + /** @type {undefined | MinifyWorker} */ + + let initializedWorker; + /** @type {undefined | number} */ + + let numberOfWorkers; + + if (optimizeOptions.availableNumberOfCores > 0) { + // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory + numberOfWorkers = Math.min(numberOfAssetsForMinify, optimizeOptions.availableNumberOfCores); // eslint-disable-next-line consistent-return + + getWorker = () => { + if (initializedWorker) { + return initializedWorker; + } + + initializedWorker = + /** @type {MinifyWorker} */ + new _jestWorker.default(__webpack_require__.ab + "minify.js", { + numWorkers: numberOfWorkers, + enableWorkerThreads: true + }); // https://github.com/facebook/jest/issues/8872#issuecomment-524822081 + + const workerStdout = initializedWorker.getStdout(); + + if (workerStdout) { + workerStdout.on('data', chunk => { + return process.stdout.write(chunk); + }); + } + + const workerStderr = initializedWorker.getStderr(); + + if (workerStderr) { + workerStderr.on('data', chunk => { + return process.stderr.write(chunk); + }); + } + + return initializedWorker; + }; + } + + const limit = (0, _pLimit.default)(getWorker && numberOfAssetsForMinify > 0 ? + /** @type {number} */ + numberOfWorkers : Infinity); + const { + SourceMapSource, + ConcatSource, + RawSource + } = compiler.webpack.sources; + const allExtractedComments = new Map(); + const scheduledTasks = []; + + for (const asset of assetsForMinify) { + scheduledTasks.push(limit(async () => { + const { + name, + inputSource, + info, + cacheItem + } = asset; + let { + output + } = asset; + + if (!output) { + let input; + let inputSourceMap; + const { + source: sourceFromInputSource, + map + } = inputSource.sourceAndMap(); + input = sourceFromInputSource; + + if (map) { + if (TerserPlugin.isSourceMap(map)) { + inputSourceMap = map; + } else { + inputSourceMap = map; + compilation.warnings.push( + /** @type {WebpackError} */ + new Error(`${name} contains invalid source map`)); + } + } + + if (Buffer.isBuffer(input)) { + input = input.toString(); + } + + const options = { + name, + input, + inputSourceMap, + minify: this.options.minify, + minifyOptions: { ...this.options.terserOptions + }, + extractComments: this.options.extractComments + }; + + if (typeof options.minifyOptions.module === 'undefined') { + if (typeof info.javascriptModule !== 'undefined') { + options.minifyOptions.module = info.javascriptModule; + } else if (/\.mjs(\?.*)?$/i.test(name)) { + options.minifyOptions.module = true; + } else if (/\.cjs(\?.*)?$/i.test(name)) { + options.minifyOptions.module = false; + } + } + + try { + output = await (getWorker ? getWorker().transform((0, _serializeJavascript.default)(options)) : (0, _minify.minify)(options)); + } catch (error) { + const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap); + compilation.errors.push(TerserPlugin.buildError(error, name, // eslint-disable-next-line no-undefined + hasSourceMap ? compilation.requestShortener : undefined, hasSourceMap ? new _sourceMap.SourceMapConsumer( + /** @type {SourceMapRawSourceMap} */ + inputSourceMap) : // eslint-disable-next-line no-undefined + undefined)); + return; + } + + let shebang; + + if ( + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith('#!')) { + const firstNewlinePosition = output.code.indexOf('\n'); + shebang = output.code.substring(0, firstNewlinePosition); + output.code = output.code.substring(firstNewlinePosition + 1); + } + + if (output.map) { + output.source = new SourceMapSource(output.code, name, output.map, input, + /** @type {SourceMapRawSourceMap} */ + inputSourceMap, true); + } else { + output.source = new RawSource(output.code); + } + + if (output.extractedComments && output.extractedComments.length > 0) { + const commentsFilename = + /** @type {ExtractCommentsObject} */ + this.options.extractComments.filename || '[file].LICENSE.txt[query]'; + let query = ''; + let filename = name; + const querySplit = filename.indexOf('?'); + + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } + + const lastSlashIndex = filename.lastIndexOf('/'); + const basename = lastSlashIndex === -1 ? filename : filename.substr(lastSlashIndex + 1); + const data = { + filename, + basename, + query + }; + output.commentsFilename = compilation.getPath(commentsFilename, data); + let banner; // Add a banner to the original file + + if ( + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false) { + banner = + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, '/')}`; + + if (typeof banner === 'function') { + banner = banner(output.commentsFilename); + } + + if (banner) { + output.source = new ConcatSource(shebang ? `${shebang}\n` : '', `/*! ${banner} */\n`, output.source); + } + } + + const extractedCommentsString = output.extractedComments.sort().join('\n\n'); + output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`); + } + + await cacheItem.storePromise({ + source: output.source, + commentsFilename: output.commentsFilename, + extractedCommentsSource: output.extractedCommentsSource + }); + } + /** @type {AssetInfo} */ + + + const newInfo = { + minimized: true + }; + const { + source, + extractedCommentsSource + } = output; // Write extracted comments to commentsFilename + + if (extractedCommentsSource) { + const { + commentsFilename + } = output; + newInfo.related = { + license: commentsFilename + }; + allExtractedComments.set(name, { + extractedCommentsSource, + commentsFilename + }); + } + + compilation.updateAsset(name, source, newInfo); + })); + } + + await Promise.all(scheduledTasks); + + if (initializedWorker) { + await initializedWorker.end(); + } + + await Array.from(allExtractedComments).sort().reduce( + /** + * @param {Promise} previousPromise + * @param {any} extractedComments + * @returns {Promise} + */ + async (previousPromise, [from, value]) => { + const previous = await previousPromise; + const { + commentsFilename, + extractedCommentsSource + } = value; + + if (previous && previous.commentsFilename === commentsFilename) { + const { + from: previousFrom, + source: prevSource + } = previous; + const mergedName = `${previousFrom}|${from}`; + const name = `${commentsFilename}|${mergedName}`; + const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue)); + let source = await cache.getPromise(name, eTag); + + if (!source) { + source = new ConcatSource(Array.from(new Set([...prevSource.source().split('\n\n'), ...extractedCommentsSource.source().split('\n\n')])).join('\n\n')); + await cache.storePromise(name, eTag, source); + } + + compilation.updateAsset(commentsFilename, source); + return { + commentsFilename, + from: mergedName, + source + }; + } + + const existingAsset = compilation.getAsset(commentsFilename); + + if (existingAsset) { + return { + commentsFilename, + from: commentsFilename, + source: existingAsset.source + }; + } + + compilation.emitAsset(commentsFilename, extractedCommentsSource); + return { + commentsFilename, + from, + source: extractedCommentsSource + }; + }, Promise.resolve()); + } + /** + * @private + * @param {any} environment + * @returns {TerserECMA} + */ + + + static getEcmaVersion(environment) { + // ES 6th + if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) { + return 2015; + } // ES 11th + + + if (environment.bigIntLiteral || environment.dynamicImport) { + return 2020; + } + + return 5; + } + /** + * @param {Compiler} compiler + * @returns {void} + */ + + + apply(compiler) { + const { + output + } = compiler.options; + + if (typeof this.options.terserOptions.ecma === 'undefined') { + this.options.terserOptions.ecma = TerserPlugin.getEcmaVersion(output.environment || {}); + } + + const pluginName = this.constructor.name; + const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel); + compiler.hooks.compilation.tap(pluginName, compilation => { + const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation); + const data = (0, _serializeJavascript.default)({ + terser: terserPackageJson.version, + terserOptions: this.options.terserOptions + }); + hooks.chunkHash.tap(pluginName, (chunk, hash) => { + hash.update('TerserPlugin'); + hash.update(data); + }); + compilation.hooks.processAssets.tapPromise({ + name: pluginName, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + }, assets => this.optimize(compiler, compilation, assets, { + availableNumberOfCores + })); + compilation.hooks.statsPrinter.tap(pluginName, stats => { + stats.hooks.print.for('asset.info.minimized').tap('terser-webpack-plugin', (minimized, { + green, + formatFlag + }) => // eslint-disable-next-line no-undefined + minimized ? green(formatFlag('minimized')) : undefined); + }); + }); + } + +} + +var _default = TerserPlugin; +exports.default = _default; + +/***/ }), + +/***/ 83393: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); + + +const { + minify: terserMinify +} = __webpack_require__(54775); +/** @typedef {import("source-map").RawSourceMap} RawSourceMap */ + +/** @typedef {import("./index.js").ExtractCommentsOptions} ExtractCommentsOptions */ + +/** @typedef {import("./index.js").CustomMinifyFunction} CustomMinifyFunction */ + +/** @typedef {import("./index.js").MinifyOptions} MinifyOptions */ + +/** @typedef {import("terser").MinifyOptions} TerserMinifyOptions */ + +/** @typedef {import("terser").MinifyOutput} MinifyOutput */ + +/** @typedef {import("terser").FormatOptions} FormatOptions */ + +/** @typedef {import("terser").MangleOptions} MangleOptions */ + +/** @typedef {import("./index.js").ExtractCommentsFunction} ExtractCommentsFunction */ + +/** @typedef {import("./index.js").ExtractCommentsCondition} ExtractCommentsCondition */ + +/** + * @typedef {Object} InternalMinifyOptions + * @property {string} name + * @property {string} input + * @property {RawSourceMap} inputSourceMap + * @property {ExtractCommentsOptions} extractComments + * @property {CustomMinifyFunction} minify + * @property {MinifyOptions} minifyOptions + */ + +/** + * @typedef {Array} ExtractedComments + */ + +/** + * @typedef {Promise} InternalMinifyResult + */ + +/** + * @typedef {TerserMinifyOptions & { sourceMap: undefined } & ({ output: FormatOptions & { beautify: boolean } } | { format: FormatOptions & { beautify: boolean } })} NormalizedTerserMinifyOptions + */ + +/** + * @param {TerserMinifyOptions} [terserOptions={}] + * @returns {NormalizedTerserMinifyOptions} + */ + + +function buildTerserOptions(terserOptions = {}) { + return { ...terserOptions, + mangle: terserOptions.mangle == null ? true : typeof terserOptions.mangle === 'boolean' ? terserOptions.mangle : { ...terserOptions.mangle + }, + // Ignoring sourceMap from options + // eslint-disable-next-line no-undefined + sourceMap: undefined, + // the `output` option is deprecated + ...(terserOptions.format ? { + format: { + beautify: false, + ...terserOptions.format + } + } : { + output: { + beautify: false, + ...terserOptions.output + } + }) + }; +} +/** + * @param {any} value + * @returns {boolean} + */ + + +function isObject(value) { + const type = typeof value; + return value != null && (type === 'object' || type === 'function'); +} +/** + * @param {ExtractCommentsOptions} extractComments + * @param {NormalizedTerserMinifyOptions} terserOptions + * @param {ExtractedComments} extractedComments + * @returns {ExtractCommentsFunction} + */ + + +function buildComments(extractComments, terserOptions, extractedComments) { + /** @type {{ [index: string]: ExtractCommentsCondition }} */ + const condition = {}; + let comments; + + if (terserOptions.format) { + ({ + comments + } = terserOptions.format); + } else if (terserOptions.output) { + ({ + comments + } = terserOptions.output); + } + + condition.preserve = typeof comments !== 'undefined' ? comments : false; + + if (typeof extractComments === 'boolean' && extractComments) { + condition.extract = 'some'; + } else if (typeof extractComments === 'string' || extractComments instanceof RegExp) { + condition.extract = extractComments; + } else if (typeof extractComments === 'function') { + condition.extract = extractComments; + } else if (extractComments && isObject(extractComments)) { + condition.extract = typeof extractComments.condition === 'boolean' && extractComments.condition ? 'some' : typeof extractComments.condition !== 'undefined' ? extractComments.condition : 'some'; + } else { + // No extract + // Preserve using "commentsOpts" or "some" + condition.preserve = typeof comments !== 'undefined' ? comments : 'some'; + condition.extract = false; + } // Ensure that both conditions are functions + + + ['preserve', 'extract'].forEach(key => { + /** @type {undefined | string} */ + let regexStr; + /** @type {undefined | RegExp} */ + + let regex; + + switch (typeof condition[key]) { + case 'boolean': + condition[key] = condition[key] ? () => true : () => false; + break; + + case 'function': + break; + + case 'string': + if (condition[key] === 'all') { + condition[key] = () => true; + + break; + } + + if (condition[key] === 'some') { + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => { + return (comment.type === 'comment2' || comment.type === 'comment1') && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value); + }; + + break; + } + + regexStr = + /** @type {string} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => { + return new RegExp( + /** @type {string} */ + regexStr).test(comment.value); + }; + + break; + + default: + regex = + /** @type {RegExp} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => + /** @type {RegExp} */ + regex.test(comment.value); + + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions + + return (astNode, comment) => { + if ( + /** @type {{ extract: ExtractCommentsFunction }} */ + condition.extract(astNode, comment)) { + const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + + return ( + /** @type {{ preserve: ExtractCommentsFunction }} */ + condition.preserve(astNode, comment) + ); + }; +} +/** + * @param {InternalMinifyOptions} options + * @returns {InternalMinifyResult} + */ + + +async function minify(options) { + const { + name, + input, + inputSourceMap, + minify: minifyFn, + minifyOptions + } = options; + + if (minifyFn) { + return minifyFn({ + [name]: input + }, inputSourceMap, minifyOptions); + } // Copy terser options + + + const terserOptions = buildTerserOptions(minifyOptions); // Let terser generate a SourceMap + + if (inputSourceMap) { + // @ts-ignore + terserOptions.sourceMap = { + asObject: true + }; + } + /** @type {ExtractedComments} */ + + + const extractedComments = []; + const { + extractComments + } = options; + + if (terserOptions.output) { + terserOptions.output.comments = buildComments(extractComments, terserOptions, extractedComments); + } else if (terserOptions.format) { + terserOptions.format.comments = buildComments(extractComments, terserOptions, extractedComments); + } + + const result = await terserMinify({ + [name]: input + }, terserOptions); + return { ...result, + extractedComments + }; +} +/** + * @param {string} options + * @returns {InternalMinifyResult} + */ + + +function transform(options) { + // 'use strict' => this === undefined (Clean Scope) + // Safer for possible security issues, albeit not critical at all here + // eslint-disable-next-line no-param-reassign + const evaluatedOptions = + /** @type {InternalMinifyOptions} */ + // eslint-disable-next-line no-new-func + new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname); + return minify(evaluatedOptions); +} + +module.exports.minify = minify; +module.exports.transform = transform; + +/***/ }), + +/***/ 39144: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const EventEmitter = __webpack_require__(28614).EventEmitter; +const fs = __webpack_require__(82161); +const path = __webpack_require__(85622); + +const watchEventSource = __webpack_require__(10547); + +const EXISTANCE_ONLY_TIME_ENTRY = Object.freeze({}); + +let FS_ACCURACY = 1000; + +const IS_OSX = __webpack_require__(12087).platform() === "darwin"; +const WATCHPACK_POLLING = process.env.WATCHPACK_POLLING; +const FORCE_POLLING = + `${+WATCHPACK_POLLING}` === WATCHPACK_POLLING + ? +WATCHPACK_POLLING + : !!WATCHPACK_POLLING && WATCHPACK_POLLING !== "false"; + +function withoutCase(str) { + return str.toLowerCase(); +} + +function needCalls(times, callback) { + return function() { + if (--times === 0) { + return callback(); + } + }; +} + +class Watcher extends EventEmitter { + constructor(directoryWatcher, filePath, startTime) { + super(); + this.directoryWatcher = directoryWatcher; + this.path = filePath; + this.startTime = startTime && +startTime; + this._cachedTimeInfoEntries = undefined; + } + + checkStartTime(mtime, initial) { + const startTime = this.startTime; + if (typeof startTime !== "number") return !initial; + return startTime <= mtime; + } + + close() { + this.emit("closed"); + } +} + +class DirectoryWatcher extends EventEmitter { + constructor(watcherManager, directoryPath, options) { + super(); + if (FORCE_POLLING) { + options.poll = FORCE_POLLING; + } + this.watcherManager = watcherManager; + this.options = options; + this.path = directoryPath; + // safeTime is the point in time after which reading is safe to be unchanged + // timestamp is a value that should be compared with another timestamp (mtime) + /** @type {Map} */ + this.filesWithoutCase = new Map(); + this.directories = new Map(); + this.lastWatchEvent = 0; + this.initialScan = true; + this.ignored = options.ignored; + this.nestedWatching = false; + this.polledWatching = + typeof options.poll === "number" + ? options.poll + : options.poll + ? 5007 + : false; + this.timeout = undefined; + this.initialScanRemoved = new Set(); + this.initialScanFinished = undefined; + /** @type {Map>} */ + this.watchers = new Map(); + this.parentWatcher = null; + this.refs = 0; + this._activeEvents = new Map(); + this.closed = false; + this.scanning = false; + this.scanAgain = false; + this.scanAgainInitial = false; + + this.createWatcher(); + this.doScan(true); + } + + checkIgnore(path) { + if (!this.ignored) return false; + path = path.replace(/\\/g, "/"); + return this.ignored.test(path); + } + + createWatcher() { + try { + if (this.polledWatching) { + this.watcher = { + close: () => { + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + } + }; + } else { + if (IS_OSX) { + this.watchInParentDirectory(); + } + this.watcher = watchEventSource.watch(this.path); + this.watcher.on("change", this.onWatchEvent.bind(this)); + this.watcher.on("error", this.onWatcherError.bind(this)); + } + } catch (err) { + this.onWatcherError(err); + } + } + + forEachWatcher(path, fn) { + const watchers = this.watchers.get(withoutCase(path)); + if (watchers !== undefined) { + for (const w of watchers) { + fn(w); + } + } + } + + setMissing(itemPath, initial, type) { + this._cachedTimeInfoEntries = undefined; + + if (this.initialScan) { + this.initialScanRemoved.add(itemPath); + } + + const oldDirectory = this.directories.get(itemPath); + if (oldDirectory) { + if (this.nestedWatching) oldDirectory.close(); + this.directories.delete(itemPath); + + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + + const oldFile = this.files.get(itemPath); + if (oldFile) { + this.files.delete(itemPath); + const key = withoutCase(itemPath); + const count = this.filesWithoutCase.get(key) - 1; + if (count <= 0) { + this.filesWithoutCase.delete(key); + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + } else { + this.filesWithoutCase.set(key, count); + } + + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + } + + setFileTime(filePath, mtime, initial, ignoreWhenEqual, type) { + const now = Date.now(); + + if (this.checkIgnore(filePath)) return; + + const old = this.files.get(filePath); + + let safeTime, accuracy; + if (initial) { + safeTime = Math.min(now, mtime) + FS_ACCURACY; + accuracy = FS_ACCURACY; + } else { + safeTime = now; + accuracy = 0; + + if (old && old.timestamp === mtime && mtime + FS_ACCURACY < now - 1000) { + // We are sure that mtime is untouched + // This can be caused by some file attribute change + // e. g. when access time has been changed + // but the file content is untouched + return; + } + } + + if (ignoreWhenEqual && old && old.timestamp === mtime) return; + + this.files.set(filePath, { + safeTime, + accuracy, + timestamp: mtime + }); + this._cachedTimeInfoEntries = undefined; + + if (!old) { + const key = withoutCase(filePath); + const count = this.filesWithoutCase.get(key); + this.filesWithoutCase.set(key, (count || 0) + 1); + if (count !== undefined) { + // There is already a file with case-insensitive-equal name + // On a case-insensitive filesystem we may miss the renaming + // when only casing is changed. + // To be sure that our information is correct + // we trigger a rescan here + this.doScan(false); + } + + this.forEachWatcher(filePath, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", mtime, type); + } + }); + } else if (!initial) { + this.forEachWatcher(filePath, w => w.emit("change", mtime, type)); + } + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", filePath, safeTime, type, initial); + } + }); + } + + setDirectory(directoryPath, birthtime, initial, type) { + if (this.checkIgnore(directoryPath)) return; + if (directoryPath === this.path) { + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", directoryPath, birthtime, type, initial) + ); + } + } else { + const old = this.directories.get(directoryPath); + if (!old) { + const now = Date.now(); + + this._cachedTimeInfoEntries = undefined; + if (this.nestedWatching) { + this.createNestedWatcher(directoryPath); + } else { + this.directories.set(directoryPath, true); + } + + let safeTime; + if (initial) { + safeTime = Math.min(now, birthtime) + FS_ACCURACY; + } else { + safeTime = now; + } + + this.forEachWatcher(directoryPath, w => { + if (!initial || w.checkStartTime(safeTime, false)) { + w.emit("change", birthtime, type); + } + }); + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", directoryPath, safeTime, type, initial); + } + }); + } + } + } + + createNestedWatcher(directoryPath) { + const watcher = this.watcherManager.watchDirectory(directoryPath, 1); + watcher.on("change", (filePath, mtime, type, initial) => { + this._cachedTimeInfoEntries = undefined; + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(mtime, initial)) { + w.emit("change", filePath, mtime, type, initial); + } + }); + }); + this.directories.set(directoryPath, watcher); + } + + setNestedWatching(flag) { + if (this.nestedWatching !== !!flag) { + this.nestedWatching = !!flag; + this._cachedTimeInfoEntries = undefined; + if (this.nestedWatching) { + for (const directory of this.directories.keys()) { + this.createNestedWatcher(directory); + } + } else { + for (const [directory, watcher] of this.directories) { + watcher.close(); + this.directories.set(directory, true); + } + } + } + } + + watch(filePath, startTime) { + const key = withoutCase(filePath); + let watchers = this.watchers.get(key); + if (watchers === undefined) { + watchers = new Set(); + this.watchers.set(key, watchers); + } + this.refs++; + const watcher = new Watcher(this, filePath, startTime); + watcher.on("closed", () => { + if (--this.refs <= 0) { + this.close(); + return; + } + watchers.delete(watcher); + if (watchers.size === 0) { + this.watchers.delete(key); + if (this.path === filePath) this.setNestedWatching(false); + } + }); + watchers.add(watcher); + let safeTime; + if (filePath === this.path) { + this.setNestedWatching(true); + safeTime = this.lastWatchEvent; + for (const entry of this.files.values()) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + } + } else { + const entry = this.files.get(filePath); + if (entry) { + fixupEntryAccuracy(entry); + safeTime = entry.safeTime; + } else { + safeTime = 0; + } + } + if (safeTime) { + if (safeTime >= startTime) { + process.nextTick(() => { + if (this.closed) return; + if (filePath === this.path) { + watcher.emit( + "change", + filePath, + safeTime, + "watch (outdated on attach)", + true + ); + } else { + watcher.emit( + "change", + safeTime, + "watch (outdated on attach)", + true + ); + } + }); + } + } else if (this.initialScan) { + if (this.initialScanRemoved.has(filePath)) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("remove"); + }); + } + } else if ( + !this.directories.has(filePath) && + watcher.checkStartTime(this.initialScanFinished, false) + ) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("initial-missing", "watch (missing on attach)"); + }); + } + return watcher; + } + + onWatchEvent(eventType, filename) { + if (this.closed) return; + if (!filename) { + // In some cases no filename is provided + // This seem to happen on windows + // So some event happened but we don't know which file is affected + // We have to do a full scan of the directory + this.doScan(false); + return; + } + + const filePath = path.join(this.path, filename); + if (this.checkIgnore(filePath)) return; + + if (this._activeEvents.get(filename) === undefined) { + this._activeEvents.set(filename, false); + const checkStats = () => { + if (this.closed) return; + this._activeEvents.set(filename, false); + fs.lstat(filePath, (err, stats) => { + if (this.closed) return; + if (this._activeEvents.get(filename) === true) { + process.nextTick(checkStats); + return; + } + this._activeEvents.delete(filename); + // ENOENT happens when the file/directory doesn't exist + // EPERM happens when the containing directory doesn't exist + if (err) { + if ( + err.code !== "ENOENT" && + err.code !== "EPERM" && + err.code !== "EBUSY" + ) { + this.onStatsError(err); + } else { + if (filename === path.basename(this.path)) { + // This may indicate that the directory itself was removed + if (!fs.existsSync(this.path)) { + this.onDirectoryRemoved("stat failed"); + } + } + } + } + this.lastWatchEvent = Date.now(); + this._cachedTimeInfoEntries = undefined; + if (!stats) { + this.setMissing(filePath, false, eventType); + } else if (stats.isDirectory()) { + this.setDirectory( + filePath, + +stats.birthtime || 1, + false, + eventType + ); + } else if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + filePath, + +stats.mtime || +stats.ctime || 1, + false, + false, + eventType + ); + } + }); + }; + process.nextTick(checkStats); + } else { + this._activeEvents.set(filename, true); + } + } + + onWatcherError(err) { + if (this.closed) return; + if (err) { + if (err.code !== "EPERM" && err.code !== "ENOENT") { + console.error("Watchpack Error (watcher): " + err); + } + this.onDirectoryRemoved("watch error"); + } + } + + onStatsError(err) { + if (err) { + console.error("Watchpack Error (stats): " + err); + } + } + + onScanError(err) { + if (err) { + console.error("Watchpack Error (initial scan): " + err); + } + this.onScanFinished(); + } + + onScanFinished() { + if (this.polledWatching) { + this.timeout = setTimeout(() => { + if (this.closed) return; + this.doScan(false); + }, this.polledWatching); + } + } + + onDirectoryRemoved(reason) { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + this.watchInParentDirectory(); + const type = `directory-removed (${reason})`; + for (const directory of this.directories.keys()) { + this.setMissing(directory, null, type); + } + for (const file of this.files.keys()) { + this.setMissing(file, null, type); + } + } + + watchInParentDirectory() { + if (!this.parentWatcher) { + const parentDir = path.dirname(this.path); + // avoid watching in the root directory + // removing directories in the root directory is not supported + if (path.dirname(parentDir) === parentDir) return; + + this.parentWatcher = this.watcherManager.watchFile(this.path, 1); + this.parentWatcher.on("change", (mtime, type) => { + if (this.closed) return; + + // On non-osx platforms we don't need this watcher to detect + // directory removal, as an EPERM error indicates that + if ((!IS_OSX || this.polledWatching) && this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + // Try to create the watcher when parent directory is found + if (!this.watcher) { + this.createWatcher(); + this.doScan(false); + + // directory was created so we emit an event + this.forEachWatcher(this.path, w => + w.emit("change", this.path, mtime, type, false) + ); + } + }); + this.parentWatcher.on("remove", () => { + this.onDirectoryRemoved("parent directory removed"); + }); + } + } + + doScan(initial) { + if (this.scanning) { + if (this.scanAgain) { + if (!initial) this.scanAgainInitial = false; + } else { + this.scanAgain = true; + this.scanAgainInitial = initial; + } + return; + } + this.scanning = true; + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + process.nextTick(() => { + if (this.closed) return; + fs.readdir(this.path, (err, items) => { + if (this.closed) return; + if (err) { + if (err.code === "ENOENT" || err.code === "EPERM") { + this.onDirectoryRemoved("scan readdir failed"); + } else { + this.onScanError(err); + } + this.initialScan = false; + this.initialScanFinished = Date.now(); + if (initial) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (parent directory missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + } + return; + } + const itemPaths = new Set( + items.map(item => path.join(this.path, item.normalize("NFC"))) + ); + for (const file of this.files.keys()) { + if (!itemPaths.has(file)) { + this.setMissing(file, initial, "scan (missing)"); + } + } + for (const directory of this.directories.keys()) { + if (!itemPaths.has(directory)) { + this.setMissing(directory, initial, "scan (missing)"); + } + } + if (this.scanAgain) { + // Early repeat of scan + this.scanAgain = false; + this.doScan(initial); + return; + } + const itemFinished = needCalls(itemPaths.size + 1, () => { + if (this.closed) return; + this.initialScan = false; + this.initialScanRemoved = null; + this.initialScanFinished = Date.now(); + if (initial) { + const missingWatchers = new Map(this.watchers); + missingWatchers.delete(withoutCase(this.path)); + for (const item of itemPaths) { + missingWatchers.delete(withoutCase(item)); + } + for (const watchers of missingWatchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + this.onScanFinished(); + } + }); + for (const itemPath of itemPaths) { + fs.lstat(itemPath, (err2, stats) => { + if (this.closed) return; + if (err2) { + if ( + err2.code === "ENOENT" || + err2.code === "EPERM" || + err2.code === "EBUSY" + ) { + this.setMissing(itemPath, initial, "scan (" + err2.code + ")"); + } else { + this.onScanError(err2); + } + itemFinished(); + return; + } + if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + itemPath, + +stats.mtime || +stats.ctime || 1, + initial, + true, + "scan (file)" + ); + } else if (stats.isDirectory()) { + if (!initial || !this.directories.has(itemPath)) + this.setDirectory( + itemPath, + +stats.birthtime || 1, + initial, + "scan (dir)" + ); + } + itemFinished(); + }); + } + itemFinished(); + }); + }); + } + + getTimes() { + const obj = Object.create(null); + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + obj[file] = Math.max(entry.safeTime, entry.timestamp); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + const times = w.directoryWatcher.getTimes(); + for (const file of Object.keys(times)) { + const time = times[file]; + safeTime = Math.max(safeTime, time); + obj[file] = time; + } + } + obj[this.path] = safeTime; + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!Object.prototype.hasOwnProperty.call(obj, path)) { + obj[path] = null; + } + } + } + } + return obj; + } + + getTimeInfoEntries() { + if (this._cachedTimeInfoEntries !== undefined) + return this._cachedTimeInfoEntries; + const map = new Map(); + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + map.set(file, entry); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + const timeInfoEntries = w.directoryWatcher.getTimeInfoEntries(); + for (const [file, entry] of timeInfoEntries) { + if (entry) { + safeTime = Math.max(safeTime, entry.safeTime); + } + map.set(file, entry); + } + } + map.set(this.path, { + safeTime + }); + } else { + for (const dir of this.directories.keys()) { + // No additional info about this directory + map.set(dir, EXISTANCE_ONLY_TIME_ENTRY); + } + map.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!map.has(path)) { + map.set(path, null); + } + } + } + this._cachedTimeInfoEntries = map; + } + return map; + } + + close() { + this.closed = true; + this.initialScan = false; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + w.close(); + } + this.directories.clear(); + } + if (this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + this.emit("closed"); + } +} + +module.exports = DirectoryWatcher; +module.exports.EXISTANCE_ONLY_TIME_ENTRY = EXISTANCE_ONLY_TIME_ENTRY; + +function fixupEntryAccuracy(entry) { + if (entry.accuracy > FS_ACCURACY) { + entry.safeTime = entry.safeTime - entry.accuracy + FS_ACCURACY; + entry.accuracy = FS_ACCURACY; + } +} + +function ensureFsAccuracy(mtime) { + if (!mtime) return; + if (FS_ACCURACY > 1 && mtime % 1 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 10 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 100 !== 0) FS_ACCURACY = 100; +} + + +/***/ }), + +/***/ 56083: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); + +const EXPECTED_ERRORS = new Set( + process.platform === "win32" ? ["EINVAL", "ENOENT", "UNKNOWN"] : ["EINVAL"] +); + +class LinkResolver { + constructor() { + this.cache = new Map(); + } + + /** + * @param {string} file path to file or directory + * @returns {string[]} array of file and all symlinks contributed in the resolving process (first item is the resolved file) + */ + resolve(file) { + const cacheEntry = this.cache.get(file); + if (cacheEntry !== undefined) { + return cacheEntry; + } + const parent = path.dirname(file); + if (parent === file) { + // At root of filesystem there can't be a link + const result = Object.freeze([file]); + this.cache.set(file, result); + return result; + } + // resolve the parent directory to find links there and get the real path + const parentResolved = this.resolve(parent); + let realFile = file; + + // is the parent directory really somewhere else? + if (parentResolved[0] !== parent) { + // get the real location of file + const basename = path.basename(file); + realFile = path.resolve(parentResolved[0], basename); + } + // try to read the link content + try { + const linkContent = fs.readlinkSync(realFile); + + // resolve the link content relative to the parent directory + const resolvedLink = path.resolve(parentResolved[0], linkContent); + + // recursive resolve the link content for more links in the structure + const linkResolved = this.resolve(resolvedLink); + + // merge parent and link resolve results + let result; + if (linkResolved.length > 1 && parentResolved.length > 1) { + // when both contain links we need to duplicate them with a Set + const resultSet = new Set(linkResolved); + // add the link + resultSet.add(realFile); + // add all symlinks of the parent + for (let i = 1; i < parentResolved.length; i++) { + resultSet.add(parentResolved[i]); + } + result = Object.freeze(Array.from(resultSet)); + } else if (parentResolved.length > 1) { + // we have links in the parent but not for the link content location + result = parentResolved.slice(); + result[0] = linkResolved[0]; + // add the link + result.push(realFile); + Object.freeze(result); + } else if (linkResolved.length > 1) { + // we can return the link content location result + result = linkResolved.slice(); + // add the link + result.push(realFile); + Object.freeze(result); + } else { + // neither link content location nor parent have links + // this link is the only link here + result = Object.freeze([ + // the resolve real location + linkResolved[0], + // add the link + realFile + ]); + } + this.cache.set(file, result); + return result; + } catch (e) { + if (!EXPECTED_ERRORS.has(e.code)) { + throw e; + } + // no link + const result = parentResolved.slice(); + result[0] = realFile; + Object.freeze(result); + this.cache.set(file, result); + return result; + } + } +} +module.exports = LinkResolver; + + +/***/ }), + +/***/ 29539: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const DirectoryWatcher = __webpack_require__(39144); + +class WatcherManager { + constructor(options) { + this.options = options; + this.directoryWatchers = new Map(); + } + + getDirectoryWatcher(directory) { + const watcher = this.directoryWatchers.get(directory); + if (watcher === undefined) { + const newWatcher = new DirectoryWatcher(this, directory, this.options); + this.directoryWatchers.set(directory, newWatcher); + newWatcher.on("closed", () => { + this.directoryWatchers.delete(directory); + }); + return newWatcher; + } + return watcher; + } + + watchFile(p, startTime) { + const directory = path.dirname(p); + if (directory === p) return null; + return this.getDirectoryWatcher(directory).watch(p, startTime); + } + + watchDirectory(directory, startTime) { + return this.getDirectoryWatcher(directory).watch(directory, startTime); + } +} + +const watcherManagers = new WeakMap(); +/** + * @param {object} options options + * @returns {WatcherManager} the watcher manager + */ +module.exports = options => { + const watcherManager = watcherManagers.get(options); + if (watcherManager !== undefined) return watcherManager; + const newWatcherManager = new WatcherManager(options); + watcherManagers.set(options, newWatcherManager); + return newWatcherManager; +}; +module.exports.WatcherManager = WatcherManager; + + +/***/ }), + +/***/ 89946: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); + +/** + * @template T + * @typedef {Object} TreeNode + * @property {string} filePath + * @property {TreeNode} parent + * @property {TreeNode[]} children + * @property {number} entries + * @property {boolean} active + * @property {T[] | T | undefined} value + */ + +/** + * @template T + * @param {Map>} the new plan + */ +module.exports = (plan, limit) => { + const treeMap = new Map(); + // Convert to tree + for (const [filePath, value] of plan) { + treeMap.set(filePath, { + filePath, + parent: undefined, + children: undefined, + entries: 1, + active: true, + value + }); + } + let currentCount = treeMap.size; + // Create parents and calculate sum of entries + for (const node of treeMap.values()) { + const parentPath = path.dirname(node.filePath); + if (parentPath !== node.filePath) { + let parent = treeMap.get(parentPath); + if (parent === undefined) { + parent = { + filePath: parentPath, + parent: undefined, + children: [node], + entries: node.entries, + active: false, + value: undefined + }; + treeMap.set(parentPath, parent); + node.parent = parent; + } else { + node.parent = parent; + if (parent.children === undefined) { + parent.children = [node]; + } else { + parent.children.push(node); + } + do { + parent.entries += node.entries; + parent = parent.parent; + } while (parent); + } + } + } + // Reduce until limit reached + while (currentCount > limit) { + // Select node that helps reaching the limit most effectively without overmerging + const overLimit = currentCount - limit; + let bestNode = undefined; + let bestCost = Infinity; + for (const node of treeMap.values()) { + if (node.entries <= 1 || !node.children || !node.parent) continue; + if (node.children.length === 0) continue; + if (node.children.length === 1 && !node.value) continue; + // Try to select the node with has just a bit more entries than we need to reduce + // When just a bit more is over 30% over the limit, + // also consider just a bit less entries then we need to reduce + const cost = + node.entries - 1 >= overLimit + ? node.entries - 1 - overLimit + : overLimit - node.entries + 1 + limit * 0.3; + if (cost < bestCost) { + bestNode = node; + bestCost = cost; + } + } + if (!bestNode) break; + // Merge all children + const reduction = bestNode.entries - 1; + bestNode.active = true; + bestNode.entries = 1; + currentCount -= reduction; + let parent = bestNode.parent; + while (parent) { + parent.entries -= reduction; + parent = parent.parent; + } + const queue = new Set(bestNode.children); + for (const node of queue) { + node.active = false; + node.entries = 0; + if (node.children) { + for (const child of node.children) queue.add(child); + } + } + } + // Write down new plan + const newPlan = new Map(); + for (const rootNode of treeMap.values()) { + if (!rootNode.active) continue; + const map = new Map(); + const queue = new Set([rootNode]); + for (const node of queue) { + if (node.active && node !== rootNode) continue; + if (node.value) { + if (Array.isArray(node.value)) { + for (const item of node.value) { + map.set(item, node.filePath); + } + } else { + map.set(node.value, node.filePath); + } + } + if (node.children) { + for (const child of node.children) { + queue.add(child); + } + } + } + newPlan.set(rootNode.filePath, map); + } + return newPlan; +}; + + +/***/ }), + +/***/ 10547: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const { EventEmitter } = __webpack_require__(28614); +const reducePlan = __webpack_require__(89946); + +const IS_OSX = __webpack_require__(12087).platform() === "darwin"; +const IS_WIN = __webpack_require__(12087).platform() === "win32"; +const SUPPORTS_RECURSIVE_WATCHING = IS_OSX || IS_WIN; + +const watcherLimit = + +process.env.WATCHPACK_WATCHER_LIMIT || (IS_OSX ? 2000 : 10000); + +const recursiveWatcherLogging = !!process.env + .WATCHPACK_RECURSIVE_WATCHER_LOGGING; + +let isBatch = false; +let watcherCount = 0; + +/** @type {Map} */ +const pendingWatchers = new Map(); + +/** @type {Map} */ +const recursiveWatchers = new Map(); + +/** @type {Map} */ +const directWatchers = new Map(); + +/** @type {Map} */ +const underlyingWatcher = new Map(); + +class DirectWatcher { + constructor(filePath) { + this.filePath = filePath; + this.watchers = new Set(); + this.watcher = undefined; + try { + const watcher = fs.watch(filePath); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + for (const w of this.watchers) { + w.emit("change", type, filename); + } + }); + watcher.on("error", error => { + for (const w of this.watchers) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.watchers) { + w.emit("error", err); + } + }); + } + watcherCount++; + } + + add(watcher) { + underlyingWatcher.set(watcher, this); + this.watchers.add(watcher); + } + + remove(watcher) { + this.watchers.delete(watcher); + if (this.watchers.size === 0) { + directWatchers.delete(this.filePath); + watcherCount--; + if (this.watcher) this.watcher.close(); + } + } + + getWatchers() { + return this.watchers; + } +} + +class RecursiveWatcher { + constructor(rootPath) { + this.rootPath = rootPath; + /** @type {Map} */ + this.mapWatcherToPath = new Map(); + /** @type {Map>} */ + this.mapPathToWatchers = new Map(); + this.watcher = undefined; + try { + const watcher = fs.watch(rootPath, { + recursive: true + }); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + if (!filename) { + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${ + this.rootPath + }) to all watchers\n` + ); + } + for (const w of this.mapWatcherToPath.keys()) { + w.emit("change", type); + } + } else { + const dir = path.dirname(filename); + const watchers = this.mapPathToWatchers.get(dir); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${ + this.rootPath + }) for '${filename}' to ${ + watchers ? watchers.size : 0 + } watchers\n` + ); + } + if (watchers === undefined) return; + for (const w of watchers) { + w.emit("change", type, path.basename(filename)); + } + } + }); + watcher.on("error", error => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", err); + } + }); + } + watcherCount++; + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] created recursive watcher at ${rootPath}\n` + ); + } + } + + add(filePath, watcher) { + underlyingWatcher.set(watcher, this); + const subpath = filePath.slice(this.rootPath.length + 1) || "."; + this.mapWatcherToPath.set(watcher, subpath); + const set = this.mapPathToWatchers.get(subpath); + if (set === undefined) { + const newSet = new Set(); + newSet.add(watcher); + this.mapPathToWatchers.set(subpath, newSet); + } else { + set.add(watcher); + } + } + + remove(watcher) { + const subpath = this.mapWatcherToPath.get(watcher); + if (!subpath) return; + this.mapWatcherToPath.delete(watcher); + const set = this.mapPathToWatchers.get(subpath); + set.delete(watcher); + if (set.size === 0) { + this.mapPathToWatchers.delete(subpath); + } + if (this.mapWatcherToPath.size === 0) { + recursiveWatchers.delete(this.rootPath); + watcherCount--; + if (this.watcher) this.watcher.close(); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] closed recursive watcher at ${this.rootPath}\n` + ); + } + } + } + + getWatchers() { + return this.mapWatcherToPath; + } +} + +class Watcher extends EventEmitter { + close() { + if (pendingWatchers.has(this)) { + pendingWatchers.delete(this); + return; + } + const watcher = underlyingWatcher.get(this); + watcher.remove(this); + underlyingWatcher.delete(this); + } +} + +const createDirectWatcher = filePath => { + const existing = directWatchers.get(filePath); + if (existing !== undefined) return existing; + const w = new DirectWatcher(filePath); + directWatchers.set(filePath, w); + return w; +}; + +const createRecursiveWatcher = rootPath => { + const existing = recursiveWatchers.get(rootPath); + if (existing !== undefined) return existing; + const w = new RecursiveWatcher(rootPath); + recursiveWatchers.set(rootPath, w); + return w; +}; + +const execute = () => { + /** @type {Map} */ + const map = new Map(); + const addWatcher = (watcher, filePath) => { + const entry = map.get(filePath); + if (entry === undefined) { + map.set(filePath, watcher); + } else if (Array.isArray(entry)) { + entry.push(watcher); + } else { + map.set(filePath, [entry, watcher]); + } + }; + for (const [watcher, filePath] of pendingWatchers) { + addWatcher(watcher, filePath); + } + pendingWatchers.clear(); + + // Fast case when we are not reaching the limit + if (!SUPPORTS_RECURSIVE_WATCHING || watcherLimit - watcherCount >= map.size) { + // Create watchers for all entries in the map + for (const [filePath, entry] of map) { + const w = createDirectWatcher(filePath); + if (Array.isArray(entry)) { + for (const item of entry) w.add(item); + } else { + w.add(entry); + } + } + return; + } + + // Reconsider existing watchers to improving watch plan + for (const watcher of recursiveWatchers.values()) { + for (const [w, subpath] of watcher.getWatchers()) { + addWatcher(w, path.join(watcher.rootPath, subpath)); + } + } + for (const watcher of directWatchers.values()) { + for (const w of watcher.getWatchers()) { + addWatcher(w, watcher.filePath); + } + } + + // Merge map entries to keep watcher limit + // Create a 10% buffer to be able to enter fast case more often + const plan = reducePlan(map, watcherLimit * 0.9); + + // Update watchers for all entries in the map + for (const [filePath, entry] of plan) { + if (entry.size === 1) { + for (const [watcher, filePath] of entry) { + const w = createDirectWatcher(filePath); + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + const filePaths = new Set(entry.values()); + if (filePaths.size > 1) { + const w = createRecursiveWatcher(filePath); + for (const [watcher, watcherPath] of entry) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcherPath, watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + for (const filePath of filePaths) { + const w = createDirectWatcher(filePath); + for (const watcher of entry.keys()) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } + } + } + } +}; + +exports.watch = filePath => { + const watcher = new Watcher(); + // Find an existing watcher + const directWatcher = directWatchers.get(filePath); + if (directWatcher !== undefined) { + directWatcher.add(watcher); + return watcher; + } + let current = filePath; + for (;;) { + const recursiveWatcher = recursiveWatchers.get(current); + if (recursiveWatcher !== undefined) { + recursiveWatcher.add(filePath, watcher); + return watcher; + } + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + // Queue up watcher for creation + pendingWatchers.set(watcher, filePath); + if (!isBatch) execute(); + return watcher; +}; + +exports.batch = fn => { + isBatch = true; + try { + fn(); + } finally { + isBatch = false; + execute(); + } +}; + +exports.getNumberOfWatchers = () => { + return watcherCount; +}; + + +/***/ }), + +/***/ 98342: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const getWatcherManager = __webpack_require__(29539); +const LinkResolver = __webpack_require__(56083); +const EventEmitter = __webpack_require__(28614).EventEmitter; +const globToRegExp = __webpack_require__(22797); +const watchEventSource = __webpack_require__(10547); + +let EXISTANCE_ONLY_TIME_ENTRY; // lazy required + +const EMPTY_ARRAY = []; +const EMPTY_OPTIONS = {}; + +function addWatchersToSet(watchers, set) { + for (const w of watchers) { + if (w !== true && !set.has(w.directoryWatcher)) { + set.add(w.directoryWatcher); + addWatchersToSet(w.directoryWatcher.directories.values(), set); + } + } +} + +const stringToRegexp = ignored => { + const source = globToRegExp(ignored, { globstar: true, extended: true }) + .source; + const matchingStart = source.slice(0, source.length - 1) + "(?:$|\\/)"; + return matchingStart; +}; + +const ignoredToRegexp = ignored => { + if (Array.isArray(ignored)) { + return new RegExp(ignored.map(i => stringToRegexp(i)).join("|")); + } else if (typeof ignored === "string") { + return new RegExp(stringToRegexp(ignored)); + } else if (ignored instanceof RegExp) { + return ignored; + } else if (ignored) { + throw new Error(`Invalid option for 'ignored': ${ignored}`); + } else { + return undefined; + } +}; + +const normalizeOptions = options => { + return { + followSymlinks: !!options.followSymlinks, + ignored: ignoredToRegexp(options.ignored), + poll: options.poll + }; +}; + +const normalizeCache = new WeakMap(); +const cachedNormalizeOptions = options => { + const cacheEntry = normalizeCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const normalized = normalizeOptions(options); + normalizeCache.set(options, normalized); + return normalized; +}; + +class Watchpack extends EventEmitter { + constructor(options) { + super(); + if (!options) options = EMPTY_OPTIONS; + this.options = options; + this.aggregateTimeout = + typeof options.aggregateTimeout === "number" + ? options.aggregateTimeout + : 200; + this.watcherOptions = cachedNormalizeOptions(options); + this.watcherManager = getWatcherManager(this.watcherOptions); + this.fileWatchers = new Map(); + this.directoryWatchers = new Map(); + this.startTime = undefined; + this.paused = false; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.aggregateTimer = undefined; + this._onTimeout = this._onTimeout.bind(this); + } + + watch(arg1, arg2, arg3) { + let files, directories, missing, startTime; + if (!arg2) { + ({ + files = EMPTY_ARRAY, + directories = EMPTY_ARRAY, + missing = EMPTY_ARRAY, + startTime + } = arg1); + } else { + files = arg1; + directories = arg2; + missing = EMPTY_ARRAY; + startTime = arg3; + } + this.paused = false; + const oldFileWatchers = this.fileWatchers; + const oldDirectoryWatchers = this.directoryWatchers; + const ignored = this.watcherOptions.ignored; + const filter = ignored + ? path => !ignored.test(path.replace(/\\/g, "/")) + : () => true; + const addToMap = (map, key, item) => { + const list = map.get(key); + if (list === undefined) { + map.set(key, [item]); + } else { + list.push(item); + } + }; + const fileWatchersNeeded = new Map(); + const directoryWatchersNeeded = new Map(); + const missingFiles = new Set(); + if (this.watcherOptions.followSymlinks) { + const resolver = new LinkResolver(); + for (const file of files) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const file of missing) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const dir of directories) { + if (filter(dir)) { + let first = true; + for (const innerItem of resolver.resolve(dir)) { + if (filter(innerItem)) { + addToMap( + first ? directoryWatchersNeeded : fileWatchersNeeded, + innerItem, + dir + ); + } + first = false; + } + } + } + } else { + for (const file of files) { + if (filter(file)) { + addToMap(fileWatchersNeeded, file, file); + } + } + for (const file of missing) { + if (filter(file)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, file, file); + } + } + for (const dir of directories) { + if (filter(dir)) { + addToMap(directoryWatchersNeeded, dir, dir); + } + } + } + const newFileWatchers = new Map(); + const newDirectoryWatchers = new Map(); + const setupFileWatcher = (watcher, key, files) => { + watcher.on("initial-missing", type => { + for (const file of files) { + if (!missingFiles.has(file)) this._onRemove(file, file, type); + } + }); + watcher.on("change", (mtime, type) => { + for (const file of files) { + this._onChange(file, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const file of files) { + this._onRemove(file, file, type); + } + }); + newFileWatchers.set(key, watcher); + }; + const setupDirectoryWatcher = (watcher, key, directories) => { + watcher.on("initial-missing", type => { + for (const item of directories) { + this._onRemove(item, item, type); + } + }); + watcher.on("change", (file, mtime, type) => { + for (const item of directories) { + this._onChange(item, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const item of directories) { + this._onRemove(item, item, type); + } + }); + newDirectoryWatchers.set(key, watcher); + }; + // Close unneeded old watchers + const fileWatchersToClose = []; + const directoryWatchersToClose = []; + for (const [key, w] of oldFileWatchers) { + if (!fileWatchersNeeded.has(key)) { + w.close(); + } else { + fileWatchersToClose.push(w); + } + } + for (const [key, w] of oldDirectoryWatchers) { + if (!directoryWatchersNeeded.has(key)) { + w.close(); + } else { + directoryWatchersToClose.push(w); + } + } + // Create new watchers and install handlers on these watchers + watchEventSource.batch(() => { + for (const [key, files] of fileWatchersNeeded) { + const watcher = this.watcherManager.watchFile(key, startTime); + if (watcher) { + setupFileWatcher(watcher, key, files); + } + } + for (const [key, directories] of directoryWatchersNeeded) { + const watcher = this.watcherManager.watchDirectory(key, startTime); + if (watcher) { + setupDirectoryWatcher(watcher, key, directories); + } + } + }); + // Close old watchers + for (const w of fileWatchersToClose) w.close(); + for (const w of directoryWatchersToClose) w.close(); + // Store watchers + this.fileWatchers = newFileWatchers; + this.directoryWatchers = newDirectoryWatchers; + this.startTime = startTime; + } + + close() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + for (const w of this.fileWatchers.values()) w.close(); + for (const w of this.directoryWatchers.values()) w.close(); + this.fileWatchers.clear(); + this.directoryWatchers.clear(); + } + + pause() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + } + + getTimes() { + const directoryWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), directoryWatchers); + addWatchersToSet(this.directoryWatchers.values(), directoryWatchers); + const obj = Object.create(null); + for (const w of directoryWatchers) { + const times = w.getTimes(); + for (const file of Object.keys(times)) obj[file] = times[file]; + } + return obj; + } + + getTimeInfoEntries() { + if (EXISTANCE_ONLY_TIME_ENTRY === undefined) { + EXISTANCE_ONLY_TIME_ENTRY = __webpack_require__(39144).EXISTANCE_ONLY_TIME_ENTRY; + } + const directoryWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), directoryWatchers); + addWatchersToSet(this.directoryWatchers.values(), directoryWatchers); + const map = new Map(); + for (const w of directoryWatchers) { + const times = w.getTimeInfoEntries(); + for (const [path, entry] of times) { + if (map.has(path)) { + if (entry === EXISTANCE_ONLY_TIME_ENTRY) continue; + const value = map.get(path); + if (value === entry) continue; + if (value !== EXISTANCE_ONLY_TIME_ENTRY) { + map.set(path, Object.assign({}, value, entry)); + continue; + } + } + map.set(path, entry); + } + } + return map; + } + + _onChange(item, mtime, file, type) { + file = file || item; + if (this.paused) return; + this.emit("change", file, mtime, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregatedRemovals.delete(item); + this.aggregatedChanges.add(item); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + + _onRemove(item, file, type) { + file = file || item; + if (this.paused) return; + this.emit("remove", file, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregatedChanges.delete(item); + this.aggregatedRemovals.add(item); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + + _onTimeout() { + this.aggregateTimer = undefined; + const changes = this.aggregatedChanges; + const removals = this.aggregatedRemovals; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.emit("aggregated", changes, removals); + } +} + +module.exports = Watchpack; + + +/***/ }), + +/***/ 55610: +/***/ ((module) => { + +class Node { + /// value; + /// next; + + constructor(value) { + this.value = value; + + // TODO: Remove this when targeting Node.js 12. + this.next = undefined; + } +} + +class Queue { + // TODO: Use private class fields when targeting Node.js 12. + // #_head; + // #_tail; + // #_size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this._head) { + this._tail.next = node; + this._tail = node; + } else { + this._head = node; + this._tail = node; + } + + this._size++; + } + + dequeue() { + const current = this._head; + if (!current) { + return; + } + + this._head = this._head.next; + this._size--; + return current.value; + } + + clear() { + this._head = undefined; + this._tail = undefined; + this._size = 0; + } + + get size() { + return this._size; + } + + * [Symbol.iterator]() { + let current = this._head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +module.exports = Queue; + + +/***/ }), + +/***/ 81956: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* eslint-disable import/no-extraneous-dependencies */ + +module.exports = function () { + return { + default: __webpack_require__(48169), + BasicEvaluatedExpression: __webpack_require__(2412), + ModuleFilenameHelpers: __webpack_require__(80295), + NodeTargetPlugin: __webpack_require__(28037), + StringXor: __webpack_require__(23877), + sources: __webpack_require__(55600), + } +} + + +/***/ }), + +/***/ 97289: +/***/ ((module) => { + +module.exports = eval("require")("pnpapi"); + + +/***/ }), + +/***/ 42357: +/***/ ((module) => { + +"use strict"; +module.exports = require("assert");; + +/***/ }), + +/***/ 3561: +/***/ ((module) => { + +"use strict"; +module.exports = require("browserslist");; + +/***/ }), + +/***/ 64293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer");; + +/***/ }), + +/***/ 27619: +/***/ ((module) => { + +"use strict"; +module.exports = require("constants");; + +/***/ }), + +/***/ 76417: +/***/ ((module) => { + +"use strict"; +module.exports = require("crypto");; + +/***/ }), + +/***/ 28614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events");; + +/***/ }), + +/***/ 35747: +/***/ ((module) => { + +"use strict"; +module.exports = require("fs");; + +/***/ }), + +/***/ 98605: +/***/ ((module) => { + +"use strict"; +module.exports = require("http");; + +/***/ }), + +/***/ 57211: +/***/ ((module) => { + +"use strict"; +module.exports = require("https");; + +/***/ }), + +/***/ 57012: +/***/ ((module) => { + +"use strict"; +module.exports = require("inspector");; + +/***/ }), + +/***/ 59733: +/***/ ((module) => { + +"use strict"; +module.exports = require("jest-worker");; + +/***/ }), + +/***/ 14442: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/find-up");; + +/***/ }), + +/***/ 36386: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/neo-async");; + +/***/ }), + +/***/ 79286: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/schema-utils3");; + +/***/ }), + +/***/ 96241: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/source-map");; + +/***/ }), + +/***/ 54775: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/terser");; + +/***/ }), + +/***/ 55600: +/***/ ((module) => { + +"use strict"; +module.exports = require("next/dist/compiled/webpack-sources2");; + +/***/ }), + +/***/ 12087: +/***/ ((module) => { + +"use strict"; +module.exports = require("os");; + +/***/ }), + +/***/ 85622: +/***/ ((module) => { + +"use strict"; +module.exports = require("path");; + +/***/ }), + +/***/ 61765: +/***/ ((module) => { + +"use strict"; +module.exports = require("process");; + +/***/ }), + +/***/ 71191: +/***/ ((module) => { + +"use strict"; +module.exports = require("querystring");; + +/***/ }), + +/***/ 92413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream");; + +/***/ }), + +/***/ 78835: +/***/ ((module) => { + +"use strict"; +module.exports = require("url");; + +/***/ }), + +/***/ 31669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }), + +/***/ 92184: +/***/ ((module) => { + +"use strict"; +module.exports = require("vm");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(81956); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/constants.json b/packages/next/compiled/webpack/constants.json new file mode 100644 index 000000000000000..9a69b858db37d73 --- /dev/null +++ b/packages/next/compiled/webpack/constants.json @@ -0,0 +1,209 @@ +{ + "O_RDONLY": 0, + "O_WRONLY": 1, + "O_RDWR": 2, + "S_IFMT": 61440, + "S_IFREG": 32768, + "S_IFDIR": 16384, + "S_IFCHR": 8192, + "S_IFBLK": 24576, + "S_IFIFO": 4096, + "S_IFLNK": 40960, + "S_IFSOCK": 49152, + "O_CREAT": 512, + "O_EXCL": 2048, + "O_NOCTTY": 131072, + "O_TRUNC": 1024, + "O_APPEND": 8, + "O_DIRECTORY": 1048576, + "O_NOFOLLOW": 256, + "O_SYNC": 128, + "O_SYMLINK": 2097152, + "O_NONBLOCK": 4, + "S_IRWXU": 448, + "S_IRUSR": 256, + "S_IWUSR": 128, + "S_IXUSR": 64, + "S_IRWXG": 56, + "S_IRGRP": 32, + "S_IWGRP": 16, + "S_IXGRP": 8, + "S_IRWXO": 7, + "S_IROTH": 4, + "S_IWOTH": 2, + "S_IXOTH": 1, + "E2BIG": 7, + "EACCES": 13, + "EADDRINUSE": 48, + "EADDRNOTAVAIL": 49, + "EAFNOSUPPORT": 47, + "EAGAIN": 35, + "EALREADY": 37, + "EBADF": 9, + "EBADMSG": 94, + "EBUSY": 16, + "ECANCELED": 89, + "ECHILD": 10, + "ECONNABORTED": 53, + "ECONNREFUSED": 61, + "ECONNRESET": 54, + "EDEADLK": 11, + "EDESTADDRREQ": 39, + "EDOM": 33, + "EDQUOT": 69, + "EEXIST": 17, + "EFAULT": 14, + "EFBIG": 27, + "EHOSTUNREACH": 65, + "EIDRM": 90, + "EILSEQ": 92, + "EINPROGRESS": 36, + "EINTR": 4, + "EINVAL": 22, + "EIO": 5, + "EISCONN": 56, + "EISDIR": 21, + "ELOOP": 62, + "EMFILE": 24, + "EMLINK": 31, + "EMSGSIZE": 40, + "EMULTIHOP": 95, + "ENAMETOOLONG": 63, + "ENETDOWN": 50, + "ENETRESET": 52, + "ENETUNREACH": 51, + "ENFILE": 23, + "ENOBUFS": 55, + "ENODATA": 96, + "ENODEV": 19, + "ENOENT": 2, + "ENOEXEC": 8, + "ENOLCK": 77, + "ENOLINK": 97, + "ENOMEM": 12, + "ENOMSG": 91, + "ENOPROTOOPT": 42, + "ENOSPC": 28, + "ENOSR": 98, + "ENOSTR": 99, + "ENOSYS": 78, + "ENOTCONN": 57, + "ENOTDIR": 20, + "ENOTEMPTY": 66, + "ENOTSOCK": 38, + "ENOTSUP": 45, + "ENOTTY": 25, + "ENXIO": 6, + "EOPNOTSUPP": 102, + "EOVERFLOW": 84, + "EPERM": 1, + "EPIPE": 32, + "EPROTO": 100, + "EPROTONOSUPPORT": 43, + "EPROTOTYPE": 41, + "ERANGE": 34, + "EROFS": 30, + "ESPIPE": 29, + "ESRCH": 3, + "ESTALE": 70, + "ETIME": 101, + "ETIMEDOUT": 60, + "ETXTBSY": 26, + "EWOULDBLOCK": 35, + "EXDEV": 18, + "SIGHUP": 1, + "SIGINT": 2, + "SIGQUIT": 3, + "SIGILL": 4, + "SIGTRAP": 5, + "SIGABRT": 6, + "SIGIOT": 6, + "SIGBUS": 10, + "SIGFPE": 8, + "SIGKILL": 9, + "SIGUSR1": 30, + "SIGSEGV": 11, + "SIGUSR2": 31, + "SIGPIPE": 13, + "SIGALRM": 14, + "SIGTERM": 15, + "SIGCHLD": 20, + "SIGCONT": 19, + "SIGSTOP": 17, + "SIGTSTP": 18, + "SIGTTIN": 21, + "SIGTTOU": 22, + "SIGURG": 16, + "SIGXCPU": 24, + "SIGXFSZ": 25, + "SIGVTALRM": 26, + "SIGPROF": 27, + "SIGWINCH": 28, + "SIGIO": 23, + "SIGSYS": 12, + "SSL_OP_ALL": 2147486719, + "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION": 262144, + "SSL_OP_CIPHER_SERVER_PREFERENCE": 4194304, + "SSL_OP_CISCO_ANYCONNECT": 32768, + "SSL_OP_COOKIE_EXCHANGE": 8192, + "SSL_OP_CRYPTOPRO_TLSEXT_BUG": 2147483648, + "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS": 2048, + "SSL_OP_EPHEMERAL_RSA": 0, + "SSL_OP_LEGACY_SERVER_CONNECT": 4, + "SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER": 32, + "SSL_OP_MICROSOFT_SESS_ID_BUG": 1, + "SSL_OP_MSIE_SSLV2_RSA_PADDING": 0, + "SSL_OP_NETSCAPE_CA_DN_BUG": 536870912, + "SSL_OP_NETSCAPE_CHALLENGE_BUG": 2, + "SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG": 1073741824, + "SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG": 8, + "SSL_OP_NO_COMPRESSION": 131072, + "SSL_OP_NO_QUERY_MTU": 4096, + "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION": 65536, + "SSL_OP_NO_SSLv2": 16777216, + "SSL_OP_NO_SSLv3": 33554432, + "SSL_OP_NO_TICKET": 16384, + "SSL_OP_NO_TLSv1": 67108864, + "SSL_OP_NO_TLSv1_1": 268435456, + "SSL_OP_NO_TLSv1_2": 134217728, + "SSL_OP_PKCS1_CHECK_1": 0, + "SSL_OP_PKCS1_CHECK_2": 0, + "SSL_OP_SINGLE_DH_USE": 1048576, + "SSL_OP_SINGLE_ECDH_USE": 524288, + "SSL_OP_SSLEAY_080_CLIENT_DH_BUG": 128, + "SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG": 0, + "SSL_OP_TLS_BLOCK_PADDING_BUG": 512, + "SSL_OP_TLS_D5_BUG": 256, + "SSL_OP_TLS_ROLLBACK_BUG": 8388608, + "ENGINE_METHOD_DSA": 2, + "ENGINE_METHOD_DH": 4, + "ENGINE_METHOD_RAND": 8, + "ENGINE_METHOD_ECDH": 16, + "ENGINE_METHOD_ECDSA": 32, + "ENGINE_METHOD_CIPHERS": 64, + "ENGINE_METHOD_DIGESTS": 128, + "ENGINE_METHOD_STORE": 256, + "ENGINE_METHOD_PKEY_METHS": 512, + "ENGINE_METHOD_PKEY_ASN1_METHS": 1024, + "ENGINE_METHOD_ALL": 65535, + "ENGINE_METHOD_NONE": 0, + "DH_CHECK_P_NOT_SAFE_PRIME": 2, + "DH_CHECK_P_NOT_PRIME": 1, + "DH_UNABLE_TO_CHECK_GENERATOR": 4, + "DH_NOT_SUITABLE_GENERATOR": 8, + "NPN_ENABLED": 1, + "RSA_PKCS1_PADDING": 1, + "RSA_SSLV23_PADDING": 2, + "RSA_NO_PADDING": 3, + "RSA_PKCS1_OAEP_PADDING": 4, + "RSA_X931_PADDING": 5, + "RSA_PKCS1_PSS_PADDING": 6, + "POINT_CONVERSION_COMPRESSED": 2, + "POINT_CONVERSION_UNCOMPRESSED": 4, + "POINT_CONVERSION_HYBRID": 6, + "F_OK": 0, + "R_OK": 4, + "W_OK": 2, + "X_OK": 1, + "UV_UDP_REUSEADDR": 4 +} diff --git a/packages/next/compiled/webpack/duplex.js b/packages/next/compiled/webpack/duplex.js new file mode 100644 index 000000000000000..7ed7b459d3bb9dc --- /dev/null +++ b/packages/next/compiled/webpack/duplex.js @@ -0,0 +1,3033 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 334: +/***/ ((__unused_webpack_module, exports) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(350); +} + + +/***/ }), + +/***/ 350: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 352: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 404: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 50: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(193).Duplex + + +/***/ }), + +/***/ 770: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +var Readable = __webpack_require__(341); +var Writable = __webpack_require__(63); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 143: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(826); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(352); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(614).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var debugUtil = __webpack_require__(669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(878); +var destroyImpl = __webpack_require__(915); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(770); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(770); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 63: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(262) +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(915); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(770); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 878: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(788).Buffer; +var util = __webpack_require__(669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 915: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + 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(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 65: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(413); + + +/***/ }), + +/***/ 788: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 395: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 193: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(341); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(63); + exports.Duplex = __webpack_require__(770); + exports.Transform = __webpack_require__(826); + exports.PassThrough = __webpack_require__(143); +} + + +/***/ }), + +/***/ 262: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(669).deprecate; + + +/***/ }), + +/***/ 293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer");; + +/***/ }), + +/***/ 614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events");; + +/***/ }), + +/***/ 413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream");; + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(50); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/empty.js b/packages/next/compiled/webpack/empty.js new file mode 100644 index 000000000000000..f79a62b0c947b87 --- /dev/null +++ b/packages/next/compiled/webpack/empty.js @@ -0,0 +1,52 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 533: +/***/ (() => { + + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(533); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/events.js b/packages/next/compiled/webpack/events.js new file mode 100644 index 000000000000000..54d34f5afaff8af --- /dev/null +++ b/packages/next/compiled/webpack/events.js @@ -0,0 +1,501 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 961: +/***/ ((module) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + var args = []; + for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + ReflectApply(this.listener, this.target, args); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(961); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/global.js b/packages/next/compiled/webpack/global.js new file mode 100644 index 000000000000000..9e5e47a15bda2ba --- /dev/null +++ b/packages/next/compiled/webpack/global.js @@ -0,0 +1,72 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 149: +/***/ ((module) => { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(149); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/harmony-module.js b/packages/next/compiled/webpack/harmony-module.js new file mode 100644 index 000000000000000..fcde4f9f0df1aea --- /dev/null +++ b/packages/next/compiled/webpack/harmony-module.js @@ -0,0 +1,76 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 931: +/***/ ((module) => { + +module.exports = function(originalModule) { + if (!originalModule.webpackPolyfill) { + var module = Object.create(originalModule); + // module.parent = undefined by default + if (!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + Object.defineProperty(module, "exports", { + enumerable: true + }); + module.webpackPolyfill = 1; + } + return module; +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(931); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index.js b/packages/next/compiled/webpack/index.js new file mode 100644 index 000000000000000..186656e35bc069f --- /dev/null +++ b/packages/next/compiled/webpack/index.js @@ -0,0 +1,2105 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 550: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 348: +/***/ ((__unused_webpack_module, exports) => { + +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 352: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 979: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(550) +var ieee754 = __webpack_require__(348) +var isArray = __webpack_require__(352) + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(979); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index1.js b/packages/next/compiled/webpack/index1.js new file mode 100644 index 000000000000000..b5ae2208b7e5d0e --- /dev/null +++ b/packages/next/compiled/webpack/index1.js @@ -0,0 +1,155 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 29: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global window, global*/ +var util = __webpack_require__(669) +var assert = __webpack_require__(357) +function now() { return new Date().getTime() } + +var slice = Array.prototype.slice +var console +var times = {} + +if (typeof global !== "undefined" && global.console) { + console = global.console +} else if (typeof window !== "undefined" && window.console) { + console = window.console +} else { + console = {} +} + +var functions = [ + [log, "log"], + [info, "info"], + [warn, "warn"], + [error, "error"], + [time, "time"], + [timeEnd, "timeEnd"], + [trace, "trace"], + [dir, "dir"], + [consoleAssert, "assert"] +] + +for (var i = 0; i < functions.length; i++) { + var tuple = functions[i] + var f = tuple[0] + var name = tuple[1] + + if (!console[name]) { + console[name] = f + } +} + +module.exports = console + +function log() {} + +function info() { + console.log.apply(console, arguments) +} + +function warn() { + console.log.apply(console, arguments) +} + +function error() { + console.warn.apply(console, arguments) +} + +function time(label) { + times[label] = now() +} + +function timeEnd(label) { + var time = times[label] + if (!time) { + throw new Error("No such label: " + label) + } + + delete times[label] + var duration = now() - time + console.log(label + ": " + duration + "ms") +} + +function trace() { + var err = new Error() + err.name = "Trace" + err.message = util.format.apply(null, arguments) + console.error(err.stack) +} + +function dir(object) { + console.log(util.inspect(object) + "\n") +} + +function consoleAssert(expression) { + if (!expression) { + var arr = slice.call(arguments, 1) + assert.ok(false, util.format.apply(null, arr)) + } +} + + +/***/ }), + +/***/ 357: +/***/ ((module) => { + +"use strict"; +module.exports = require("assert");; + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(29); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index10.js b/packages/next/compiled/webpack/index10.js new file mode 100644 index 000000000000000..ea5627c8bdcb26b --- /dev/null +++ b/packages/next/compiled/webpack/index10.js @@ -0,0 +1,201 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 287: +/***/ ((__unused_webpack_module, exports) => { + +var indexOf = function (xs, item) { + if (xs.indexOf) return xs.indexOf(item); + else for (var i = 0; i < xs.length; i++) { + if (xs[i] === item) return i; + } + return -1; +}; +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } +}()); + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; + } + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; + } + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); + } + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + if (context) { + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; + }); + } + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.isContext = function (context) { + return context instanceof Context; +}; + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + return copy; +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(287); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index11.js b/packages/next/compiled/webpack/index11.js new file mode 100644 index 000000000000000..b45493aca2e3606 --- /dev/null +++ b/packages/next/compiled/webpack/index11.js @@ -0,0 +1,6883 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 301: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +/* eslint camelcase: "off" */ + +var assert = __webpack_require__(357); + +var Zstream = __webpack_require__(249); +var zlib_deflate = __webpack_require__(132); +var zlib_inflate = __webpack_require__(517); +var constants = __webpack_require__(11); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +var GZIP_HEADER_ID1 = 0x1f; +var GZIP_HEADER_ID2 = 0x8b; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError('Bad argument'); + } + + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; +} + +Zlib.prototype.close = function () { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + assert(this.init_done, 'close before init'); + assert(this.mode <= exports.UNZIP); + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; + + this.dictionary = null; +}; + +Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { + assert.equal(arguments.length, 8); + + assert(this.init_done, 'write before init'); + assert(this.mode !== exports.NONE, 'already finalized'); + assert.equal(false, this.write_in_progress, 'write already in progress'); + assert.equal(false, this.pending_close, 'close is pending'); + + this.write_in_progress = true; + + assert.equal(false, flush === undefined, 'must provide flush value'); + + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + + if (!async) { + // sync version + this._process(); + + if (this._checkError()) { + return this._afterSync(); + } + return; + } + + // async version + var self = this; + process.nextTick(function () { + self._process(); + self._after(); + }); + + return this; +}; + +Zlib.prototype._afterSync = function () { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + return [avail_in, avail_out]; +}; + +Zlib.prototype._process = function () { + var next_expected_header_byte = null; + + // If the avail_out is left at 0, then it means that it ran out + // of room. If there was avail_out left over, then it means + // that all of the input was consumed. + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + + if (this.strm.avail_in === 1) { + // The only available byte was already read. + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + // There is no actual difference between INFLATE and INFLATERAW + // (after initialization). + this.mode = exports.INFLATE; + } + + break; + default: + throw new Error('invalid number of gzip magic number bytes read'); + } + + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate(this.strm, this.flush + + // If data was encoded with dictionary + );if (this.err === exports.Z_NEED_DICT && this.dictionary) { + // Load it + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + // And try to decode again + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. + // Make it possible for After() to tell a bad dictionary from bad + // input. + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { + // Bytes remain in input buffer. Perhaps this is another compressed + // member in the same archive, or just trailing garbage. + // Trailing zero bytes are okay, though, since they are frequently + // used for padding. + + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error('Unknown mode ' + this.mode); + } +}; + +Zlib.prototype._checkError = function () { + // Acceptable error states depend on the type of zlib stream. + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error('unexpected end of file'); + return false; + } + break; + case exports.Z_STREAM_END: + // normal statuses, not fatal + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error('Missing dictionary'); + } else { + this._error('Bad dictionary'); + } + return false; + default: + // something else. + this._error('Zlib error'); + return false; + } + + return true; +}; + +Zlib.prototype._after = function () { + if (!this._checkError()) { + return; + } + + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + // call the write() cb + this.callback(avail_in, avail_out); + + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype._error = function (message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror(message, this.err + + // no hope of rescue. + );this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { + assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); + + assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); + assert(level >= -1 && level <= 9, 'invalid compression level'); + + assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); + + assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); + + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); +}; + +Zlib.prototype.params = function () { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype.reset = function () { + this._reset(); + this._setDictionary(); +}; + +Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + + this.flush = exports.Z_NO_FLUSH; + + this.err = exports.Z_OK; + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + + this.strm = new Zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (this.err !== exports.Z_OK) { + this._error('Init error'); + } + + this.dictionary = dictionary; + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype._setDictionary = function () { + if (this.dictionary == null) { + return; + } + + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to set dictionary'); + } +}; + +Zlib.prototype._reset = function () { + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to reset stream'); + } +}; + +exports.Zlib = Zlib; + +/***/ }), + +/***/ 555: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var Buffer = __webpack_require__(293).Buffer; +var Transform = __webpack_require__(413).Transform; +var binding = __webpack_require__(301); +var util = __webpack_require__(669); +var assert = __webpack_require__(357).ok; +var kMaxLength = __webpack_require__(293).kMaxLength; +var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = 16 * 1024; + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +var bkeys = Object.keys(binding); +for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, value: binding[bkey], writable: false + }); + } +} + +// translation table for return codes. +var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +var ckeys = Object.keys(codes); +for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; +} + +Object.defineProperty(exports, "codes", ({ + enumerable: true, value: Object.freeze(codes), writable: false +})); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function (o) { + return new Deflate(o); +}; + +exports.createInflate = function (o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function (o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function (o) { + return new InflateRaw(o); +}; + +exports.createGzip = function (o) { + return new Gzip(o); +}; + +exports.createGunzip = function (o) { + return new Gunzip(o); +}; + +exports.createUnzip = function (o) { + return new Unzip(o); +}; + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function (buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function (buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function (buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function (buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function (buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function (buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function (buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf; + var err = null; + + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer.concat(buffers, nread); + } + + buffers = []; + engine.close(); + callback(err, buf); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') buffer = Buffer.from(buffer); + + if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); + + var flushFlag = engine._finishFlushFlag; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + +function isValidFlushFlag(flag) { + return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + var _this = this; + + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error('Invalid flush flag: ' + opts.finishFlush); + } + + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._handle = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._handle.onerror = function (message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + _close(self); + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + + this._buffer = Buffer.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + + Object.defineProperty(this, '_closed', { + get: function () { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function (level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function () { + assert(self._handle, 'zlib binding closed'); + self._handle.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function () { + assert(this._handle, 'zlib binding closed'); + return this._handle.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function (callback) { + this._transform(Buffer.alloc(0), '', callback); +}; + +Zlib.prototype.flush = function (kind, callback) { + var _this2 = this; + + var ws = this._writableState; + + if (typeof kind === 'function' || kind === undefined && !callback) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) process.nextTick(callback); + } else if (ws.ending) { + if (callback) this.once('end', callback); + } else if (ws.needDrain) { + if (callback) { + this.once('drain', function () { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer.alloc(0), '', callback); + } +}; + +Zlib.prototype.close = function (callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); +}; + +function _close(engine, callback) { + if (callback) process.nextTick(callback); + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) return; + + engine._handle.close(); + engine._handle = null; +} + +function emitCloseNT(self) { + self.emit('close'); +} + +Zlib.prototype._transform = function (chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); + + if (!this._handle) return cb(new Error('zlib binding closed')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag + // (or whatever flag was provided using opts.finishFlush). + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) flushFlag = this._finishFlushFlag;else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function (er) { + error = er; + }); + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; + } + + assert(this._handle, 'zlib binding closed'); + var req = this._handle.write(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + // When the callback is used in an async write, the callback's + // context is the `req` object that was created. The req object + // is === this._handle, and that's why it's important to null + // out the values after they are done being used. `this._handle` + // can stay in memory longer than the callback and buffer are needed. + if (this) { + this.buffer = null; + this.callback = null; + } + + if (self._hadError) return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + if (!async) return true; + + var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); + +/***/ }), + +/***/ 311: +/***/ ((__unused_webpack_module, exports) => { + + + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + + +/***/ }), + +/***/ 759: +/***/ ((module) => { + + + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + + +/***/ }), + +/***/ 11: +/***/ ((module) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + + +/***/ }), + +/***/ 662: +/***/ ((module) => { + + + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + + +/***/ }), + +/***/ 132: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(311); +var trees = __webpack_require__(922); +var adler32 = __webpack_require__(759); +var crc32 = __webpack_require__(662); +var msg = __webpack_require__(296); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + + +/***/ }), + +/***/ 36: +/***/ ((module) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + + +/***/ }), + +/***/ 517: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(311); +var adler32 = __webpack_require__(759); +var crc32 = __webpack_require__(662); +var inflate_fast = __webpack_require__(36); +var inflate_table = __webpack_require__(622); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + + +/***/ }), + +/***/ 622: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(311); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + + +/***/ }), + +/***/ 296: +/***/ ((module) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + + +/***/ }), + +/***/ 922: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = __webpack_require__(311); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + + +/***/ }), + +/***/ 249: +/***/ ((module) => { + + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + + +/***/ }), + +/***/ 357: +/***/ ((module) => { + +module.exports = require("assert");; + +/***/ }), + +/***/ 293: +/***/ ((module) => { + +module.exports = require("buffer");; + +/***/ }), + +/***/ 413: +/***/ ((module) => { + +module.exports = require("stream");; + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(555); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index12.js b/packages/next/compiled/webpack/index12.js new file mode 100644 index 000000000000000..2490b4f0eb19cb2 --- /dev/null +++ b/packages/next/compiled/webpack/index12.js @@ -0,0 +1,109 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 305: +/***/ (() => { + + + +let $module + +/* + let contextProto = this.context; + while (contextProto = Object.getPrototypeOf(contextProto)) { + completionGroups.push(Object.getOwnPropertyNames(contextProto)); + } +*/ + + +function handle (data) { + let idx = data.idx + , child = data.child + , method = data.method + , args = data.args + , callback = function () { + let _args = Array.prototype.slice.call(arguments) + if (_args[0] instanceof Error) { + let e = _args[0] + _args[0] = { + '$error' : '$error' + , 'type' : e.constructor.name + , 'message' : e.message + , 'stack' : e.stack + } + Object.keys(e).forEach(function(key) { + _args[0][key] = e[key] + }) + } + process.send({ owner: 'farm', idx: idx, child: child, args: _args }) + } + , exec + + if (method == null && typeof $module == 'function') + exec = $module + else if (typeof $module[method] == 'function') + exec = $module[method] + + if (!exec) + return console.error('NO SUCH METHOD:', method) + + exec.apply(null, args.concat([ callback ])) +} + + +process.on('message', function (data) { + if (data.owner !== 'farm') { + return; + } + + if (!$module) return $module = require(data.module) + if (data.event == 'die') return process.exit(0) + handle(data) +}) + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(305); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index2.js b/packages/next/compiled/webpack/index2.js new file mode 100644 index 000000000000000..ef78d0a68d19aa6 --- /dev/null +++ b/packages/next/compiled/webpack/index2.js @@ -0,0 +1,16403 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3557: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"sha224WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha224\",\"id\":\"302d300d06096086480165030402040500041c\"},\"RSA-SHA224\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha224\",\"id\":\"302d300d06096086480165030402040500041c\"},\"sha256WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha256\",\"id\":\"3031300d060960864801650304020105000420\"},\"RSA-SHA256\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha256\",\"id\":\"3031300d060960864801650304020105000420\"},\"sha384WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha384\",\"id\":\"3041300d060960864801650304020205000430\"},\"RSA-SHA384\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha384\",\"id\":\"3041300d060960864801650304020205000430\"},\"sha512WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha512\",\"id\":\"3051300d060960864801650304020305000440\"},\"RSA-SHA512\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha512\",\"id\":\"3051300d060960864801650304020305000440\"},\"RSA-SHA1\":{\"sign\":\"rsa\",\"hash\":\"sha1\",\"id\":\"3021300906052b0e03021a05000414\"},\"ecdsa-with-SHA1\":{\"sign\":\"ecdsa\",\"hash\":\"sha1\",\"id\":\"\"},\"sha256\":{\"sign\":\"ecdsa\",\"hash\":\"sha256\",\"id\":\"\"},\"sha224\":{\"sign\":\"ecdsa\",\"hash\":\"sha224\",\"id\":\"\"},\"sha384\":{\"sign\":\"ecdsa\",\"hash\":\"sha384\",\"id\":\"\"},\"sha512\":{\"sign\":\"ecdsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-SHA\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA-SHA1\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA-WITH-SHA224\":{\"sign\":\"dsa\",\"hash\":\"sha224\",\"id\":\"\"},\"DSA-SHA224\":{\"sign\":\"dsa\",\"hash\":\"sha224\",\"id\":\"\"},\"DSA-WITH-SHA256\":{\"sign\":\"dsa\",\"hash\":\"sha256\",\"id\":\"\"},\"DSA-SHA256\":{\"sign\":\"dsa\",\"hash\":\"sha256\",\"id\":\"\"},\"DSA-WITH-SHA384\":{\"sign\":\"dsa\",\"hash\":\"sha384\",\"id\":\"\"},\"DSA-SHA384\":{\"sign\":\"dsa\",\"hash\":\"sha384\",\"id\":\"\"},\"DSA-WITH-SHA512\":{\"sign\":\"dsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-SHA512\":{\"sign\":\"dsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-RIPEMD160\":{\"sign\":\"dsa\",\"hash\":\"rmd160\",\"id\":\"\"},\"ripemd160WithRSA\":{\"sign\":\"rsa\",\"hash\":\"rmd160\",\"id\":\"3021300906052b2403020105000414\"},\"RSA-RIPEMD160\":{\"sign\":\"rsa\",\"hash\":\"rmd160\",\"id\":\"3021300906052b2403020105000414\"},\"md5WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"md5\",\"id\":\"3020300c06082a864886f70d020505000410\"},\"RSA-MD5\":{\"sign\":\"rsa\",\"hash\":\"md5\",\"id\":\"3020300c06082a864886f70d020505000410\"}}"); + +/***/ }), + +/***/ 3182: +/***/ ((module) => { + +"use strict"; +module.exports = {"i8":"6.5.3"}; + +/***/ }), + +/***/ 5424: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"2.16.840.1.101.3.4.1.1\":\"aes-128-ecb\",\"2.16.840.1.101.3.4.1.2\":\"aes-128-cbc\",\"2.16.840.1.101.3.4.1.3\":\"aes-128-ofb\",\"2.16.840.1.101.3.4.1.4\":\"aes-128-cfb\",\"2.16.840.1.101.3.4.1.21\":\"aes-192-ecb\",\"2.16.840.1.101.3.4.1.22\":\"aes-192-cbc\",\"2.16.840.1.101.3.4.1.23\":\"aes-192-ofb\",\"2.16.840.1.101.3.4.1.24\":\"aes-192-cfb\",\"2.16.840.1.101.3.4.1.41\":\"aes-256-ecb\",\"2.16.840.1.101.3.4.1.42\":\"aes-256-cbc\",\"2.16.840.1.101.3.4.1.43\":\"aes-256-ofb\",\"2.16.840.1.101.3.4.1.44\":\"aes-256-cfb\"}"); + +/***/ }), + +/***/ 1363: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = exports; + +asn1.bignum = __webpack_require__(2828); + +asn1.define = __webpack_require__(9506).define; +asn1.base = __webpack_require__(2285); +asn1.constants = __webpack_require__(6859); +asn1.decoders = __webpack_require__(5120); +asn1.encoders = __webpack_require__(5568); + + +/***/ }), + +/***/ 9506: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = __webpack_require__(1363); +var inherits = __webpack_require__(2989); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = __webpack_require__(2184).runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; + + +/***/ }), + +/***/ 2044: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); +var Reporter = __webpack_require__(2285).Reporter; +var Buffer = __webpack_require__(4293).Buffer; + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.C = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.R = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + + +/***/ }), + +/***/ 2285: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var base = exports; + +base.Reporter = __webpack_require__(3206)/* .Reporter */ .b; +base.DecoderBuffer = __webpack_require__(2044)/* .DecoderBuffer */ .C; +base.EncoderBuffer = __webpack_require__(2044)/* .EncoderBuffer */ .R; +base.Node = __webpack_require__(3621); + + +/***/ }), + +/***/ 3621: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Reporter = __webpack_require__(2285).Reporter; +var EncoderBuffer = __webpack_require__(2285).EncoderBuffer; +var DecoderBuffer = __webpack_require__(2285).DecoderBuffer; +var assert = __webpack_require__(6787); + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + var result = state['default']; + var present = true; + + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); + + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; + + +/***/ }), + +/***/ 3206: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.b = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; +}; + + +/***/ }), + +/***/ 2173: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = __webpack_require__(6859); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + + +/***/ }), + +/***/ 6859: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = __webpack_require__(2173); + + +/***/ }), + +/***/ 9921: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); + +var asn1 = __webpack_require__(1363); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + + +/***/ }), + +/***/ 5120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var decoders = exports; + +decoders.der = __webpack_require__(9921); +decoders.pem = __webpack_require__(6707); + + +/***/ }), + +/***/ 6707: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); +var Buffer = __webpack_require__(4293).Buffer; + +var DERDecoder = __webpack_require__(9921); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; + + +/***/ }), + +/***/ 9515: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); +var Buffer = __webpack_require__(4293).Buffer; + +var asn1 = __webpack_require__(1363); +var base = asn1.base; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + + +/***/ }), + +/***/ 5568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var encoders = exports; + +encoders.der = __webpack_require__(9515); +encoders.pem = __webpack_require__(4557); + + +/***/ }), + +/***/ 4557: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(2989); + +var DEREncoder = __webpack_require__(9515); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + + +/***/ }), + +/***/ 2828: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = __webpack_require__(4293).Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 2752: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + +if (typeof self === 'object') { + if (self.crypto && self.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker with no crypto support + try { + var crypto = __webpack_require__(6417); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } +} + + +/***/ }), + +/***/ 8855: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers + + +/***/ }), + +/***/ 2724: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers + + +/***/ }), + +/***/ 4326: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var bn = __webpack_require__(2828); +var randomBytes = __webpack_require__(9822); +module.exports = crt; +function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; +} +function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); +} +crt.getr = getr; +function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + return r; +} + + +/***/ }), + +/***/ 220: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(3557) + + +/***/ }), + +/***/ 693: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) + +exports.createSign = crypto.createSign +exports.Sign = crypto.Sign + +exports.createVerify = crypto.createVerify +exports.Verify = crypto.Verify + + +/***/ }), + +/***/ 2776: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var elliptic = __webpack_require__(4117) +var BN = __webpack_require__(2828) + +module.exports = function createECDH (curve) { + return new ECDH(curve) +} + +var aliases = { + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +} + +aliases.p224 = aliases.secp224r1 +aliases.p256 = aliases.secp256r1 = aliases.prime256v1 +aliases.p192 = aliases.secp192r1 = aliases.prime192v1 +aliases.p384 = aliases.secp384r1 +aliases.p521 = aliases.secp521r1 + +function ECDH (curve) { + this.curveType = aliases[curve] + if (!this.curveType) { + this.curveType = { + name: curve + } + } + this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap + this.keys = void 0 +} + +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair() + return this.getPublicKey(enc, format) +} + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8' + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc) + } + var otherPub = this.curve.keyFromPublic(other).getPublic() + var out = otherPub.mul(this.keys.getPrivate()).getX() + return formatReturnValue(out, enc, this.curveType.byteLength) +} + +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true) + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7 + } else { + key[0] = 6 + } + } + return formatReturnValue(key, enc) +} + +ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc) +} + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc) + } + this.keys._importPublic(pub) + return this +} + +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc) + } + + var _priv = new BN(priv) + _priv = _priv.toString(16) + this.keys = this.curve.genKeyPair() + this.keys._importPrivate(_priv) + return this +} + +function formatReturnValue (bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray() + } + var buf = new Buffer(bn) + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length) + zeros.fill(0) + buf = Buffer.concat([zeros, buf]) + } + if (!enc) { + return buf + } else { + return buf.toString(enc) + } +} + + +/***/ }), + +/***/ 9318: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var createECDH = __webpack_require__(6417).createECDH + +module.exports = createECDH || __webpack_require__(2776) + + +/***/ }), + +/***/ 356: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(6417).createHash + + +/***/ }), + +/***/ 9871: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(6417).createHmac + + +/***/ }), + +/***/ 1223: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(9822) +exports.createHash = exports.Hash = __webpack_require__(356) +exports.createHmac = exports.Hmac = __webpack_require__(9871) + +var algos = __webpack_require__(220) +var algoKeys = Object.keys(algos) +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) +exports.getHashes = function () { + return hashes +} + +var p = __webpack_require__(800) +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync + +var aes = __webpack_require__(2724) + +exports.Cipher = aes.Cipher +exports.createCipher = aes.createCipher +exports.Cipheriv = aes.Cipheriv +exports.createCipheriv = aes.createCipheriv +exports.Decipher = aes.Decipher +exports.createDecipher = aes.createDecipher +exports.Decipheriv = aes.Decipheriv +exports.createDecipheriv = aes.createDecipheriv +exports.getCiphers = aes.getCiphers +exports.listCiphers = aes.listCiphers + +var dh = __webpack_require__(7777) + +exports.DiffieHellmanGroup = dh.DiffieHellmanGroup +exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup +exports.getDiffieHellman = dh.getDiffieHellman +exports.createDiffieHellman = dh.createDiffieHellman +exports.DiffieHellman = dh.DiffieHellman + +var sign = __webpack_require__(693) + +exports.createSign = sign.createSign +exports.Sign = sign.Sign +exports.createVerify = sign.createVerify +exports.Verify = sign.Verify + +exports.createECDH = __webpack_require__(9318) + +var publicEncrypt = __webpack_require__(232) + +exports.publicEncrypt = publicEncrypt.publicEncrypt +exports.privateEncrypt = publicEncrypt.privateEncrypt +exports.publicDecrypt = publicEncrypt.publicDecrypt +exports.privateDecrypt = publicEncrypt.privateDecrypt + +// the least I can do is make error messages for the rest of the node.js/crypto api. +// ;[ +// 'createCredentials' +// ].forEach(function (name) { +// exports[name] = function () { +// throw new Error([ +// 'sorry, ' + name + ' is not implemented yet', +// 'we accept pull requests', +// 'https://github.com/crypto-browserify/crypto-browserify' +// ].join('\n')) +// } +// }) + +var rf = __webpack_require__(4859) + +exports.randomFill = rf.randomFill +exports.randomFillSync = rf.randomFillSync + +exports.createCredentials = function () { + throw new Error([ + 'sorry, createCredentials is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) +} + +exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + 'POINT_CONVERSION_UNCOMPRESSED': 4, + 'POINT_CONVERSION_HYBRID': 6 +} + + +/***/ }), + +/***/ 7777: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) + +// getDiffieHellman +exports.DiffieHellmanGroup = crypto.DiffieHellmanGroup +exports.createDiffieHellmanGroup = crypto.createDiffieHellmanGroup +exports.getDiffieHellman = crypto.getDiffieHellman + +// createDiffieHellman +exports.createDiffieHellman = crypto.createDiffieHellman +exports.DiffieHellman = crypto.DiffieHellman + + +/***/ }), + +/***/ 4117: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var elliptic = exports; + +elliptic.version = __webpack_require__(3182)/* .version */ .i8; +elliptic.utils = __webpack_require__(8843); +elliptic.rand = __webpack_require__(2752); +elliptic.curve = __webpack_require__(6506); +elliptic.curves = __webpack_require__(6866); + +// Protocols +elliptic.ec = __webpack_require__(7720); +elliptic.eddsa = __webpack_require__(1774); + + +/***/ }), + +/***/ 3695: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); +var utils = __webpack_require__(8843); +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + + this._bitLength = this.n ? this.n.bitLength() : 0; + + // Generalized Greg Maxwell's trick + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w, this._bitLength); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); + naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + + +/***/ }), + +/***/ 9463: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(8843); +var BN = __webpack_require__(2828); +var inherits = __webpack_require__(2989); +var Base = __webpack_require__(3695); + +var assert = utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.z).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + + +/***/ }), + +/***/ 6506: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curve = exports; + +curve.base = __webpack_require__(3695); +curve.short = __webpack_require__(2424); +curve.mont = __webpack_require__(5710); +curve.edwards = __webpack_require__(9463); + + +/***/ }), + +/***/ 5710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); +var inherits = __webpack_require__(2989); +var Base = __webpack_require__(3695); + +var utils = __webpack_require__(8843); + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + + +/***/ }), + +/***/ 2424: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(8843); +var BN = __webpack_require__(2828); +var inherits = __webpack_require__(2989); +var Base = __webpack_require__(3695); + +var assert = utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + if (this.isInfinity()) + return this; + else if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + + +/***/ }), + +/***/ 6866: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curves = exports; + +var hash = __webpack_require__(5582); +var curve = __webpack_require__(6506); +var utils = __webpack_require__(8843); + +var assert = utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve.short(options); + else if (options.type === 'edwards') + this.curve = new curve.edwards(options); + else + this.curve = new curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +var pre; +try { + pre = __webpack_require__(2790); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] +}); + + +/***/ }), + +/***/ 7720: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); +var HmacDRBG = __webpack_require__(566); +var utils = __webpack_require__(8843); +var curves = __webpack_require__(6866); +var rand = __webpack_require__(2752); +var assert = utils.assert; + +var KeyPair = __webpack_require__(1888); +var Signature = __webpack_require__(2736); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8' + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + if (!this.curve._maxwellTrick) { + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + var p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; + + +/***/ }), + +/***/ 1888: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); +var utils = __webpack_require__(8843); +var assert = utils.assert; + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + + +/***/ }), + +/***/ 2736: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); + +var utils = __webpack_require__(8843); +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + + // Indefinite length or overflow + if (octetLen === 0 || octetLen > 4) { + return false; + } + + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; + } + + // Leading zeroes + if (val <= 0x7f) { + return false; + } + + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if (len === false) { + return false; + } + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + if (rlen === false) { + return false; + } + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (slen === false) { + return false; + } + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0) { + if (r[1] & 0x80) { + r = r.slice(1); + } else { + // Leading zeroes + return false; + } + } + if (s[0] === 0) { + if (s[1] & 0x80) { + s = s.slice(1); + } else { + // Leading zeroes + return false; + } + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 1774: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(5582); +var curves = __webpack_require__(6866); +var utils = __webpack_require__(8843); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = __webpack_require__(4560); +var Signature = __webpack_require__(1294); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; + + +/***/ }), + +/***/ 4560: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(8843); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; + + +/***/ }), + +/***/ 1294: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(2828); +var utils = __webpack_require__(8843); +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; + + +/***/ }), + +/***/ 2790: +/***/ ((module) => { + +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } +}; + + +/***/ }), + +/***/ 8843: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = exports; +var BN = __webpack_require__(2828); +var minAssert = __webpack_require__(6787); +var minUtils = __webpack_require__(8157); + +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; + +// Represent num in a w-NAF form +function getNAF(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + naf.fill(0); + + var ws = 1 << (w + 1); + var k = num.clone(); + + for (var i = 0; i < naf.length; i++) { + var z; + var mod = k.andln(ws - 1); + if (k.isOdd()) { + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + + naf[i] = z; + k.iushrn(1); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + + + +/***/ }), + +/***/ 9727: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = __webpack_require__(9615).Buffer +var MD5 = __webpack_require__(8575) + +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') + } + + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) + + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() + + var used = 0 + + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } + + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length + } + } + + tmp.fill(0) + return { key: key, iv: iv } +} + +module.exports = EVP_BytesToKey + + +/***/ }), + +/***/ 9086: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = __webpack_require__(9615).Buffer +var Transform = __webpack_require__(8022).Transform +var inherits = __webpack_require__(2989) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + + +/***/ }), + +/***/ 2145: +/***/ ((module) => { + +"use strict"; + + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.q = codes; + + +/***/ }), + +/***/ 7328: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = __webpack_require__(4614); + +var Writable = __webpack_require__(9213); + +__webpack_require__(2989)(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +/***/ }), + +/***/ 674: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + +module.exports = PassThrough; + +var Transform = __webpack_require__(9343); + +__webpack_require__(2989)(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 4614: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = __webpack_require__(8614).EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = __webpack_require__(9089); +/**/ + + +var Buffer = __webpack_require__(4293).Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = __webpack_require__(1669); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = __webpack_require__(7031); + +var destroyImpl = __webpack_require__(3302); + +var _require = __webpack_require__(6747), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = __webpack_require__(2145)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +__webpack_require__(2989)(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(7328); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(937)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(7328); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. + + +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(937)/* .StringDecoder */ .s; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB + + +var MAX_HWM = 0x40000000; + +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. + + +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; +} // you can override either this method, or the async _read(n) below. + + +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; +}; + +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. + + +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. + + +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. + + +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __webpack_require__(7257); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __webpack_require__(9914); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} + +/***/ }), + +/***/ 9343: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + +module.exports = Transform; + +var _require$codes = __webpack_require__(2145)/* .codes */ .q, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = __webpack_require__(7328); + +__webpack_require__(2989)(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. + + +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. + + +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} + +/***/ }), + +/***/ 9213: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream + + +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ + + +var Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: __webpack_require__(2262) +}; +/**/ + +/**/ + +var Stream = __webpack_require__(9089); +/**/ + + +var Buffer = __webpack_require__(4293).Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = __webpack_require__(3302); + +var _require = __webpack_require__(6747), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = __webpack_require__(2145)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +__webpack_require__(2989)(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(7328); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. + + +var realHasInstance; + +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(7328); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. + + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; + +Writable.prototype.cork = function () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; + +/***/ }), + +/***/ 7257: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = __webpack_require__(2713); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; + +/***/ }), + +/***/ 7031: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = __webpack_require__(4293), + Buffer = _require.Buffer; + +var _require2 = __webpack_require__(1669), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); + +/***/ }), + +/***/ 3302: +/***/ ((module) => { + +"use strict"; + // undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +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.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; + +/***/ }), + +/***/ 2713: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + +var ERR_STREAM_PREMATURE_CLOSE = __webpack_require__(2145)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; + +/***/ }), + +/***/ 9914: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var ERR_INVALID_ARG_TYPE = __webpack_require__(2145)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} + +module.exports = from; + +/***/ }), + +/***/ 4802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = __webpack_require__(2145)/* .codes */ .q, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __webpack_require__(2713); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; + +/***/ }), + +/***/ 6747: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = __webpack_require__(2145)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; + +/***/ }), + +/***/ 9089: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(2413); + + +/***/ }), + +/***/ 8022: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(2413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(4614); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(9213); + exports.Duplex = __webpack_require__(7328); + exports.Transform = __webpack_require__(9343); + exports.PassThrough = __webpack_require__(674); + exports.finished = __webpack_require__(2713); + exports.pipeline = __webpack_require__(4802); +} + + +/***/ }), + +/***/ 5582: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var hash = exports; + +hash.utils = __webpack_require__(6128); +hash.common = __webpack_require__(4803); +hash.sha = __webpack_require__(2347); +hash.ripemd = __webpack_require__(2630); +hash.hmac = __webpack_require__(3622); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; + + +/***/ }), + +/***/ 4803: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var assert = __webpack_require__(6787); + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; + + +/***/ }), + +/***/ 3622: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var assert = __webpack_require__(6787); + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + + +/***/ }), + +/***/ 2630: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var common = __webpack_require__(4803); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + + +/***/ }), + +/***/ 2347: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.sha1 = __webpack_require__(9057); +exports.sha224 = __webpack_require__(3079); +exports.sha256 = __webpack_require__(5082); +exports.sha384 = __webpack_require__(7062); +exports.sha512 = __webpack_require__(4673); + + +/***/ }), + +/***/ 9057: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var common = __webpack_require__(4803); +var shaCommon = __webpack_require__(5541); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 3079: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var SHA256 = __webpack_require__(5082); + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + + + +/***/ }), + +/***/ 5082: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var common = __webpack_require__(4803); +var shaCommon = __webpack_require__(5541); +var assert = __webpack_require__(6787); + +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; + +var BlockHash = common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 7062: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); + +var SHA512 = __webpack_require__(4673); + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + + +/***/ }), + +/***/ 4673: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var common = __webpack_require__(4803); +var assert = __webpack_require__(6787); + +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; + +var BlockHash = common.BlockHash; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + + +/***/ }), + +/***/ 5541: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(6128); +var rotr32 = utils.rotr32; + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +exports.ft_1 = ft_1; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +exports.ch32 = ch32; + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +exports.maj32 = maj32; + +function p32(x, y, z) { + return x ^ y ^ z; +} +exports.p32 = p32; + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} +exports.s0_256 = s0_256; + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} +exports.s1_256 = s1_256; + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} +exports.g0_256 = g0_256; + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} +exports.g1_256 = g1_256; + + +/***/ }), + +/***/ 6128: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(6787); +var inherits = __webpack_require__(2989); + +exports.inherits = inherits; + +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; +} + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + // Inspired by stringToUtf8ByteArray() in closure-library by Google + // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 + // Apache License 2.0 + // https://github.com/google/closure-library/blob/master/LICENSE + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = (c >> 6) | 192; + res[p++] = (c & 63) | 128; + } else if (isSurrogatePair(msg, i)) { + c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); + res[p++] = (c >> 18) | 240; + res[p++] = ((c >> 12) & 63) | 128; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } else { + res[p++] = (c >> 12) | 224; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +exports.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +exports.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +exports.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +exports.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +exports.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +exports.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +exports.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +exports.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +exports.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +exports.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +exports.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +exports.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +exports.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +exports.sum32_5 = sum32_5; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +} +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +} +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.shr64_lo = shr64_lo; + + +/***/ }), + +/***/ 566: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(5582); +var utils = __webpack_require__(8157); +var assert = __webpack_require__(6787); + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils.toArray(options.pers, options.persEnc || 'hex'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 2989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(1669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(7350); +} + + +/***/ }), + +/***/ 7350: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 8575: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(2989) +var HashBase = __webpack_require__(9086) +var Buffer = __webpack_require__(9615).Buffer + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 + + +/***/ }), + +/***/ 6787: +/***/ ((module) => { + +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + + +/***/ }), + +/***/ 8157: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + + +/***/ }), + +/***/ 9750: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + + +var asn1 = __webpack_require__(1363) + +exports.certificate = __webpack_require__(2648) + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ) +}) +exports.RSAPrivateKey = RSAPrivateKey + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ) +}) +exports.RSAPublicKey = RSAPublicKey + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) +}) +exports.PublicKey = PublicKey + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p').int(), + this.key('q').int(), + this.key('g').int() + ).optional() + ) +}) + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ) +}) +exports.PrivateKey = PrivateKeyInfo +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ) +}) + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('p').int(), + this.key('q').int(), + this.key('g').int(), + this.key('pub_key').int(), + this.key('priv_key').int() + ) +}) +exports.DSAPrivateKey = DSAPrivateKey + +exports.DSAparam = asn1.define('DSAparam', function () { + this.int() +}) + +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ) +}) +exports.ECPrivateKey = ECPrivateKey + +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }) +}) + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r').int(), + this.key('s').int() + ) +}) + + +/***/ }), + +/***/ 2648: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js +// thanks to @Rantanen + + + +var asn = __webpack_require__(1363) + +var Time = asn.define('Time', function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }) +}) + +var AttributeTypeValue = asn.define('AttributeTypeValue', function () { + this.seq().obj( + this.key('type').objid(), + this.key('value').any() + ) +}) + +var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional(), + this.key('curve').objid().optional() + ) +}) + +var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) +}) + +var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { + this.setof(AttributeTypeValue) +}) + +var RDNSequence = asn.define('RDNSequence', function () { + this.seqof(RelativeDistinguishedName) +}) + +var Name = asn.define('Name', function () { + this.choice({ + rdnSequence: this.use(RDNSequence) + }) +}) + +var Validity = asn.define('Validity', function () { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ) +}) + +var Extension = asn.define('Extension', function () { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ) +}) + +var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0).int().optional(), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ) +}) + +var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ) +}) + +module.exports = X509Certificate + + +/***/ }), + +/***/ 5831: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m +var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m +var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m +var evp = __webpack_require__(9727) +var ciphers = __webpack_require__(8855) +var Buffer = __webpack_require__(9615).Buffer +module.exports = function (okey, password) { + var key = okey.toString() + var match = key.match(findProc) + var decrypted + if (!match) { + var match2 = key.match(fullRegex) + decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64') + } else { + var suite = 'aes' + match[1] + var iv = Buffer.from(match[2], 'hex') + var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64') + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key + var out = [] + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + decrypted = Buffer.concat(out) + } + var tag = key.match(startRegex)[1] + return { + tag: tag, + data: decrypted + } +} + + +/***/ }), + +/***/ 6885: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var asn1 = __webpack_require__(9750) +var aesid = __webpack_require__(5424) +var fixProc = __webpack_require__(5831) +var ciphers = __webpack_require__(8855) +var compat = __webpack_require__(800) +var Buffer = __webpack_require__(9615).Buffer +module.exports = parseKeys + +function parseKeys (buffer) { + var password + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase + buffer = buffer.key + } + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer) + } + + var stripped = fixProc(buffer, password) + + var type = stripped.tag + var data = stripped.data + var subtype, ndata + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der') + } + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey + return { + type: 'ec', + data: ndata + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') + return { + type: 'dsa', + data: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der') + data = decrypt(data, password) + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') + return { + type: 'dsa', + params: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der') + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der') + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + } + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der') + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type) + } +} +parseKeys.signature = asn1.signature +function decrypt (data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] + var iv = data.algorithm.decrypt.cipher.iv + var cipherText = data.subjectPrivateKey + var keylen = parseInt(algo.split('-')[1], 10) / 8 + var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1') + var cipher = ciphers.createDecipheriv(algo, key, iv) + var out = [] + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + return Buffer.concat(out) +} + + +/***/ }), + +/***/ 800: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var native = __webpack_require__(6417) + +var checkParameters = __webpack_require__(9725) +var defaultEncoding = __webpack_require__(7713) +var toBuffer = __webpack_require__(3005) + +function nativePBKDF2 (password, salt, iterations, keylen, digest, callback) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + + if (typeof digest === 'function') { + callback = digest + digest = 'sha1' + } + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + return native.pbkdf2(password, salt, iterations, keylen, digest, callback) +} + +function nativePBKDF2Sync (password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + digest = digest || 'sha1' + return native.pbkdf2Sync(password, salt, iterations, keylen, digest) +} + +/* istanbul ignore next */ +if (!native.pbkdf2Sync || native.pbkdf2Sync.toString().indexOf('keylen, digest') === -1) { + exports.pbkdf2Sync = __webpack_require__(2602) + exports.pbkdf2 = __webpack_require__(9055) + +// native +} else { + exports.pbkdf2Sync = nativePBKDF2Sync + exports.pbkdf2 = nativePBKDF2 +} + + +/***/ }), + +/***/ 9055: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = __webpack_require__(9615).Buffer + +var checkParameters = __webpack_require__(9725) +var defaultEncoding = __webpack_require__(7713) +var sync = __webpack_require__(2602) +var toBuffer = __webpack_require__(3005) + +var ZERO_BUF +var subtle = global.crypto && global.crypto.subtle +var toBrowser = { + sha: 'SHA-1', + 'sha-1': 'SHA-1', + sha1: 'SHA-1', + sha256: 'SHA-256', + 'sha-256': 'SHA-256', + sha384: 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + sha512: 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom +} + +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) +} + +function resolvePromise (promise, callback) { + promise.then(function (out) { + process.nextTick(function () { + callback(null, out) + }) + }, function (e) { + process.nextTick(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] + + if (!algo || typeof global.Promise !== 'function') { + return process.nextTick(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + } + + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + + return sync(password, salt, iterations, keylen, digest) + }), callback) +} + + +/***/ }), + +/***/ 7713: +/***/ ((module) => { + +var defaultEncoding +/* istanbul ignore next */ +if (process.browser) { + defaultEncoding = 'utf-8' +} else if (process.version) { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} else { + defaultEncoding = 'utf-8' +} +module.exports = defaultEncoding + + +/***/ }), + +/***/ 9725: +/***/ ((module) => { + +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + + +/***/ }), + +/***/ 2602: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} + +var createHmac = __webpack_require__(9871) +var Buffer = __webpack_require__(9615).Buffer + +var checkParameters = __webpack_require__(9725) +var defaultEncoding = __webpack_require__(7713) +var toBuffer = __webpack_require__(3005) + +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + + digest = digest || 'sha1' + + var DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var T = createHmac(digest, password).update(block1).digest() + var U = T + + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest() + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + T.copy(DK, destPos) + destPos += hLen + } + + return DK +} + +module.exports = pbkdf2 + + +/***/ }), + +/***/ 3005: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = __webpack_require__(9615).Buffer + +module.exports = function (thing, encoding, name) { + if (Buffer.isBuffer(thing)) { + return thing + } else if (typeof thing === 'string') { + return Buffer.from(thing, encoding) + } else if (ArrayBuffer.isView(thing)) { + return Buffer.from(thing.buffer) + } else { + throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') + } +} + + +/***/ }), + +/***/ 3463: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.publicEncrypt = __webpack_require__(8944) +exports.privateDecrypt = __webpack_require__(8070) + +exports.privateEncrypt = function privateEncrypt (key, buf) { + return exports.publicEncrypt(key, buf, true) +} + +exports.publicDecrypt = function publicDecrypt (key, buf) { + return exports.privateDecrypt(key, buf, true) +} + + +/***/ }), + +/***/ 232: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) +if (typeof crypto.publicEncrypt !== 'function') { + crypto = __webpack_require__(3463) +} +exports.publicEncrypt = crypto.publicEncrypt +exports.privateDecrypt = crypto.privateDecrypt + +if (typeof crypto.privateEncrypt !== 'function') { + exports.privateEncrypt = __webpack_require__(3463).privateEncrypt +} else { + exports.privateEncrypt = crypto.privateEncrypt +} + +if (typeof crypto.publicDecrypt !== 'function') { + exports.publicDecrypt = __webpack_require__(3463).publicDecrypt +} else { + exports.publicDecrypt = crypto.publicDecrypt +} + + +/***/ }), + +/***/ 2224: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var createHash = __webpack_require__(356) +var Buffer = __webpack_require__(9615).Buffer + +module.exports = function (seed, len) { + var t = Buffer.alloc(0) + var i = 0 + var c + while (t.length < len) { + c = i2ops(i++) + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]) + } + return t.slice(0, len) +} + +function i2ops (c) { + var out = Buffer.allocUnsafe(4) + out.writeUInt32BE(c, 0) + return out +} + + +/***/ }), + +/***/ 8070: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(6885) +var mgf = __webpack_require__(2224) +var xor = __webpack_require__(8075) +var BN = __webpack_require__(2828) +var crt = __webpack_require__(4326) +var createHash = __webpack_require__(356) +var withPublic = __webpack_require__(8920) +var Buffer = __webpack_require__(9615).Buffer + +module.exports = function privateDecrypt (privateKey, enc, reverse) { + var padding + if (privateKey.padding) { + padding = privateKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + + var key = parseKeys(privateKey) + var k = key.modulus.byteLength() + if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error') + } + var msg + if (reverse) { + msg = withPublic(new BN(enc), key) + } else { + msg = crt(enc, key) + } + var zBuffer = Buffer.alloc(k - msg.length) + msg = Buffer.concat([zBuffer, msg], k) + if (padding === 4) { + return oaep(key, msg) + } else if (padding === 1) { + return pkcs1(key, msg, reverse) + } else if (padding === 3) { + return msg + } else { + throw new Error('unknown padding') + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + if (msg[0] !== 0) { + throw new Error('decryption error') + } + var maskedSeed = msg.slice(1, hLen + 1) + var maskedDb = msg.slice(hLen + 1) + var seed = xor(maskedSeed, mgf(maskedDb, hLen)) + var db = xor(maskedDb, mgf(seed, k - hLen - 1)) + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error') + } + var i = hLen + while (db[i] === 0) { + i++ + } + if (db[i++] !== 1) { + throw new Error('decryption error') + } + return db.slice(i) +} + +function pkcs1 (key, msg, reverse) { + var p1 = msg.slice(0, 2) + var i = 2 + var status = 0 + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++ + break + } + } + var ps = msg.slice(2, i - 1) + + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) { + status++ + } + if (ps.length < 8) { + status++ + } + if (status) { + throw new Error('decryption error') + } + return msg.slice(i) +} +function compare (a, b) { + a = Buffer.from(a) + b = Buffer.from(b) + var dif = 0 + var len = a.length + if (a.length !== b.length) { + dif++ + len = Math.min(a.length, b.length) + } + var i = -1 + while (++i < len) { + dif += (a[i] ^ b[i]) + } + return dif +} + + +/***/ }), + +/***/ 8944: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(6885) +var randomBytes = __webpack_require__(9822) +var createHash = __webpack_require__(356) +var mgf = __webpack_require__(2224) +var xor = __webpack_require__(8075) +var BN = __webpack_require__(2828) +var withPublic = __webpack_require__(8920) +var crt = __webpack_require__(4326) +var Buffer = __webpack_require__(9615).Buffer + +module.exports = function publicEncrypt (publicKey, msg, reverse) { + var padding + if (publicKey.padding) { + padding = publicKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + var key = parseKeys(publicKey) + var paddedMsg + if (padding === 4) { + paddedMsg = oaep(key, msg) + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse) + } else if (padding === 3) { + paddedMsg = new BN(msg) + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus') + } + } else { + throw new Error('unknown padding') + } + if (reverse) { + return crt(paddedMsg, key) + } else { + return withPublic(paddedMsg, key) + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var mLen = msg.length + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + var hLen2 = 2 * hLen + if (mLen > k - hLen2 - 2) { + throw new Error('message too long') + } + var ps = Buffer.alloc(k - mLen - hLen2 - 2) + var dblen = k - hLen - 1 + var seed = randomBytes(hLen) + var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)) + var maskedSeed = xor(seed, mgf(maskedDb, hLen)) + return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)) +} +function pkcs1 (key, msg, reverse) { + var mLen = msg.length + var k = key.modulus.byteLength() + if (mLen > k - 11) { + throw new Error('message too long') + } + var ps + if (reverse) { + ps = Buffer.alloc(k - mLen - 3, 0xff) + } else { + ps = nonZero(k - mLen - 3) + } + return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)) +} +function nonZero (len) { + var out = Buffer.allocUnsafe(len) + var i = 0 + var cache = randomBytes(len * 2) + var cur = 0 + var num + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len * 2) + cur = 0 + } + num = cache[cur++] + if (num) { + out[i++] = num + } + } + return out +} + + +/***/ }), + +/***/ 8920: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BN = __webpack_require__(2828) +var Buffer = __webpack_require__(9615).Buffer + +function withPublic (paddedMsg, key) { + return Buffer.from(paddedMsg + .toRed(BN.mont(key.modulus)) + .redPow(new BN(key.publicExponent)) + .fromRed() + .toArray()) +} + +module.exports = withPublic + + +/***/ }), + +/***/ 8075: +/***/ ((module) => { + +module.exports = function xor (a, b) { + var len = a.length + var i = -1 + while (++i < len) { + a[i] ^= b[i] + } + return a +} + + +/***/ }), + +/***/ 9822: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(6417).randomBytes + + +/***/ }), + +/***/ 4953: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function oldBrowser () { + throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') +} +var safeBuffer = __webpack_require__(9615) +var randombytes = __webpack_require__(9822) +var Buffer = safeBuffer.Buffer +var kBufferMaxLength = safeBuffer.kMaxLength +var crypto = global.crypto || global.msCrypto +var kMaxUint32 = Math.pow(2, 32) - 1 +function assertOffset (offset, length) { + if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare + throw new TypeError('offset must be a number') + } + + if (offset > kMaxUint32 || offset < 0) { + throw new TypeError('offset must be a uint32') + } + + if (offset > kBufferMaxLength || offset > length) { + throw new RangeError('offset out of range') + } +} + +function assertSize (size, offset, length) { + if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare + throw new TypeError('size must be a number') + } + + if (size > kMaxUint32 || size < 0) { + throw new TypeError('size must be a uint32') + } + + if (size + offset > length || size > kBufferMaxLength) { + throw new RangeError('buffer too small') + } +} +if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync +} else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser +} +function randomFill (buf, offset, size, cb) { + if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + if (typeof offset === 'function') { + cb = offset + offset = 0 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) +} + +function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf +} +function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + assertOffset(offset, buf.length) + + if (size === undefined) size = buf.length - offset + + assertSize(size, offset, buf.length) + + return actualFill(buf, offset, size) +} + + +/***/ }), + +/***/ 4859: +/***/ ((module, exports, __webpack_require__) => { + +var crypto = __webpack_require__(6417) +if (typeof crypto.randomFill === 'function' && typeof crypto.randomFillSync === 'function') { + exports.randomFill = crypto.randomFill + exports.randomFillSync = crypto.randomFillSync +} else { + module.exports = __webpack_require__(4953) +} + + +/***/ }), + +/***/ 9615: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(4293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 937: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(9615).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 2262: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(1669).deprecate; + + +/***/ }), + +/***/ 4293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer");; + +/***/ }), + +/***/ 6417: +/***/ ((module) => { + +"use strict"; +module.exports = require("crypto");; + +/***/ }), + +/***/ 8614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events");; + +/***/ }), + +/***/ 2413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream");; + +/***/ }), + +/***/ 1669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }), + +/***/ 2184: +/***/ ((module) => { + +"use strict"; +module.exports = require("vm");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(1223); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index3.js b/packages/next/compiled/webpack/index3.js new file mode 100644 index 000000000000000..5718b1939554be4 --- /dev/null +++ b/packages/next/compiled/webpack/index3.js @@ -0,0 +1,130 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 819: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +// This file should be ES5 compatible +/* eslint prefer-spread:0, no-var:0, prefer-reflect:0, no-magic-numbers:0 */ + + +module.exports = (function () { + // Import Events + var events = __webpack_require__(614) + + // Export Domain + var domain = {} + domain.createDomain = domain.create = function () { + var d = new events.EventEmitter() + + function emitError (e) { + d.emit('error', e) + } + + d.add = function (emitter) { + emitter.on('error', emitError) + } + d.remove = function (emitter) { + emitter.removeListener('error', emitError) + } + d.bind = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments) + try { + fn.apply(null, args) + } + catch (err) { + emitError(err) + } + } + } + d.intercept = function (fn) { + return function (err) { + if ( err ) { + emitError(err) + } + else { + var args = Array.prototype.slice.call(arguments, 1) + try { + fn.apply(null, args) + } + catch (err) { + emitError(err) + } + } + } + } + d.run = function (fn) { + try { + fn() + } + catch (err) { + emitError(err) + } + return this + } + d.dispose = function () { + this.removeAllListeners() + return this + } + d.enter = d.exit = function () { + return this + } + return d + } + return domain +}).call(this) + + +/***/ }), + +/***/ 614: +/***/ ((module) => { + +module.exports = require("events");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(819); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index4.js b/packages/next/compiled/webpack/index4.js new file mode 100644 index 000000000000000..41e3ef26e04e9f8 --- /dev/null +++ b/packages/next/compiled/webpack/index4.js @@ -0,0 +1,3848 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 503: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = __webpack_require__(605).STATUS_CODES + + +/***/ }), + +/***/ 334: +/***/ ((__unused_webpack_module, exports) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(350); +} + + +/***/ }), + +/***/ 350: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 352: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 404: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 770: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +var Readable = __webpack_require__(341); +var Writable = __webpack_require__(63); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 143: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(826); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(352); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(614).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var debugUtil = __webpack_require__(669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(878); +var destroyImpl = __webpack_require__(915); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(770); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(770); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 63: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(216) +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(915); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(770); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 878: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(788).Buffer; +var util = __webpack_require__(669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 915: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + 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(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 65: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(413); + + +/***/ }), + +/***/ 788: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 395: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 193: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(341); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(63); + exports.Duplex = __webpack_require__(770); + exports.Transform = __webpack_require__(826); + exports.PassThrough = __webpack_require__(143); +} + + +/***/ }), + +/***/ 262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ClientRequest = __webpack_require__(105) +var response = __webpack_require__(434) +var extend = __webpack_require__(791) +var statusCodes = __webpack_require__(503) +var url = __webpack_require__(835) + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] + +/***/ }), + +/***/ 594: +/***/ ((__unused_webpack_module, exports) => { + +exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) + +exports.writableStream = isFunction(global.WritableStream) + +exports.abortController = isFunction(global.AbortController) + +exports.blobConstructor = false +try { + new Blob([new ArrayBuffer(1)]) + exports.blobConstructor = true +} catch (e) {} + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (global.XMLHttpRequest) { + xhr = new global.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. +// Safari 7.1 appears to have fixed this bug. +var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' +var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +exports.vbArray = isFunction(global.VBArray) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + + +/***/ }), + +/***/ 105: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var capability = __webpack_require__(594) +var inherits = __webpack_require__(989) +var response = __webpack_require__(434) +var stream = __webpack_require__(193) +var toArrayBuffer = __webpack_require__(103) + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + if (capability.arraybuffer) { + body = toArrayBuffer(Buffer.concat(self._body)) + } else if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + var fetchTimer = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = global.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + global.clearTimeout(self._fetchTimer) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0] + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress() +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { + var self = this + self._destroyed = true + global.clearTimeout(self._fetchTimer) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setTimeout = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + + +/***/ }), + +/***/ 434: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var capability = __webpack_require__(594) +var inherits = __webpack_require__(989) +var stream = __webpack_require__(193) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(new Buffer(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + global.clearTimeout(fetchTimer) + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function () { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null) + } +} + + +/***/ }), + +/***/ 103: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = __webpack_require__(293).Buffer + +module.exports = function (buf) { + // If the buffer is backed by a Uint8Array, a faster version will work + if (buf instanceof Uint8Array) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) + } + } + + if (Buffer.isBuffer(buf)) { + // This is the slow version that will work with any Buffer + // implementation (even in old browsers) + var arrayCopy = new Uint8Array(buf.length) + var len = buf.length + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i] + } + return arrayCopy.buffer + } else { + throw new Error('Argument must be a Buffer') + } +} + + +/***/ }), + +/***/ 216: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(669).deprecate; + + +/***/ }), + +/***/ 791: +/***/ ((module) => { + +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + + +/***/ }), + +/***/ 293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer");; + +/***/ }), + +/***/ 614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events");; + +/***/ }), + +/***/ 605: +/***/ ((module) => { + +"use strict"; +module.exports = require("http");; + +/***/ }), + +/***/ 413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream");; + +/***/ }), + +/***/ 835: +/***/ ((module) => { + +"use strict"; +module.exports = require("url");; + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(262); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index5.js b/packages/next/compiled/webpack/index5.js new file mode 100644 index 000000000000000..b82eda7aec69e6e --- /dev/null +++ b/packages/next/compiled/webpack/index5.js @@ -0,0 +1,99 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 591: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var http = __webpack_require__(605) +var url = __webpack_require__(835) + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), + +/***/ 605: +/***/ ((module) => { + +"use strict"; +module.exports = require("http");; + +/***/ }), + +/***/ 835: +/***/ ((module) => { + +"use strict"; +module.exports = require("url");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(591); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index6.js b/packages/next/compiled/webpack/index6.js new file mode 100644 index 000000000000000..9e25dc3a1e25028 --- /dev/null +++ b/packages/next/compiled/webpack/index6.js @@ -0,0 +1,351 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 478: +/***/ ((__unused_webpack_module, exports) => { + +// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, +// backported and transplited with Babel, with backwards-compat fixes + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function (path) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); +}; + +function basename(path) { + if (typeof path !== 'string') path = path + ''; + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); +} + +// Uses a mixed approach for backwards-compatibility, as ext behavior changed +// in new Node.js versions, so only basename() above is backported here +exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + +exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = true + ? function (str, start, len) { return str.substr(start, len) } + : 0 +; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(478); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index7.js b/packages/next/compiled/webpack/index7.js new file mode 100644 index 000000000000000..e2a50c368565deb --- /dev/null +++ b/packages/next/compiled/webpack/index7.js @@ -0,0 +1,240 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 402: +/***/ ((module) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + + +/***/ }), + +/***/ 499: +/***/ ((module) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + + +/***/ }), + +/***/ 83: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +exports.decode = exports.parse = __webpack_require__(402); +exports.encode = exports.stringify = __webpack_require__(499); + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(83); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index8.js b/packages/next/compiled/webpack/index8.js new file mode 100644 index 000000000000000..e32cf54718bf195 --- /dev/null +++ b/packages/next/compiled/webpack/index8.js @@ -0,0 +1,3248 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 334: +/***/ ((__unused_webpack_module, exports) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(350); +} + + +/***/ }), + +/***/ 350: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 352: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 183: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = __webpack_require__(614).EventEmitter; +var inherits = __webpack_require__(906); + +inherits(Stream, EE); +Stream.Readable = __webpack_require__(193); +Stream.Writable = __webpack_require__(333); +Stream.Duplex = __webpack_require__(50); +Stream.Transform = __webpack_require__(617); +Stream.PassThrough = __webpack_require__(376); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + + +/***/ }), + +/***/ 906: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +try { + var util = __webpack_require__(669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(722); +} + + +/***/ }), + +/***/ 722: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 404: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 50: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(193).Duplex + + +/***/ }), + +/***/ 770: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +var Readable = __webpack_require__(341); +var Writable = __webpack_require__(63); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 143: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(826); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(352); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(614).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var debugUtil = __webpack_require__(669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(878); +var destroyImpl = __webpack_require__(915); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(770); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(395)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 826: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(770); + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 63: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(334)); +util.inherits = __webpack_require__(989); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(262) +}; +/**/ + +/**/ +var Stream = __webpack_require__(65); +/**/ + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(915); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(770); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(770); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 878: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(788).Buffer; +var util = __webpack_require__(669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 915: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(404); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + 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(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 65: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(413); + + +/***/ }), + +/***/ 788: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 395: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(788).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 376: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(193).PassThrough + + +/***/ }), + +/***/ 193: +/***/ ((module, exports, __webpack_require__) => { + +var Stream = __webpack_require__(413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(341); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(63); + exports.Duplex = __webpack_require__(770); + exports.Transform = __webpack_require__(826); + exports.PassThrough = __webpack_require__(143); +} + + +/***/ }), + +/***/ 617: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(193).Transform + + +/***/ }), + +/***/ 333: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Stream = __webpack_require__(413) +var Writable = __webpack_require__(63) + +if (process.env.READABLE_STREAM === 'disable') { + module.exports = Stream && Stream.Writable || Writable +} else { + module.exports = Writable +} + + +/***/ }), + +/***/ 262: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = __webpack_require__(669).deprecate; + + +/***/ }), + +/***/ 293: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer");; + +/***/ }), + +/***/ 614: +/***/ ((module) => { + +"use strict"; +module.exports = require("events");; + +/***/ }), + +/***/ 413: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream");; + +/***/ }), + +/***/ 669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util");; + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(183); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/index9.js b/packages/next/compiled/webpack/index9.js new file mode 100644 index 000000000000000..bb23aa35bce3533 --- /dev/null +++ b/packages/next/compiled/webpack/index9.js @@ -0,0 +1,63 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 946: +/***/ ((__unused_webpack_module, exports) => { + +exports.isatty = function () { return false; }; + +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.ReadStream = ReadStream; + +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.WriteStream = WriteStream; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ if(__webpack_module_cache__[moduleId]) { +/******/ return __webpack_module_cache__[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ +/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ // startup +/******/ // Load entry module and return exports +/******/ return __webpack_require__(946); +/******/ })() +; \ No newline at end of file diff --git a/packages/next/compiled/webpack/main.js b/packages/next/compiled/webpack/main.js new file mode 100644 index 000000000000000..5e5a41defd14c23 --- /dev/null +++ b/packages/next/compiled/webpack/main.js @@ -0,0 +1,308 @@ +module.exports = +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 617: +/***/ (function() { + +(function (global, undefined) { + "use strict"; + + if (global.setImmediate) { + return; + } + + var nextHandle = 1; // Spec says greater than zero + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + + function setImmediate(callback) { + // Callback can either be a function or a string + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + // Copy function arguments + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + // Store and register the task + var task = { callback: callback, args: args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + + function runIfPresent(handle) { + // From the spec: "Wait until any invocations of this algorithm started before this one have completed." + // So if we're currently running a task, we'll need to delay this invocation. + if (currentlyRunningATask) { + // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a + // "too much recursion" error. + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function () { runIfPresent(handle); }); + }; + } + + function canUsePostMessage() { + // The test against `importScripts` prevents this implementation from being installed inside a web worker, + // where `global.postMessage` means something completely different and can't be used for this purpose. + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + + function installPostMessageImplementation() { + // Installs an event handler on `global` for the `message` event: see + // * https://developer.mozilla.org/en/DOM/window.postMessage + // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && + typeof event.data === "string" && + event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + + if (global.addEventListener) { + global.addEventListener("message", onGlobalMessage, false); + } else { + global.attachEvent("onmessage", onGlobalMessage); + } + + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + // Create a