diff --git a/packages/next/compiled/conf/index.js b/packages/next/compiled/conf/index.js index 4644219baaa8f..96130b2822411 100644 --- a/packages/next/compiled/conf/index.js +++ b/packages/next/compiled/conf/index.js @@ -1 +1 @@ -module.exports=(()=>{var f={601:f=>{"use strict";f.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:f=>{"use strict";f.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}')},1414:(f,e,n)=>{"use strict";var s=n(1645),l=n(2630),v=n(7246),r=n(7837),b=n(3600),g=n(9290),w=n(1665),j=n(6989),d=n(6057);f.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=n(75);var E=n(8093);Ajv.prototype.addKeyword=E.add;Ajv.prototype.getKeyword=E.get;Ajv.prototype.removeKeyword=E.remove;Ajv.prototype.validateKeyword=E.validate;var R=n(2718);Ajv.ValidationError=R.Validation;Ajv.MissingRefError=R.MissingRef;Ajv.$dataMetaSchema=j;var A="http://json-schema.org/draft-07/schema";var F=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var p=["/properties"];function Ajv(f){if(!(this instanceof Ajv))return new Ajv(f);f=this._opts=d.copy(f)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=g(f.format);this._cache=f.cache||new v;this._loadingSchemas={};this._compilations=[];this.RULES=w();this._getId=chooseGetId(f);f.loopRequired=f.loopRequired||Infinity;if(f.errorDataPath=="property")f._errorDataPathProperty=true;if(f.serialize===undefined)f.serialize=b;this._metaOpts=getMetaSchemaOptions(this);if(f.formats)addInitialFormats(this);if(f.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof f.meta=="object")this.addMetaSchema(f.meta);if(f.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(f,e){var n;if(typeof f=="string"){n=this.getSchema(f);if(!n)throw new Error('no schema with key or ref "'+f+'"')}else{var s=this._addSchema(f);n=s.validate||this._compile(s)}var l=n(e);if(n.$async!==true)this.errors=n.errors;return l}function compile(f,e){var n=this._addSchema(f,undefined,e);return n.validate||this._compile(n)}function addSchema(f,e,n,s){if(Array.isArray(f)){for(var v=0;v{"use strict";var e=f.exports=function Cache(){this._cache={}};e.prototype.put=function Cache_put(f,e){this._cache[f]=e};e.prototype.get=function Cache_get(f){return this._cache[f]};e.prototype.del=function Cache_del(f){delete this._cache[f]};e.prototype.clear=function Cache_clear(){this._cache={}}},75:(f,e,n)=>{"use strict";var s=n(2718).MissingRef;f.exports=compileAsync;function compileAsync(f,e,n){var l=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof e=="function"){n=e;e=undefined}var v=loadMetaSchemaOf(f).then(function(){var n=l._addSchema(f,undefined,e);return n.validate||_compileAsync(n)});if(n){v.then(function(f){n(null,f)},n)}return v;function loadMetaSchemaOf(f){var e=f.$schema;return e&&!l.getSchema(e)?compileAsync.call(l,{$ref:e},true):Promise.resolve()}function _compileAsync(f){try{return l._compile(f)}catch(f){if(f instanceof s)return loadMissingSchema(f);throw f}function loadMissingSchema(n){var s=n.missingSchema;if(added(s))throw new Error("Schema "+s+" is loaded but "+n.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(f){if(!added(s)){return loadMetaSchemaOf(f).then(function(){if(!added(s))l.addSchema(f,s,undefined,e)})}}).then(function(){return _compileAsync(f)});function removePromise(){delete l._loadingSchemas[s]}function added(f){return l._refs[f]||l._schemas[f]}}}}},2718:(f,e,n)=>{"use strict";var s=n(2630);f.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(f){this.message="validation failed";this.errors=f;this.ajv=this.validation=true}MissingRefError.message=function(f,e){return"can't resolve reference "+e+" from id "+f};function MissingRefError(f,e,n){this.message=n||MissingRefError.message(f,e);this.missingRef=s.url(f,e);this.missingSchema=s.normalizeId(s.fullPath(this.missingRef))}function errorSubclass(f){f.prototype=Object.create(Error.prototype);f.prototype.constructor=f;return f}},9290:(f,e,n)=>{"use strict";var s=n(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 b=/^(?=.{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 g=/^(?:[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 w=/^(?:[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 j=/^(?:(?:[^\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 d=/^(?:(?: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 E=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var R=/^(?:\/(?:[^~/]|~0|~1)*)*$/;var A=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var F=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;f.exports=formats;function formats(f){f=f=="full"?"full":"fast";return s.copy(formats[f])}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":j,url:d,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:b,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:E,"json-pointer":R,"json-pointer-uri-fragment":A,"relative-json-pointer":F};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":w,"uri-template":j,url:d,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:b,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:E,"json-pointer":R,"json-pointer-uri-fragment":A,"relative-json-pointer":F};function isLeapYear(f){return f%4===0&&(f%100!==0||f%400===0)}function date(f){var e=f.match(l);if(!e)return false;var n=+e[1];var s=+e[2];var r=+e[3];return s>=1&&s<=12&&r>=1&&r<=(s==2&&isLeapYear(n)?29:v[s])}function time(f,e){var n=f.match(r);if(!n)return false;var s=n[1];var l=n[2];var v=n[3];var b=n[5];return(s<=23&&l<=59&&v<=59||s==23&&l==59&&v==60)&&(!e||b)}var p=/t|\s/i;function date_time(f){var e=f.split(p);return e.length==2&&date(e[0])&&time(e[1],true)}var I=/\/|:/;function uri(f){return I.test(f)&&g.test(f)}var x=/[^\\]\\Z/;function regex(f){if(x.test(f))return false;try{new RegExp(f);return true}catch(f){return false}}},1645:(f,e,n)=>{"use strict";var s=n(2630),l=n(6057),v=n(2718),r=n(3600);var b=n(6131);var g=l.ucs2length;var w=n(3933);var j=v.Validation;f.exports=compile;function compile(f,e,n,d){var E=this,R=this._opts,A=[undefined],F={},p=[],I={},x=[],z={},U=[];e=e||{schema:f,refVal:A,refs:F};var N=checkCompiling.call(this,f,e,d);var Q=this._compilations[N.index];if(N.compiling)return Q.callValidate=callValidate;var q=this._formats;var O=this.RULES;try{var C=localCompile(f,e,n,d);Q.validate=C;var L=Q.callValidate;if(L){L.schema=C.schema;L.errors=null;L.refs=C.refs;L.refVal=C.refVal;L.root=C.root;L.$async=C.$async;if(R.sourceCode)L.source=C.source}return C}finally{endCompiling.call(this,f,e,d)}function callValidate(){var f=Q.validate;var e=f.apply(this,arguments);callValidate.errors=f.errors;return e}function localCompile(f,n,r,d){var I=!n||n&&n.schema==f;if(n.schema!=e.schema)return compile.call(E,f,n,r,d);var z=f.$async===true;var N=b({isTop:true,schema:f,isRoot:I,baseId:d,root:n,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:v.MissingRef,RULES:O,validate:b,util:l,resolve:s,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:R,formats:q,logger:E.logger,self:E});N=vars(A,refValCode)+vars(p,patternCode)+vars(x,defaultCode)+vars(U,customRuleCode)+N;if(R.processCode)N=R.processCode(N,f);var Q;try{var C=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",N);Q=C(E,O,q,e,A,x,U,w,g,j);A[0]=Q}catch(f){E.logger.error("Error compiling schema, function code:",N);throw f}Q.schema=f;Q.errors=null;Q.refs=F;Q.refVal=A;Q.root=I?Q:n;if(z)Q.$async=true;if(R.sourceCode===true){Q.source={code:N,patterns:p,defaults:x}}return Q}function resolveRef(f,l,v){l=s.url(f,l);var r=F[l];var b,g;if(r!==undefined){b=A[r];g="refVal["+r+"]";return resolvedRef(b,g)}if(!v&&e.refs){var w=e.refs[l];if(w!==undefined){b=e.refVal[w];g=addLocalRef(l,b);return resolvedRef(b,g)}}g=addLocalRef(l);var j=s.call(E,localCompile,e,l);if(j===undefined){var d=n&&n[l];if(d){j=s.inlineRef(d,R.inlineRefs)?d:compile.call(E,d,e,n,f)}}if(j===undefined){removeLocalRef(l)}else{replaceLocalRef(l,j);return resolvedRef(j,g)}}function addLocalRef(f,e){var n=A.length;A[n]=e;F[f]=n;return"refVal"+n}function removeLocalRef(f){delete F[f]}function replaceLocalRef(f,e){var n=F[f];A[n]=e}function resolvedRef(f,e){return typeof f=="object"||typeof f=="boolean"?{code:e,schema:f,inline:true}:{code:e,$async:f&&!!f.$async}}function usePattern(f){var e=I[f];if(e===undefined){e=I[f]=p.length;p[e]=f}return"pattern"+e}function useDefault(f){switch(typeof f){case"boolean":case"number":return""+f;case"string":return l.toQuotedString(f);case"object":if(f===null)return"null";var e=r(f);var n=z[e];if(n===undefined){n=z[e]=x.length;x[n]=f}return"default"+n}}function useCustomRule(f,e,n,s){if(E._opts.validateSchema!==false){var l=f.definition.dependencies;if(l&&!l.every(function(f){return Object.prototype.hasOwnProperty.call(n,f)}))throw new Error("parent schema must have all required keywords: "+l.join(","));var v=f.definition.validateSchema;if(v){var r=v(e);if(!r){var b="keyword schema is invalid: "+E.errorsText(v.errors);if(E._opts.validateSchema=="log")E.logger.error(b);else throw new Error(b)}}}var g=f.definition.compile,w=f.definition.inline,j=f.definition.macro;var d;if(g){d=g.call(E,e,n,s)}else if(j){d=j.call(E,e,n,s);if(R.validateSchema!==false)E.validateSchema(d,true)}else if(w){d=w.call(E,s,f.keyword,e,n)}else{d=f.definition.validate;if(!d)return}if(d===undefined)throw new Error('custom keyword "'+f.keyword+'"failed to compile');var A=U.length;U[A]=d;return{code:"customRule"+A,validate:d}}}function checkCompiling(f,e,n){var s=compIndex.call(this,f,e,n);if(s>=0)return{index:s,compiling:true};s=this._compilations.length;this._compilations[s]={schema:f,root:e,baseId:n};return{index:s,compiling:false}}function endCompiling(f,e,n){var s=compIndex.call(this,f,e,n);if(s>=0)this._compilations.splice(s,1)}function compIndex(f,e,n){for(var s=0;s{"use strict";var s=n(4007),l=n(3933),v=n(6057),r=n(7837),b=n(2437);f.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(f,e,n){var s=this._refs[n];if(typeof s=="string"){if(this._refs[s])s=this._refs[s];else return resolve.call(this,f,e,s)}s=s||this._schemas[n];if(s instanceof r){return inlineRef(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s)}var l=resolveSchema.call(this,e,n);var v,b,g;if(l){v=l.schema;e=l.root;g=l.baseId}if(v instanceof r){b=v.validate||f.call(this,v.schema,e,undefined,g)}else if(v!==undefined){b=inlineRef(v,this._opts.inlineRefs)?v:f.call(this,v,e,undefined,g)}return b}function resolveSchema(f,e){var n=s.parse(e),l=_getFullPath(n),v=getFullPath(this._getId(f.schema));if(Object.keys(f.schema).length===0||l!==v){var b=normalizeId(l);var g=this._refs[b];if(typeof g=="string"){return resolveRecursive.call(this,f,g,n)}else if(g instanceof r){if(!g.validate)this._compile(g);f=g}else{g=this._schemas[b];if(g instanceof r){if(!g.validate)this._compile(g);if(b==normalizeId(e))return{schema:g,root:f,baseId:v};f=g}else{return}}if(!f.schema)return;v=getFullPath(this._getId(f.schema))}return getJsonPointer.call(this,n,v,f.schema,f)}function resolveRecursive(f,e,n){var s=resolveSchema.call(this,f,e);if(s){var l=s.schema;var v=s.baseId;f=s.root;var r=this._getId(l);if(r)v=resolveUrl(v,r);return getJsonPointer.call(this,n,v,l,f)}}var g=v.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(f,e,n,s){f.fragment=f.fragment||"";if(f.fragment.slice(0,1)!="/")return;var l=f.fragment.split("/");for(var r=1;r{"use strict";var s=n(4124),l=n(6057).toHash;f.exports=function rules(){var f=[{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 e=["type","$comment"];var n=["$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"];f.all=l(e);f.types=l(v);f.forEach(function(n){n.rules=n.rules.map(function(n){var l;if(typeof n=="object"){var v=Object.keys(n)[0];l=n[v];n=v;l.forEach(function(n){e.push(n);f.all[n]=true})}e.push(n);var r=f.all[n]={keyword:n,code:s[n],implements:l};return r});f.all.$comment={keyword:"$comment",code:s.$comment};if(n.type)f.types[n.type]=n});f.keywords=l(e.concat(n));f.custom={};return f}},7837:(f,e,n)=>{"use strict";var s=n(6057);f.exports=SchemaObject;function SchemaObject(f){s.copy(f,this)}},9652:f=>{"use strict";f.exports=function ucs2length(f){var e=0,n=f.length,s=0,l;while(s=55296&&l<=56319&&s{"use strict";f.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:n(3933),ucs2length:n(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(f,e){e=e||{};for(var n in f)e[n]=f[n];return e}function checkDataType(f,e,n,s){var l=s?" !== ":" === ",v=s?" || ":" && ",r=s?"!":"",b=s?"":"!";switch(f){case"null":return e+l+"null";case"array":return r+"Array.isArray("+e+")";case"object":return"("+r+e+v+"typeof "+e+l+'"object"'+v+b+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+l+'"number"'+v+b+"("+e+" % 1)"+v+e+l+e+(n?v+r+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+l+'"'+f+'"'+(n?v+r+"isFinite("+e+")":"")+")";default:return"typeof "+e+l+'"'+f+'"'}}function checkDataTypes(f,e,n){switch(f.length){case 1:return checkDataType(f[0],e,n,true);default:var s="";var l=toHash(f);if(l.array&&l.object){s=l.null?"(":"(!"+e+" || ";s+="typeof "+e+' !== "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,e,n,true);return s}}var s=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(f,e){if(Array.isArray(e)){var n=[];for(var l=0;l=e)throw new Error("Cannot access property/index "+s+" levels up, current level is "+e);return n[e-s]}if(s>e)throw new Error("Cannot access data "+s+" levels up, current level is "+e);v="data"+(e-s||"");if(!l)return v}var w=v;var j=l.split("/");for(var d=0;d{"use strict";var e=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];f.exports=function(f,n){for(var s=0;s{"use strict";var s=n(8938);f.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:f=>{"use strict";f.exports=function generate__limit(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A=e=="maximum",F=A?"exclusiveMaximum":"exclusiveMinimum",p=f.schema[F],I=f.opts.$data&&p&&p.$data,x=A?"<":">",z=A?">":"<",j=undefined;if(!(E||typeof r=="number"||r===undefined)){throw new Error(e+" must be number")}if(!(I||p===undefined||typeof p=="number"||typeof p=="boolean")){throw new Error(F+" must be number or boolean")}if(I){var U=f.util.getData(p.$data,v,f.dataPathArr),N="exclusive"+l,Q="exclType"+l,q="exclIsNumber"+l,O="op"+l,C="' + "+O+" + '";s+=" var schemaExcl"+l+" = "+U+"; ";U="schemaExcl"+l;s+=" var "+N+"; var "+Q+" = typeof "+U+"; if ("+Q+" != 'boolean' && "+Q+" != 'undefined' && "+Q+" != 'number') { ";var j=F;var L=L||[];L.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: '"+F+" should be boolean' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var J=s;s=L.pop();if(!f.compositeRule&&w){if(f.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(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+Q+" == 'number' ? ( ("+N+" = "+R+" === undefined || "+U+" "+x+"= "+R+") ? "+d+" "+z+"= "+U+" : "+d+" "+z+" "+R+" ) : ( ("+N+" = "+U+" === true) ? "+d+" "+z+"= "+R+" : "+d+" "+z+" "+R+" ) || "+d+" !== "+d+") { var op"+l+" = "+N+" ? '"+x+"' : '"+x+"='; ";if(r===undefined){j=F;g=f.errSchemaPath+"/"+F;R=U;E=I}}else{var q=typeof p=="number",C=x;if(q&&E){var O="'"+C+"'";s+=" if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" ( "+R+" === undefined || "+p+" "+x+"= "+R+" ? "+d+" "+z+"= "+p+" : "+d+" "+z+" "+R+" ) || "+d+" !== "+d+") { "}else{if(q&&r===undefined){N=true;j=F;g=f.errSchemaPath+"/"+F;R=p;z+="="}else{if(q)R=Math[A?"min":"max"](p,r);if(p===(q?R:true)){N=true;j=F;g=f.errSchemaPath+"/"+F;z+="="}else{N=false;C+="="}}var O="'"+C+"'";s+=" if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+d+" "+z+" "+R+" || "+d+" !== "+d+") { "}}j=j||e;var L=L||[];L.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limit")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { comparison: "+O+", limit: "+R+", exclusive: "+N+" } ";if(f.opts.messages!==false){s+=" , message: 'should be "+C+" ";if(E){s+="' + "+R}else{s+=""+R+"'"}}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var J=s;s=L.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},5675:f=>{"use strict";f.exports=function generate__limitItems(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxItems"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+d+".length "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitItems")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have ";if(e=="maxItems"){s+="more"}else{s+="fewer"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" items' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},6051:f=>{"use strict";f.exports=function generate__limitLength(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxLength"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}if(f.opts.unicode===false){s+=" "+d+".length "}else{s+=" ucs2length("+d+") "}s+=" "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitLength")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT be ";if(e=="maxLength"){s+="longer"}else{s+="shorter"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" characters' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},7043:f=>{"use strict";f.exports=function generate__limitProperties(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxProperties"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" Object.keys("+d+").length "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitProperties")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have ";if(e=="maxProperties"){s+="more"}else{s+="fewer"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" properties' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},3639:f=>{"use strict";f.exports=function generate_allOf(f,e,n){var s=" ";var l=f.schema[e];var v=f.schemaPath+f.util.getProperty(e);var r=f.errSchemaPath+"/"+e;var b=!f.opts.allErrors;var g=f.util.copy(f);var w="";g.level++;var j="valid"+g.level;var d=g.baseId,E=true;var R=l;if(R){var A,F=-1,p=R.length-1;while(F0||A===false:f.util.schemaHasRules(A,f.RULES.all)){E=false;g.schema=A;g.schemaPath=v+"["+F+"]";g.errSchemaPath=r+"/"+F;s+=" "+f.validate(g)+" ";g.baseId=d;if(b){s+=" if ("+j+") { ";w+="}"}}}}if(b){if(E){s+=" if (true) { "}else{s+=" "+w.slice(0,-1)+" "}}return s}},1256:f=>{"use strict";f.exports=function generate_anyOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p=r.every(function(e){return f.opts.strictKeywords?typeof e=="object"&&Object.keys(e).length>0||e===false:f.util.schemaHasRules(e,f.RULES.all)});if(p){var I=R.baseId;s+=" var "+E+" = errors; var "+d+" = false; ";var x=f.compositeRule;f.compositeRule=R.compositeRule=true;var z=r;if(z){var U,N=-1,Q=z.length-1;while(N{"use strict";f.exports=function generate_comment(f,e,n){var s=" ";var l=f.schema[e];var v=f.errSchemaPath+"/"+e;var r=!f.opts.allErrors;var b=f.util.toQuotedString(l);if(f.opts.$comment===true){s+=" console.log("+b+");"}else if(typeof f.opts.$comment=="function"){s+=" self._opts.$comment("+b+", "+f.util.toQuotedString(v)+", validate.root.schema);"}return s}},184:f=>{"use strict";f.exports=function generate_const(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!E){s+=" var schema"+l+" = validate.schema"+b+";"}s+="var "+d+" = equal("+j+", schema"+l+"); if (!"+d+") { ";var A=A||[];A.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { allowedValue: schema"+l+" } ";if(f.opts.messages!==false){s+=" , message: 'should be equal to constant' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var F=s;s=A.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},7419:f=>{"use strict";f.exports=function generate_contains(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p="i"+l,I=R.dataLevel=f.dataLevel+1,x="data"+I,z=f.baseId,U=f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all);s+="var "+E+" = errors;var "+d+";";if(U){var N=f.compositeRule;f.compositeRule=R.compositeRule=true;R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" var "+F+" = false; for (var "+p+" = 0; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var Q=j+"["+p+"]";R.dataPathArr[I]=p;var q=f.validate(R);R.baseId=z;if(f.util.varOccurences(q,x)<2){s+=" "+f.util.varReplace(q,x,Q)+" "}else{s+=" var "+x+" = "+Q+"; "+q+" "}s+=" if ("+F+") break; } ";f.compositeRule=R.compositeRule=N;s+=" "+A+" if (!"+F+") {"}else{s+=" if ("+j+".length == 0) {"}var O=O||[];O.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should contain a valid item' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var C=s;s=O.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+C+"]); "}else{s+=" validate.errors = ["+C+"]; return false; "}}else{s+=" var err = "+C+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { ";if(U){s+=" errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; } "}if(f.opts.allErrors){s+=" } "}return s}},7921:f=>{"use strict";f.exports=function generate_custom(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E="valid"+l;var R="errs__"+l;var A=f.opts.$data&&r&&r.$data,F;if(A){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";F="schema"+l}else{F=r}var p=this,I="definition"+l,x=p.definition,z="";var U,N,Q,q,O;if(A&&x.$data){O="keywordValidate"+l;var C=x.validateSchema;s+=" var "+I+" = RULES.custom['"+e+"'].definition; var "+O+" = "+I+".validate;"}else{q=f.useCustomRule(p,r,f.schema,f);if(!q)return;F="validate.schema"+b;O=q.code;U=x.compile;N=x.inline;Q=x.macro}var L=O+".errors",J="i"+l,T="ruleErr"+l,G=x.async;if(G&&!f.async)throw new Error("async keyword in sync schema");if(!(N||Q)){s+=""+L+" = null;"}s+="var "+R+" = errors;var "+E+";";if(A&&x.$data){z+="}";s+=" if ("+F+" === undefined) { "+E+" = true; } else { ";if(C){z+="}";s+=" "+E+" = "+I+".validateSchema("+F+"); if ("+E+") { "}}if(N){if(x.statements){s+=" "+q.validate+" "}else{s+=" "+E+" = "+q.validate+"; "}}else if(Q){var H=f.util.copy(f);var z="";H.level++;var X="valid"+H.level;H.schema=q.validate;H.schemaPath="";var M=f.compositeRule;f.compositeRule=H.compositeRule=true;var Y=f.validate(H).replace(/validate\.schema/g,O);f.compositeRule=H.compositeRule=M;s+=" "+Y}else{var W=W||[];W.push(s);s="";s+=" "+O+".call( ";if(f.opts.passContext){s+="this"}else{s+="self"}if(U||x.schema===false){s+=" , "+d+" "}else{s+=" , "+F+" , "+d+" , validate.schema"+f.schemaPath+" "}s+=" , (dataPath || '')";if(f.errorPath!='""'){s+=" + "+f.errorPath}var B=v?"data"+(v-1||""):"parentData",c=v?f.dataPathArr[v]:"parentDataProperty";s+=" , "+B+" , "+c+" , rootData ) ";var Z=s;s=W.pop();if(x.errors===false){s+=" "+E+" = ";if(G){s+="await "}s+=""+Z+"; "}else{if(G){L="customErrors"+l;s+=" var "+L+" = null; try { "+E+" = await "+Z+"; } catch (e) { "+E+" = false; if (e instanceof ValidationError) "+L+" = e.errors; else throw e; } "}else{s+=" "+L+" = null; "+E+" = "+Z+"; "}}}if(x.modifying){s+=" if ("+B+") "+d+" = "+B+"["+c+"];"}s+=""+z;if(x.valid){if(w){s+=" if (true) { "}}else{s+=" if ( ";if(x.valid===undefined){s+=" !";if(Q){s+=""+X}else{s+=""+E}}else{s+=" "+!x.valid+" "}s+=") { ";j=p.keyword;var W=W||[];W.push(s);s="";var W=W||[];W.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"custom")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { keyword: '"+p.keyword+"' } ";if(f.opts.messages!==false){s+=" , message: 'should pass \""+p.keyword+"\" keyword validation' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var D=s;s=W.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+D+"]); "}else{s+=" validate.errors = ["+D+"]; return false; "}}else{s+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var K=s;s=W.pop();if(N){if(x.errors){if(x.errors!="full"){s+=" for (var "+J+"="+R+"; "+J+"{"use strict";f.exports=function generate_dependencies(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;var F={},p={},I=f.opts.ownProperties;for(N in r){if(N=="__proto__")continue;var x=r[N];var z=Array.isArray(x)?p:F;z[N]=x}s+="var "+d+" = errors;";var U=f.errorPath;s+="var missing"+l+";";for(var N in p){z=p[N];if(z.length){s+=" if ( "+j+f.util.getProperty(N)+" !== undefined ";if(I){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(N)+"') "}if(w){s+=" && ( ";var Q=z;if(Q){var q,O=-1,C=Q.length-1;while(O0||x===false:f.util.schemaHasRules(x,f.RULES.all)){s+=" "+A+" = true; if ( "+j+f.util.getProperty(N)+" !== undefined ";if(I){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(N)+"') "}s+=") { ";E.schema=x;E.schemaPath=b+f.util.getProperty(N);E.errSchemaPath=g+"/"+f.util.escapeFragment(N);s+=" "+f.validate(E)+" ";E.baseId=B;s+=" } ";if(w){s+=" if ("+A+") { ";R+="}"}}}if(w){s+=" "+R+" if ("+d+" == errors) {"}return s}},9795:f=>{"use strict";f.exports=function generate_enum(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A="i"+l,F="schema"+l;if(!E){s+=" var "+F+" = validate.schema"+b+";"}s+="var "+d+";";if(E){s+=" if (schema"+l+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+l+")) "+d+" = false; else {"}s+=""+d+" = false;for (var "+A+"=0; "+A+"<"+F+".length; "+A+"++) if (equal("+j+", "+F+"["+A+"])) { "+d+" = true; break; }";if(E){s+=" } "}s+=" if (!"+d+") { ";var p=p||[];p.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { allowedValues: schema"+l+" } ";if(f.opts.messages!==false){s+=" , message: 'should be equal to one of the allowed values' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var I=s;s=p.pop();if(!f.compositeRule&&w){if(f.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+=" }";if(w){s+=" else { "}return s}},5801:f=>{"use strict";f.exports=function generate_format(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");if(f.opts.format===false){if(w){s+=" if (true) { "}return s}var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}var R=f.opts.unknownFormats,A=Array.isArray(R);if(d){var F="format"+l,p="isObject"+l,I="formatType"+l;s+=" var "+F+" = formats["+E+"]; var "+p+" = typeof "+F+" == 'object' && !("+F+" instanceof RegExp) && "+F+".validate; var "+I+" = "+p+" && "+F+".type || 'string'; if ("+p+") { ";if(f.async){s+=" var async"+l+" = "+F+".async; "}s+=" "+F+" = "+F+".validate; } if ( ";if(d){s+=" ("+E+" !== undefined && typeof "+E+" != 'string') || "}s+=" (";if(R!="ignore"){s+=" ("+E+" && !"+F+" ";if(A){s+=" && self._opts.unknownFormats.indexOf("+E+") == -1 "}s+=") || "}s+=" ("+F+" && "+I+" == '"+n+"' && !(typeof "+F+" == 'function' ? ";if(f.async){s+=" (async"+l+" ? await "+F+"("+j+") : "+F+"("+j+")) "}else{s+=" "+F+"("+j+") "}s+=" : "+F+".test("+j+"))))) {"}else{var F=f.formats[r];if(!F){if(R=="ignore"){f.logger.warn('unknown format "'+r+'" ignored in schema at path "'+f.errSchemaPath+'"');if(w){s+=" if (true) { "}return s}else if(A&&R.indexOf(r)>=0){if(w){s+=" if (true) { "}return s}else{throw new Error('unknown format "'+r+'" is used in schema at path "'+f.errSchemaPath+'"')}}var p=typeof F=="object"&&!(F instanceof RegExp)&&F.validate;var I=p&&F.type||"string";if(p){var x=F.async===true;F=F.validate}if(I!=n){if(w){s+=" if (true) { "}return s}if(x){if(!f.async)throw new Error("async format in sync schema");var z="formats"+f.util.getProperty(r)+".validate";s+=" if (!(await "+z+"("+j+"))) { "}else{s+=" if (! ";var z="formats"+f.util.getProperty(r);if(p)z+=".validate";if(typeof F=="function"){s+=" "+z+"("+j+") "}else{s+=" "+z+".test("+j+") "}s+=") { "}}var U=U||[];U.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { format: ";if(d){s+=""+E}else{s+=""+f.util.toQuotedString(r)}s+=" } ";if(f.opts.messages!==false){s+=" , message: 'should match format \"";if(d){s+="' + "+E+" + '"}else{s+=""+f.util.escapeQuotes(r)}s+="\"' "}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+f.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var N=s;s=U.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},4962:f=>{"use strict";f.exports=function generate_if(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);R.level++;var A="valid"+R.level;var F=f.schema["then"],p=f.schema["else"],I=F!==undefined&&(f.opts.strictKeywords?typeof F=="object"&&Object.keys(F).length>0||F===false:f.util.schemaHasRules(F,f.RULES.all)),x=p!==undefined&&(f.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===false:f.util.schemaHasRules(p,f.RULES.all)),z=R.baseId;if(I||x){var U;R.createErrors=false;R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" var "+E+" = errors; var "+d+" = true; ";var N=f.compositeRule;f.compositeRule=R.compositeRule=true;s+=" "+f.validate(R)+" ";R.baseId=z;R.createErrors=true;s+=" errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; } ";f.compositeRule=R.compositeRule=N;if(I){s+=" if ("+A+") { ";R.schema=f.schema["then"];R.schemaPath=f.schemaPath+".then";R.errSchemaPath=f.errSchemaPath+"/then";s+=" "+f.validate(R)+" ";R.baseId=z;s+=" "+d+" = "+A+"; ";if(I&&x){U="ifClause"+l;s+=" var "+U+" = 'then'; "}else{U="'then'"}s+=" } ";if(x){s+=" else { "}}else{s+=" if (!"+A+") { "}if(x){R.schema=f.schema["else"];R.schemaPath=f.schemaPath+".else";R.errSchemaPath=f.errSchemaPath+"/else";s+=" "+f.validate(R)+" ";R.baseId=z;s+=" "+d+" = "+A+"; ";if(I&&x){U="ifClause"+l;s+=" var "+U+" = 'else'; "}else{U="'else'"}s+=" } "}s+=" if (!"+d+") { var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { failingKeyword: "+U+" } ";if(f.opts.messages!==false){s+=" , message: 'should match \"' + "+U+" + '\" schema' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+=" } ";if(w){s+=" else { "}}else{if(w){s+=" if (true) { "}}return s}},4124:(f,e,n)=>{"use strict";f.exports={$ref:n(5746),allOf:n(3639),anyOf:n(1256),$comment:n(2660),const:n(184),contains:n(7419),dependencies:n(7299),enum:n(9795),format:n(5801),if:n(4962),items:n(9623),maximum:n(3711),minimum:n(3711),maxItems:n(5675),minItems:n(5675),maxLength:n(6051),minLength:n(6051),maxProperties:n(7043),minProperties:n(7043),multipleOf:n(9251),not:n(7739),oneOf:n(6857),pattern:n(8099),properties:n(9438),propertyNames:n(3466),required:n(8430),uniqueItems:n(2207),validate:n(6131)}},9623:f=>{"use strict";f.exports=function generate_items(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p="i"+l,I=R.dataLevel=f.dataLevel+1,x="data"+I,z=f.baseId;s+="var "+E+" = errors;var "+d+";";if(Array.isArray(r)){var U=f.schema.additionalItems;if(U===false){s+=" "+d+" = "+j+".length <= "+r.length+"; ";var N=g;g=f.errSchemaPath+"/additionalItems";s+=" if (!"+d+") { ";var Q=Q||[];Q.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+r.length+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have more than "+r.length+" items' "}if(f.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var q=s;s=Q.pop();if(!f.compositeRule&&w){if(f.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+=" } ";g=N;if(w){A+="}";s+=" else { "}}var O=r;if(O){var C,L=-1,J=O.length-1;while(L0||C===false:f.util.schemaHasRules(C,f.RULES.all)){s+=" "+F+" = true; if ("+j+".length > "+L+") { ";var T=j+"["+L+"]";R.schema=C;R.schemaPath=b+"["+L+"]";R.errSchemaPath=g+"/"+L;R.errorPath=f.util.getPathExpr(f.errorPath,L,f.opts.jsonPointers,true);R.dataPathArr[I]=L;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}s+=" } ";if(w){s+=" if ("+F+") { ";A+="}"}}}}if(typeof U=="object"&&(f.opts.strictKeywords?typeof U=="object"&&Object.keys(U).length>0||U===false:f.util.schemaHasRules(U,f.RULES.all))){R.schema=U;R.schemaPath=f.schemaPath+".additionalItems";R.errSchemaPath=f.errSchemaPath+"/additionalItems";s+=" "+F+" = true; if ("+j+".length > "+r.length+") { for (var "+p+" = "+r.length+"; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var T=j+"["+p+"]";R.dataPathArr[I]=p;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}if(w){s+=" if (!"+F+") break; "}s+=" } } ";if(w){s+=" if ("+F+") { ";A+="}"}}}else if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" for (var "+p+" = "+0+"; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var T=j+"["+p+"]";R.dataPathArr[I]=p;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}if(w){s+=" if (!"+F+") break; "}s+=" }"}if(w){s+=" "+A+" if ("+E+" == errors) {"}return s}},9251:f=>{"use strict";f.exports=function generate_multipleOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}if(!(d||typeof r=="number")){throw new Error(e+" must be number")}s+="var division"+l+";if (";if(d){s+=" "+E+" !== undefined && ( typeof "+E+" != 'number' || "}s+=" (division"+l+" = "+j+" / "+E+", ";if(f.opts.multipleOfPrecision){s+=" Math.abs(Math.round(division"+l+") - division"+l+") > 1e-"+f.opts.multipleOfPrecision+" "}else{s+=" division"+l+" !== parseInt(division"+l+") "}s+=" ) ";if(d){s+=" ) "}s+=" ) { ";var R=R||[];R.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { multipleOf: "+E+" } ";if(f.opts.messages!==false){s+=" , message: 'should be multiple of ";if(d){s+="' + "+E}else{s+=""+E+"'"}}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var A=s;s=R.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},7739:f=>{"use strict";f.exports=function generate_not(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);E.level++;var R="valid"+E.level;if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){E.schema=r;E.schemaPath=b;E.errSchemaPath=g;s+=" var "+d+" = errors; ";var A=f.compositeRule;f.compositeRule=E.compositeRule=true;E.createErrors=false;var F;if(E.opts.allErrors){F=E.opts.allErrors;E.opts.allErrors=false}s+=" "+f.validate(E)+" ";E.createErrors=true;if(F)E.opts.allErrors=F;f.compositeRule=E.compositeRule=A;s+=" if ("+R+") { ";var p=p||[];p.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var I=s;s=p.pop();if(!f.compositeRule&&w){if(f.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 { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ";if(f.opts.allErrors){s+=" } "}}else{s+=" var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(w){s+=" if (false) { "}}return s}},6857:f=>{"use strict";f.exports=function generate_oneOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p=R.baseId,I="prevValid"+l,x="passingSchemas"+l;s+="var "+E+" = errors , "+I+" = false , "+d+" = false , "+x+" = null; ";var z=f.compositeRule;f.compositeRule=R.compositeRule=true;var U=r;if(U){var N,Q=-1,q=U.length-1;while(Q0||N===false:f.util.schemaHasRules(N,f.RULES.all)){R.schema=N;R.schemaPath=b+"["+Q+"]";R.errSchemaPath=g+"/"+Q;s+=" "+f.validate(R)+" ";R.baseId=p}else{s+=" var "+F+" = true; "}if(Q){s+=" if ("+F+" && "+I+") { "+d+" = false; "+x+" = ["+x+", "+Q+"]; } else { ";A+="}"}s+=" if ("+F+") { "+d+" = "+I+" = true; "+x+" = "+Q+"; }"}}f.compositeRule=R.compositeRule=z;s+=""+A+"if (!"+d+") { var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { passingSchemas: "+x+" } ";if(f.opts.messages!==false){s+=" , message: 'should match exactly one schema in oneOf' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+="} else { errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; }";if(f.opts.allErrors){s+=" } "}return s}},8099:f=>{"use strict";f.exports=function generate_pattern(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}var R=d?"(new RegExp("+E+"))":f.usePattern(r);s+="if ( ";if(d){s+=" ("+E+" !== undefined && typeof "+E+" != 'string') || "}s+=" !"+R+".test("+j+") ) { ";var A=A||[];A.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { pattern: ";if(d){s+=""+E}else{s+=""+f.util.toQuotedString(r)}s+=" } ";if(f.opts.messages!==false){s+=" , message: 'should match pattern \"";if(d){s+="' + "+E+" + '"}else{s+=""+f.util.escapeQuotes(r)}s+="\"' "}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+f.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var F=s;s=A.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},9438:f=>{"use strict";f.exports=function generate_properties(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;var F="key"+l,p="idx"+l,I=E.dataLevel=f.dataLevel+1,x="data"+I,z="dataProperties"+l;var U=Object.keys(r||{}).filter(notProto),N=f.schema.patternProperties||{},Q=Object.keys(N).filter(notProto),q=f.schema.additionalProperties,O=U.length||Q.length,C=q===false,L=typeof q=="object"&&Object.keys(q).length,J=f.opts.removeAdditional,T=C||L||J,G=f.opts.ownProperties,H=f.baseId;var X=f.schema.required;if(X&&!(f.opts.$data&&X.$data)&&X.length8){s+=" || validate.schema"+b+".hasOwnProperty("+F+") "}else{var Y=U;if(Y){var W,B=-1,c=Y.length-1;while(B0||t===false:f.util.schemaHasRules(t,f.RULES.all)){var ff=f.util.getProperty(W),P=j+ff,ef=_&&t.default!==undefined;E.schema=t;E.schemaPath=b+ff;E.errSchemaPath=g+"/"+f.util.escapeFragment(W);E.errorPath=f.util.getPath(f.errorPath,W,f.opts.jsonPointers);E.dataPathArr[I]=f.util.toQuotedString(W);var i=f.validate(E);E.baseId=H;if(f.util.varOccurences(i,x)<2){i=f.util.varReplace(i,x,P);var nf=P}else{var nf=x;s+=" var "+x+" = "+P+"; "}if(ef){s+=" "+i+" "}else{if(M&&M[W]){s+=" if ( "+nf+" === undefined ";if(G){s+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=") { "+A+" = false; ";var y=f.errorPath,h=g,sf=f.util.escapeQuotes(W);if(f.opts._errorDataPathProperty){f.errorPath=f.util.getPath(y,W,f.opts.jsonPointers)}g=f.errSchemaPath+"/required";var a=a||[];a.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { missingProperty: '"+sf+"' } ";if(f.opts.messages!==false){s+=" , message: '";if(f.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+sf+"\\'"}s+="' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var S=s;s=a.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+S+"]); "}else{s+=" validate.errors = ["+S+"]; return false; "}}else{s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}g=h;f.errorPath=y;s+=" } else { "}else{if(w){s+=" if ( "+nf+" === undefined ";if(G){s+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=") { "+A+" = true; } else { "}else{s+=" if ("+nf+" !== undefined ";if(G){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=" ) { "}}s+=" "+i+" } "}}if(w){s+=" if ("+A+") { ";R+="}"}}}}if(Q.length){var lf=Q;if(lf){var D,vf=-1,rf=lf.length-1;while(vf0||t===false:f.util.schemaHasRules(t,f.RULES.all)){E.schema=t;E.schemaPath=f.schemaPath+".patternProperties"+f.util.getProperty(D);E.errSchemaPath=f.errSchemaPath+"/patternProperties/"+f.util.escapeFragment(D);if(G){s+=" "+z+" = "+z+" || Object.keys("+j+"); for (var "+p+"=0; "+p+"<"+z+".length; "+p+"++) { var "+F+" = "+z+"["+p+"]; "}else{s+=" for (var "+F+" in "+j+") { "}s+=" if ("+f.usePattern(D)+".test("+F+")) { ";E.errorPath=f.util.getPathExpr(f.errorPath,F,f.opts.jsonPointers);var P=j+"["+F+"]";E.dataPathArr[I]=F;var i=f.validate(E);E.baseId=H;if(f.util.varOccurences(i,x)<2){s+=" "+f.util.varReplace(i,x,P)+" "}else{s+=" var "+x+" = "+P+"; "+i+" "}if(w){s+=" if (!"+A+") break; "}s+=" } ";if(w){s+=" else "+A+" = true; "}s+=" } ";if(w){s+=" if ("+A+") { ";R+="}"}}}}}if(w){s+=" "+R+" if ("+d+" == errors) {"}return s}},3466:f=>{"use strict";f.exports=function generate_propertyNames(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;s+="var "+d+" = errors;";if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){E.schema=r;E.schemaPath=b;E.errSchemaPath=g;var F="key"+l,p="idx"+l,I="i"+l,x="' + "+F+" + '",z=E.dataLevel=f.dataLevel+1,U="data"+z,N="dataProperties"+l,Q=f.opts.ownProperties,q=f.baseId;if(Q){s+=" var "+N+" = undefined; "}if(Q){s+=" "+N+" = "+N+" || Object.keys("+j+"); for (var "+p+"=0; "+p+"<"+N+".length; "+p+"++) { var "+F+" = "+N+"["+p+"]; "}else{s+=" for (var "+F+" in "+j+") { "}s+=" var startErrs"+l+" = errors; ";var O=F;var C=f.compositeRule;f.compositeRule=E.compositeRule=true;var L=f.validate(E);E.baseId=q;if(f.util.varOccurences(L,U)<2){s+=" "+f.util.varReplace(L,U,O)+" "}else{s+=" var "+U+" = "+O+"; "+L+" "}f.compositeRule=E.compositeRule=C;s+=" if (!"+A+") { for (var "+I+"=startErrs"+l+"; "+I+"{"use strict";f.exports=function generate_ref(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.errSchemaPath+"/"+e;var g=!f.opts.allErrors;var w="data"+(v||"");var j="valid"+l;var d,E;if(r=="#"||r=="#/"){if(f.isRoot){d=f.async;E="validate"}else{d=f.root.schema.$async===true;E="root.refVal[0]"}}else{var R=f.resolveRef(f.baseId,r,f.isRoot);if(R===undefined){var A=f.MissingRefError.message(f.baseId,r);if(f.opts.missingRefs=="fail"){f.logger.error(A);var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"$ref"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(b)+" , params: { ref: '"+f.util.escapeQuotes(r)+"' } ";if(f.opts.messages!==false){s+=" , message: 'can\\'t resolve reference "+f.util.escapeQuotes(r)+"' "}if(f.opts.verbose){s+=" , schema: "+f.util.toQuotedString(r)+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+w+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&g){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}if(g){s+=" if (false) { "}}else if(f.opts.missingRefs=="ignore"){f.logger.warn(A);if(g){s+=" if (true) { "}}else{throw new f.MissingRefError(f.baseId,r,A)}}else if(R.inline){var I=f.util.copy(f);I.level++;var x="valid"+I.level;I.schema=R.schema;I.schemaPath="";I.errSchemaPath=r;var z=f.validate(I).replace(/validate\.schema/g,R.code);s+=" "+z+" ";if(g){s+=" if ("+x+") { "}}else{d=R.$async===true||f.async&&R.$async!==false;E=R.code}}if(E){var F=F||[];F.push(s);s="";if(f.opts.passContext){s+=" "+E+".call(this, "}else{s+=" "+E+"( "}s+=" "+w+", (dataPath || '')";if(f.errorPath!='""'){s+=" + "+f.errorPath}var U=v?"data"+(v-1||""):"parentData",N=v?f.dataPathArr[v]:"parentDataProperty";s+=" , "+U+" , "+N+", rootData) ";var Q=s;s=F.pop();if(d){if(!f.async)throw new Error("async schema referenced by sync schema");if(g){s+=" var "+j+"; "}s+=" try { await "+Q+"; ";if(g){s+=" "+j+" = 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(g){s+=" "+j+" = false; "}s+=" } ";if(g){s+=" if ("+j+") { "}}else{s+=" if (!"+Q+") { if (vErrors === null) vErrors = "+E+".errors; else vErrors = vErrors.concat("+E+".errors); errors = vErrors.length; } ";if(g){s+=" else { "}}}return s}},8430:f=>{"use strict";f.exports=function generate_required(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A="schema"+l;if(!E){if(r.length0||U===false:f.util.schemaHasRules(U,f.RULES.all)))){F[F.length]=I}}}}else{var F=r}}if(E||F.length){var N=f.errorPath,Q=E||F.length>=f.opts.loopRequired,q=f.opts.ownProperties;if(w){s+=" var missing"+l+"; ";if(Q){if(!E){s+=" var "+A+" = validate.schema"+b+"; "}var O="i"+l,C="schema"+l+"["+O+"]",L="' + "+C+" + '";if(f.opts._errorDataPathProperty){f.errorPath=f.util.getPathExpr(N,C,f.opts.jsonPointers)}s+=" var "+d+" = true; ";if(E){s+=" if (schema"+l+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+l+")) "+d+" = false; else {"}s+=" for (var "+O+" = 0; "+O+" < "+A+".length; "+O+"++) { "+d+" = "+j+"["+A+"["+O+"]] !== undefined ";if(q){s+=" && Object.prototype.hasOwnProperty.call("+j+", "+A+"["+O+"]) "}s+="; if (!"+d+") break; } ";if(E){s+=" } "}s+=" if (!"+d+") { ";var J=J||[];J.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { missingProperty: '"+L+"' } ";if(f.opts.messages!==false){s+=" , message: '";if(f.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+L+"\\'"}s+="' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var T=s;s=J.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+T+"]); "}else{s+=" validate.errors = ["+T+"]; return false; "}}else{s+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { "}else{s+=" if ( ";var G=F;if(G){var H,O=-1,X=G.length-1;while(O{"use strict";f.exports=function generate_uniqueItems(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if((r||E)&&f.opts.uniqueItems!==false){if(E){s+=" var "+d+"; if ("+R+" === false || "+R+" === undefined) "+d+" = true; else if (typeof "+R+" != 'boolean') "+d+" = false; else { "}s+=" var i = "+j+".length , "+d+" = true , j; if (i > 1) { ";var A=f.schema.items&&f.schema.items.type,F=Array.isArray(A);if(!A||A=="object"||A=="array"||F&&(A.indexOf("object")>=0||A.indexOf("array")>=0)){s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+j+"[i], "+j+"[j])) { "+d+" = false; break outer; } } } "}else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+j+"[i]; ";var p="checkDataType"+(F?"s":"");s+=" if ("+f.util[p](A,"item",f.opts.strictNumbers,true)+") continue; ";if(F){s+=" if (typeof item == 'string') item = '\"' + item; "}s+=" if (typeof itemIndices[item] == 'number') { "+d+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ";if(E){s+=" } "}s+=" if (!"+d+") { ";var I=I||[];I.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"uniqueItems"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { i: i, j: j } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var x=s;s=I.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+x+"]); "}else{s+=" validate.errors = ["+x+"]; return false; "}}else{s+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(w){s+=" else { "}}else{if(w){s+=" if (true) { "}}return s}},6131:f=>{"use strict";f.exports=function generate_validate(f,e,n){var s="";var l=f.schema.$async===true,v=f.util.schemaHasRulesExcept(f.schema,f.RULES.all,"$ref"),r=f.self._getId(f.schema);if(f.opts.strictKeywords){var b=f.util.schemaUnknownRules(f.schema,f.RULES.keywords);if(b){var g="unknown keyword: "+b;if(f.opts.strictKeywords==="log")f.logger.warn(g);else throw new Error(g)}}if(f.isTop){s+=" var validate = ";if(l){f.async=true;s+="async "}s+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";if(r&&(f.opts.sourceCode||f.opts.processCode)){s+=" "+("/*# sourceURL="+r+" */")+" "}}if(typeof f.schema=="boolean"||!(v||f.schema.$ref)){var e="false schema";var w=f.level;var j=f.dataLevel;var d=f.schema[e];var E=f.schemaPath+f.util.getProperty(e);var R=f.errSchemaPath+"/"+e;var A=!f.opts.allErrors;var F;var p="data"+(j||"");var I="valid"+w;if(f.schema===false){if(f.isTop){A=true}else{s+=" var "+I+" = false; "}var x=x||[];x.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(F||"false schema")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(R)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'boolean schema is false' "}if(f.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+f.schemaPath+" , data: "+p+" "}s+=" } "}else{s+=" {} "}var z=s;s=x.pop();if(!f.compositeRule&&A){if(f.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(f.isTop){if(l){s+=" return data; "}else{s+=" validate.errors = null; return true; "}}else{s+=" var "+I+" = true; "}}if(f.isTop){s+=" }; return validate; "}return s}if(f.isTop){var U=f.isTop,w=f.level=0,j=f.dataLevel=0,p="data";f.rootId=f.resolve.fullPath(f.self._getId(f.root.schema));f.baseId=f.baseId||f.rootId;delete f.isTop;f.dataPathArr=[""];if(f.schema.default!==undefined&&f.opts.useDefaults&&f.opts.strictDefaults){var N="default is ignored in the schema root";if(f.opts.strictDefaults==="log")f.logger.warn(N);else throw new Error(N)}s+=" var vErrors = null; ";s+=" var errors = 0; ";s+=" if (rootData === undefined) rootData = data; "}else{var w=f.level,j=f.dataLevel,p="data"+(j||"");if(r)f.baseId=f.resolve.url(f.baseId,r);if(l&&!f.async)throw new Error("async schema in sync schema");s+=" var errs_"+w+" = errors;"}var I="valid"+w,A=!f.opts.allErrors,Q="",q="";var F;var O=f.schema.type,C=Array.isArray(O);if(O&&f.opts.nullable&&f.schema.nullable===true){if(C){if(O.indexOf("null")==-1)O=O.concat("null")}else if(O!="null"){O=[O,"null"];C=true}}if(C&&O.length==1){O=O[0];C=false}if(f.schema.$ref&&v){if(f.opts.extendRefs=="fail"){throw new Error('$ref: validation keywords used in schema at path "'+f.errSchemaPath+'" (see option extendRefs)')}else if(f.opts.extendRefs!==true){v=false;f.logger.warn('$ref: keywords ignored in schema at path "'+f.errSchemaPath+'"')}}if(f.schema.$comment&&f.opts.$comment){s+=" "+f.RULES.all.$comment.code(f,"$comment")}if(O){if(f.opts.coerceTypes){var L=f.util.coerceToTypes(f.opts.coerceTypes,O)}var J=f.RULES.types[O];if(L||C||J===true||J&&!$shouldUseGroup(J)){var E=f.schemaPath+".type",R=f.errSchemaPath+"/type";var E=f.schemaPath+".type",R=f.errSchemaPath+"/type",T=C?"checkDataTypes":"checkDataType";s+=" if ("+f.util[T](O,p,f.opts.strictNumbers,true)+") { ";if(L){var G="dataType"+w,H="coerced"+w;s+=" var "+G+" = typeof "+p+"; var "+H+" = undefined; ";if(f.opts.coerceTypes=="array"){s+=" if ("+G+" == 'object' && Array.isArray("+p+") && "+p+".length == 1) { "+p+" = "+p+"[0]; "+G+" = typeof "+p+"; if ("+f.util.checkDataType(f.schema.type,p,f.opts.strictNumbers)+") "+H+" = "+p+"; } "}s+=" if ("+H+" !== undefined) ; ";var X=L;if(X){var M,Y=-1,W=X.length-1;while(Y{"use strict";var s=/^[a-z_$][a-z0-9_$-]*$/i;var l=n(7921);var v=n(5533);f.exports={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(f,e){var n=this.RULES;if(n.keywords[f])throw new Error("Keyword "+f+" is already defined");if(!s.test(f))throw new Error("Keyword "+f+" is not a valid identifier");if(e){this.validateKeyword(e,true);var v=e.type;if(Array.isArray(v)){for(var r=0;r{"use strict";f=n.nmd(f);const s=n(5747);const l=n(5622);const v=n(6417);const r=n(2357);const b=n(8614);const g=n(5514);const w=n(293);const j=n(6536);const d=n(7727);const E=n(8393);const R=n(1414);const A=()=>Object.create(null);const F="aes-256-cbc";delete require.cache[__filename];const p=l.dirname(f.parent&&f.parent.filename||".");const I=(f,e)=>{const n=["undefined","symbol","function"];const s=typeof e;if(n.includes(s)){throw new TypeError(`Setting a value of type \`${s}\` for key \`${f}\` is not allowed as it's not supported by JSON`)}};class Conf{constructor(f){f={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:true,serialize:f=>JSON.stringify(f,null,"\t"),deserialize:JSON.parse,accessPropertiesByDotNotation:true,...f};if(!f.cwd){if(!f.projectName){const e=j.sync(p);f.projectName=e&&JSON.parse(s.readFileSync(e,"utf8")).name}if(!f.projectName){throw new Error("Project name could not be inferred. Please specify the `projectName` option.")}f.cwd=d(f.projectName,{suffix:f.projectSuffix}).config}this._options=f;if(f.schema){if(typeof f.schema!=="object"){throw new TypeError("The `schema` option must be an object.")}const e=new R({allErrors:true,format:"full",useDefaults:true,errorDataPath:"property"});const n={type:"object",properties:f.schema};this._validator=e.compile(n)}this.events=new b;this.encryptionKey=f.encryptionKey;this.serialize=f.serialize;this.deserialize=f.deserialize;const e=f.fileExtension?`.${f.fileExtension}`:"";this.path=l.resolve(f.cwd,`${f.configName}${e}`);const n=this.store;const v=Object.assign(A(),f.defaults,n);this._validate(v);try{r.deepEqual(n,v)}catch(f){this.store=v}}_validate(f){if(!this._validator){return}const e=this._validator(f);if(!e){const f=this._validator.errors.reduce((f,{dataPath:e,message:n})=>f+` \`${e.slice(1)}\` ${n};`,"");throw new Error("Config schema violation:"+f.slice(0,-1))}}get(f,e){if(this._options.accessPropertiesByDotNotation){return g.get(this.store,f,e)}return f in this.store?this.store[f]:e}set(f,e){if(typeof f!=="string"&&typeof f!=="object"){throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof f}`)}if(typeof f!=="object"&&e===undefined){throw new TypeError("Use `delete()` to clear values")}const{store:n}=this;const s=(f,e)=>{I(f,e);if(this._options.accessPropertiesByDotNotation){g.set(n,f,e)}else{n[f]=e}};if(typeof f==="object"){const e=f;for(const[f,n]of Object.entries(e)){s(f,n)}}else{s(f,e)}this.store=n}has(f){if(this._options.accessPropertiesByDotNotation){return g.has(this.store,f)}return f in this.store}delete(f){const{store:e}=this;if(this._options.accessPropertiesByDotNotation){g.delete(e,f)}else{delete e[f]}this.store=e}clear(){this.store=A()}onDidChange(f,e){if(typeof f!=="string"){throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof f}`)}if(typeof e!=="function"){throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`)}const n=()=>this.get(f);return this.handleChange(n,e)}onDidAnyChange(f){if(typeof f!=="function"){throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof f}`)}const e=()=>this.store;return this.handleChange(e,f)}handleChange(f,e){let n=f();const s=()=>{const s=n;const l=f();try{r.deepEqual(l,s)}catch(f){n=l;e.call(this,l,s)}};this.events.on("change",s);return()=>this.events.removeListener("change",s)}get size(){return Object.keys(this.store).length}get store(){try{let f=s.readFileSync(this.path,this.encryptionKey?null:"utf8");if(this.encryptionKey){try{if(f.slice(16,17).toString()===":"){const e=f.slice(0,16);const n=v.pbkdf2Sync(this.encryptionKey,e.toString(),1e4,32,"sha512");const s=v.createDecipheriv(F,n,e);f=Buffer.concat([s.update(f.slice(17)),s.final()])}else{const e=v.createDecipher(F,this.encryptionKey);f=Buffer.concat([e.update(f),e.final()])}}catch(f){}}f=this.deserialize(f);this._validate(f);return Object.assign(A(),f)}catch(f){if(f.code==="ENOENT"){w.sync(l.dirname(this.path));return A()}if(this._options.clearInvalidConfig&&f.name==="SyntaxError"){return A()}throw f}}set store(f){w.sync(l.dirname(this.path));this._validate(f);let e=this.serialize(f);if(this.encryptionKey){const f=v.randomBytes(16);const n=v.pbkdf2Sync(this.encryptionKey,f.toString(),1e4,32,"sha512");const s=v.createCipheriv(F,n,f);e=Buffer.concat([f,Buffer.from(":"),s.update(Buffer.from(e)),s.final()])}E.sync(this.path,e);this.events.emit("change")}*[Symbol.iterator](){for(const[f,e]of Object.entries(this.store)){yield[f,e]}}}f.exports=Conf},5514:(f,e,n)=>{"use strict";const s=n(1771);const l=["__proto__","prototype","constructor"];const v=f=>!f.some(f=>l.includes(f));function getPathSegments(f){const e=f.split(".");const n=[];for(let f=0;f{"use strict";f.exports=(f=>{const e=typeof f;return f!==null&&(e==="object"||e==="function")})},8393:(f,e,n)=>{"use strict";f.exports=writeFile;f.exports.sync=writeFileSync;f.exports._getTmpname=getTmpname;f.exports._cleanupOnExit=cleanupOnExit;const s=n(5747);const l=n(8681);const v=n(2317);const r=n(5622);const b=n(3010);const g=n(4005);const{promisify:w}=n(1669);const j={};const d=function getId(){try{const f=n(5013);return f.threadId}catch(f){return 0}}();let E=0;function getTmpname(f){return f+"."+l(__filename).hash(String(process.pid)).hash(String(d)).hash(String(++E)).result()}function cleanupOnExit(f){return()=>{try{s.unlinkSync(typeof f==="function"?f():f)}catch(f){}}}function serializeActiveFile(f){return new Promise(e=>{if(!j[f])j[f]=[];j[f].push(e);if(j[f].length===1)e()})}async function writeFileAsync(f,e,n={}){if(typeof n==="string"){n={encoding:n}}let l;let d;const E=v(cleanupOnExit(()=>d));const R=r.resolve(f);try{await serializeActiveFile(R);const v=await w(s.realpath)(f).catch(()=>f);d=getTmpname(v);if(!n.mode||!n.chown){const f=await w(s.stat)(v).catch(()=>{});if(f){if(n.mode==null){n.mode=f.mode}if(n.chown==null&&process.getuid){n.chown={uid:f.uid,gid:f.gid}}}}l=await w(s.open)(d,"w",n.mode);if(n.tmpfileCreated){await n.tmpfileCreated(d)}if(b(e)){e=g(e)}if(Buffer.isBuffer(e)){await w(s.write)(l,e,0,e.length,0)}else if(e!=null){await w(s.write)(l,String(e),0,String(n.encoding||"utf8"))}if(n.fsync!==false){await w(s.fsync)(l)}await w(s.close)(l);l=null;if(n.chown){await w(s.chown)(d,n.chown.uid,n.chown.gid)}if(n.mode){await w(s.chmod)(d,n.mode)}await w(s.rename)(d,v)}finally{if(l){await w(s.close)(l).catch(()=>{})}E();await w(s.unlink)(d).catch(()=>{});j[R].shift();if(j[R].length>0){j[R][0]()}else delete j[R]}}function writeFile(f,e,n,s){if(n instanceof Function){s=n;n={}}const l=writeFileAsync(f,e,n);if(s){l.then(s,s)}return l}function writeFileSync(f,e,n){if(typeof n==="string")n={encoding:n};else if(!n)n={};try{f=s.realpathSync(f)}catch(f){}const l=getTmpname(f);if(!n.mode||!n.chown){try{const e=s.statSync(f);n=Object.assign({},n);if(!n.mode){n.mode=e.mode}if(!n.chown&&process.getuid){n.chown={uid:e.uid,gid:e.gid}}}catch(f){}}let r;const w=cleanupOnExit(l);const j=v(w);let d=true;try{r=s.openSync(l,"w",n.mode);if(n.tmpfileCreated){n.tmpfileCreated(l)}if(b(e)){e=g(e)}if(Buffer.isBuffer(e)){s.writeSync(r,e,0,e.length,0)}else if(e!=null){s.writeSync(r,String(e),0,String(n.encoding||"utf8"))}if(n.fsync!==false){s.fsyncSync(r)}s.closeSync(r);r=null;if(n.chown)s.chownSync(l,n.chown.uid,n.chown.gid);if(n.mode)s.chmodSync(l,n.mode);s.renameSync(l,f);d=false}finally{if(r){try{s.closeSync(r)}catch(f){}}j();if(d){w()}}}},7727:(f,e,n)=>{"use strict";const s=n(5622);const l=n(2087);const v=l.homedir();const r=l.tmpdir();const{env:b}=process;const g=f=>{const e=s.join(v,"Library");return{data:s.join(e,"Application Support",f),config:s.join(e,"Preferences",f),cache:s.join(e,"Caches",f),log:s.join(e,"Logs",f),temp:s.join(r,f)}};const w=f=>{const e=b.APPDATA||s.join(v,"AppData","Roaming");const n=b.LOCALAPPDATA||s.join(v,"AppData","Local");return{data:s.join(n,f,"Data"),config:s.join(e,f,"Config"),cache:s.join(n,f,"Cache"),log:s.join(n,f,"Log"),temp:s.join(r,f)}};const j=f=>{const e=s.basename(v);return{data:s.join(b.XDG_DATA_HOME||s.join(v,".local","share"),f),config:s.join(b.XDG_CONFIG_HOME||s.join(v,".config"),f),cache:s.join(b.XDG_CACHE_HOME||s.join(v,".cache"),f),log:s.join(b.XDG_STATE_HOME||s.join(v,".local","state"),f),temp:s.join(r,e,f)}};const d=(f,e)=>{if(typeof f!=="string"){throw new TypeError(`Expected string, got ${typeof f}`)}e=Object.assign({suffix:"nodejs"},e);if(e.suffix){f+=`-${e.suffix}`}if(process.platform==="darwin"){return g(f)}if(process.platform==="win32"){return w(f)}return j(f)};f.exports=d;f.exports.default=d},3933:f=>{"use strict";f.exports=function equal(f,e){if(f===e)return true;if(f&&e&&typeof f=="object"&&typeof e=="object"){if(f.constructor!==e.constructor)return false;var n,s,l;if(Array.isArray(f)){n=f.length;if(n!=e.length)return false;for(s=n;s--!==0;)if(!equal(f[s],e[s]))return false;return true}if(f.constructor===RegExp)return f.source===e.source&&f.flags===e.flags;if(f.valueOf!==Object.prototype.valueOf)return f.valueOf()===e.valueOf();if(f.toString!==Object.prototype.toString)return f.toString()===e.toString();l=Object.keys(f);n=l.length;if(n!==Object.keys(e).length)return false;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(e,l[s]))return false;for(s=n;s--!==0;){var v=l[s];if(!equal(f[v],e[v]))return false}return true}return f!==f&&e!==e}},3600:f=>{"use strict";f.exports=function(f,e){if(!e)e={};if(typeof e==="function")e={cmp:e};var n=typeof e.cycles==="boolean"?e.cycles:false;var s=e.cmp&&function(f){return function(e){return function(n,s){var l={key:n,value:e[n]};var v={key:s,value:e[s]};return f(l,v)}}}(e.cmp);var l=[];return function stringify(f){if(f&&f.toJSON&&typeof f.toJSON==="function"){f=f.toJSON()}if(f===undefined)return;if(typeof f=="number")return isFinite(f)?""+f:"null";if(typeof f!=="object")return JSON.stringify(f);var e,v;if(Array.isArray(f)){v="[";for(e=0;e{(function(){var e;function MurmurHash3(f,n){var s=this instanceof MurmurHash3?this:e;s.reset(n);if(typeof f==="string"&&f.length>0){s.hash(f)}if(s!==this){return s}}MurmurHash3.prototype.hash=function(f){var e,n,s,l,v;v=f.length;this.len+=v;n=this.k1;s=0;switch(this.rem){case 0:n^=v>s?f.charCodeAt(s++)&65535:0;case 1:n^=v>s?(f.charCodeAt(s++)&65535)<<8:0;case 2:n^=v>s?(f.charCodeAt(s++)&65535)<<16:0;case 3:n^=v>s?(f.charCodeAt(s)&255)<<24:0;n^=v>s?(f.charCodeAt(s++)&65280)>>8:0}this.rem=v+this.rem&3;v-=this.rem;if(v>0){e=this.h1;while(1){n=n*11601+(n&65535)*3432906752&4294967295;n=n<<15|n>>>17;n=n*13715+(n&65535)*461832192&4294967295;e^=n;e=e<<13|e>>>19;e=e*5+3864292196&4294967295;if(s>=v){break}n=f.charCodeAt(s++)&65535^(f.charCodeAt(s++)&65535)<<8^(f.charCodeAt(s++)&65535)<<16;l=f.charCodeAt(s++);n^=(l&255)<<24^(l&65280)>>8}n=0;switch(this.rem){case 3:n^=(f.charCodeAt(s+2)&65535)<<16;case 2:n^=(f.charCodeAt(s+1)&65535)<<8;case 1:n^=f.charCodeAt(s)&65535}this.h1=e}this.k1=n;return this};MurmurHash3.prototype.result=function(){var f,e;f=this.k1;e=this.h1;if(f>0){f=f*11601+(f&65535)*3432906752&4294967295;f=f<<15|f>>>17;f=f*13715+(f&65535)*461832192&4294967295;e^=f}e^=this.len;e^=e>>>16;e=e*51819+(e&65535)*2246770688&4294967295;e^=e>>>13;e=e*44597+(e&65535)*3266445312&4294967295;e^=e>>>16;return e>>>0};MurmurHash3.prototype.reset=function(f){this.h1=typeof f==="number"?f:0;this.rem=this.k1=this.len=0;return this};e=new MurmurHash3;if(true){f.exports=MurmurHash3}else{}})()},3010:f=>{f.exports=isTypedArray;isTypedArray.strict=isStrictTypedArray;isTypedArray.loose=isLooseTypedArray;var e=Object.prototype.toString;var n={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function isTypedArray(f){return isStrictTypedArray(f)||isLooseTypedArray(f)}function isStrictTypedArray(f){return f instanceof Int8Array||f instanceof Int16Array||f instanceof Int32Array||f instanceof Uint8Array||f instanceof Uint8ClampedArray||f instanceof Uint16Array||f instanceof Uint32Array||f instanceof Float32Array||f instanceof Float64Array}function isLooseTypedArray(f){return n[e.call(f)]}},2437:f=>{"use strict";var e=f.exports=function(f,e,n){if(typeof e=="function"){n=e;e={}}n=e.cb||n;var s=typeof n=="function"?n:n.pre||function(){};var l=n.post||function(){};_traverse(e,s,l,f,"",f)};e.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true};e.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};e.propsKeywords={definitions:true,properties:true,patternProperties:true,dependencies:true};e.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(f,n,s,l,v,r,b,g,w,j){if(l&&typeof l=="object"&&!Array.isArray(l)){n(l,v,r,b,g,w,j);for(var d in l){var E=l[d];if(Array.isArray(E)){if(d in e.arrayKeywords){for(var R=0;R{"use strict";const s=n(5747);const l=n(5622);const{promisify:v}=n(1669);const r=n(2519);const b=r.satisfies(process.version,">=10.12.0");const g=f=>{if(process.platform==="win32"){const e=/[<>:"|?*]/.test(f.replace(l.parse(f).root,""));if(e){const e=new Error(`Path contains invalid characters: ${f}`);e.code="EINVAL";throw e}}};const w=f=>{const e={mode:511&~process.umask(),fs:s};return{...e,...f}};const j=f=>{const e=new Error(`operation not permitted, mkdir '${f}'`);e.code="EPERM";e.errno=-4048;e.path=f;e.syscall="mkdir";return e};const d=async(f,e)=>{g(f);e=w(e);const n=v(e.fs.mkdir);const r=v(e.fs.stat);if(b&&e.fs.mkdir===s.mkdir){const s=l.resolve(f);await n(s,{mode:e.mode,recursive:true});return s}const d=async f=>{try{await n(f,e.mode);return f}catch(e){if(e.code==="EPERM"){throw e}if(e.code==="ENOENT"){if(l.dirname(f)===f){throw j(f)}if(e.message.includes("null bytes")){throw e}await d(l.dirname(f));return d(f)}try{const n=await r(f);if(!n.isDirectory()){throw new Error("The path is not a directory")}}catch(f){throw e}return f}};return d(l.resolve(f))};f.exports=d;f.exports.sync=((f,e)=>{g(f);e=w(e);if(b&&e.fs.mkdirSync===s.mkdirSync){const n=l.resolve(f);s.mkdirSync(n,{mode:e.mode,recursive:true});return n}const n=f=>{try{e.fs.mkdirSync(f,e.mode)}catch(s){if(s.code==="EPERM"){throw s}if(s.code==="ENOENT"){if(l.dirname(f)===f){throw j(f)}if(s.message.includes("null bytes")){throw s}n(l.dirname(f));return n(f)}try{if(!e.fs.statSync(f).isDirectory()){throw new Error("The path is not a directory")}}catch(f){throw s}}return f};return n(l.resolve(f))})},6536:(f,e,n)=>{"use strict";const s=n(4442);f.exports=(async({cwd:f}={})=>s("package.json",{cwd:f}));f.exports.sync=(({cwd:f}={})=>s.sync("package.json",{cwd:f}))},2317:(f,e,n)=>{var s=n(2357);var l=n(2935);var v=n(8614);if(typeof v!=="function"){v=v.EventEmitter}var r;if(process.__signal_exit_emitter__){r=process.__signal_exit_emitter__}else{r=process.__signal_exit_emitter__=new v;r.count=0;r.emitted={}}if(!r.infinite){r.setMaxListeners(Infinity);r.infinite=true}f.exports=function(f,e){s.equal(typeof f,"function","a callback must be provided for exit handler");if(g===false){load()}var n="exit";if(e&&e.alwaysLast){n="afterexit"}var l=function(){r.removeListener(n,f);if(r.listeners("exit").length===0&&r.listeners("afterexit").length===0){unload()}};r.on(n,f);return l};f.exports.unload=unload;function unload(){if(!g){return}g=false;l.forEach(function(f){try{process.removeListener(f,b[f])}catch(f){}});process.emit=j;process.reallyExit=w;r.count-=1}function emit(f,e,n){if(r.emitted[f]){return}r.emitted[f]=true;r.emit(f,e,n)}var b={};l.forEach(function(f){b[f]=function listener(){var e=process.listeners(f);if(e.length===r.count){unload();emit("exit",null,f);emit("afterexit",null,f);process.kill(process.pid,f)}}});f.exports.signals=function(){return l};f.exports.load=load;var g=false;function load(){if(g){return}g=true;r.count+=1;l=l.filter(function(f){try{process.on(f,b[f]);return true}catch(f){return false}});process.emit=processEmit;process.reallyExit=processReallyExit}var w=process.reallyExit;function processReallyExit(f){process.exitCode=f||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);w.call(process,process.exitCode)}var j=process.emit;function processEmit(f,e){if(f==="exit"){if(e!==undefined){process.exitCode=e}var n=j.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return n}else{return j.apply(this,arguments)}}},2935:f=>{f.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){f.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){f.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},4005:(f,e,n)=>{var s=n(3010).strict;f.exports=function typedarrayToBuffer(f){if(s(f)){var e=Buffer.from(f.buffer);if(f.byteLength!==f.buffer.byteLength){e=e.slice(f.byteOffset,f.byteOffset+f.byteLength)}return e}else{return Buffer.from(f)}}},4007:function(f,e){(function(f,n){true?n(e):0})(this,function(f){"use strict";function merge(){for(var f=arguments.length,e=Array(f),n=0;n1){e[0]=e[0].slice(0,-1);var s=e.length-1;for(var l=1;l= 0x80 (not a basic code point)","invalid-input":"Invalid input"};var x=r-b;var z=Math.floor;var U=String.fromCharCode;function error$1(f){throw new RangeError(I[f])}function map(f,e){var n=[];var s=f.length;while(s--){n[s]=e(f[s])}return n}function mapDomain(f,e){var n=f.split("@");var s="";if(n.length>1){s=n[0]+"@";f=n[1]}f=f.replace(p,".");var l=f.split(".");var v=map(l,e).join(".");return s+v}function ucs2decode(f){var e=[];var n=0;var s=f.length;while(n=55296&&l<=56319&&n>1;f+=z(f/e);for(;f>x*g>>1;s+=r){f=z(f/x)}return z(s+(x+1)*f/(f+w))};var C=function decode(f){var e=[];var n=f.length;var s=0;var l=E;var w=d;var j=f.lastIndexOf(R);if(j<0){j=0}for(var A=0;A=128){error$1("not-basic")}e.push(f.charCodeAt(A))}for(var F=j>0?j+1:0;F=n){error$1("invalid-input")}var U=Q(f.charCodeAt(F++));if(U>=r||U>z((v-s)/I)){error$1("overflow")}s+=U*I;var N=x<=w?b:x>=w+g?g:x-w;if(Uz(v/q)){error$1("overflow")}I*=q}var C=e.length+1;w=O(s-p,C,p==0);if(z(s/C)>v-l){error$1("overflow")}l+=z(s/C);s%=C;e.splice(s++,0,l)}return String.fromCodePoint.apply(String,e)};var L=function encode(f){var e=[];f=ucs2decode(f);var n=f.length;var s=E;var l=0;var w=d;var j=true;var A=false;var F=undefined;try{for(var p=f[Symbol.iterator](),I;!(j=(I=p.next()).done);j=true){var x=I.value;if(x<128){e.push(U(x))}}}catch(f){A=true;F=f}finally{try{if(!j&&p.return){p.return()}}finally{if(A){throw F}}}var N=e.length;var Q=N;if(N){e.push(R)}while(Q=s&&Xz((v-l)/M)){error$1("overflow")}l+=(C-s)*M;s=C;var Y=true;var W=false;var B=undefined;try{for(var c=f[Symbol.iterator](),Z;!(Y=(Z=c.next()).done);Y=true){var D=Z.value;if(Dv){error$1("overflow")}if(D==s){var K=l;for(var V=r;;V+=r){var y=V<=w?b:V>=w+g?g:V-w;if(K>6|192).toString(16).toUpperCase()+"%"+(e&63|128).toString(16).toUpperCase();else n="%"+(e>>12|224).toString(16).toUpperCase()+"%"+(e>>6&63|128).toString(16).toUpperCase()+"%"+(e&63|128).toString(16).toUpperCase();return n}function pctDecChars(f){var e="";var n=0;var s=f.length;while(n=194&&l<224){if(s-n>=6){var v=parseInt(f.substr(n+4,2),16);e+=String.fromCharCode((l&31)<<6|v&63)}else{e+=f.substr(n,6)}n+=6}else if(l>=224){if(s-n>=9){var r=parseInt(f.substr(n+4,2),16);var b=parseInt(f.substr(n+7,2),16);e+=String.fromCharCode((l&15)<<12|(r&63)<<6|b&63)}else{e+=f.substr(n,9)}n+=9}else{e+=f.substr(n,3);n+=3}}return e}function _normalizeComponentEncoding(f,e){function decodeUnreserved(f){var n=pctDecChars(f);return!n.match(e.UNRESERVED)?f:n}if(f.scheme)f.scheme=String(f.scheme).replace(e.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(e.NOT_SCHEME,"");if(f.userinfo!==undefined)f.userinfo=String(f.userinfo).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_USERINFO,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.host!==undefined)f.host=String(f.host).replace(e.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(e.NOT_HOST,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.path!==undefined)f.path=String(f.path).replace(e.PCT_ENCODED,decodeUnreserved).replace(f.scheme?e.NOT_PATH:e.NOT_PATH_NOSCHEME,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.query!==undefined)f.query=String(f.query).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_QUERY,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.fragment!==undefined)f.fragment=String(f.fragment).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_FRAGMENT,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);return f}function _stripLeadingZeros(f){return f.replace(/^0*(.*)/,"$1")||"0"}function _normalizeIPv4(f,e){var n=f.match(e.IPV4ADDRESS)||[];var l=s(n,2),v=l[1];if(v){return v.split(".").map(_stripLeadingZeros).join(".")}else{return f}}function _normalizeIPv6(f,e){var n=f.match(e.IPV6ADDRESS)||[];var l=s(n,3),v=l[1],r=l[2];if(v){var b=v.toLowerCase().split("::").reverse(),g=s(b,2),w=g[0],j=g[1];var d=j?j.split(":").map(_stripLeadingZeros):[];var E=w.split(":").map(_stripLeadingZeros);var R=e.IPV4ADDRESS.test(E[E.length-1]);var A=R?7:8;var F=E.length-A;var p=Array(A);for(var I=0;I1){var N=p.slice(0,z.index);var Q=p.slice(z.index+z.length);U=N.join(":")+"::"+Q.join(":")}else{U=p.join(":")}if(r){U+="%"+r}return U}else{return f}}var X=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;var M="".match(/(){0}/)[1]===undefined;function parse(f){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l={};var v=s.iri!==false?n:e;if(s.reference==="suffix")f=(s.scheme?s.scheme+":":"")+"//"+f;var r=f.match(X);if(r){if(M){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=f.indexOf("@")!==-1?r[3]:undefined;l.host=f.indexOf("//")!==-1?r[4]:undefined;l.port=parseInt(r[5],10);l.path=r[6]||"";l.query=f.indexOf("?")!==-1?r[7]:undefined;l.fragment=f.indexOf("#")!==-1?r[8]:undefined;if(isNaN(l.port)){l.port=f.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 b=H[(s.scheme||l.scheme||"").toLowerCase()];if(!s.unicodeSupport&&(!b||!b.unicodeSupport)){if(l.host&&(s.domainHost||b&&b.domainHost)){try{l.host=G.toASCII(l.host.replace(v.PCT_ENCODED,pctDecChars).toLowerCase())}catch(f){l.error=l.error||"Host's domain name can not be converted to ASCII via punycode: "+f}}_normalizeComponentEncoding(l,e)}else{_normalizeComponentEncoding(l,v)}if(b&&b.parse){b.parse(l,s)}}else{l.error=l.error||"URI can not be parsed."}return l}function _recomposeAuthority(f,s){var l=s.iri!==false?n:e;var v=[];if(f.userinfo!==undefined){v.push(f.userinfo);v.push("@")}if(f.host!==undefined){v.push(_normalizeIPv6(_normalizeIPv4(String(f.host),l),l).replace(l.IPV6ADDRESS,function(f,e,n){return"["+e+(n?"%25"+n:"")+"]"}))}if(typeof f.port==="number"){v.push(":");v.push(f.port.toString(10))}return v.length?v.join(""):undefined}var Y=/^\.\.?\//;var W=/^\/\.(\/|$)/;var B=/^\/\.\.(\/|$)/;var c=/^\/?(?:.|\n)*?(?=\/|$)/;function removeDotSegments(f){var e=[];while(f.length){if(f.match(Y)){f=f.replace(Y,"")}else if(f.match(W)){f=f.replace(W,"/")}else if(f.match(B)){f=f.replace(B,"/");e.pop()}else if(f==="."||f===".."){f=""}else{var n=f.match(c);if(n){var s=n[0];f=f.slice(s.length);e.push(s)}else{throw new Error("Unexpected dot segment condition")}}}return e.join("")}function serialize(f){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l=s.iri?n:e;var v=[];var r=H[(s.scheme||f.scheme||"").toLowerCase()];if(r&&r.serialize)r.serialize(f,s);if(f.host){if(l.IPV6ADDRESS.test(f.host)){}else if(s.domainHost||r&&r.domainHost){try{f.host=!s.iri?G.toASCII(f.host.replace(l.PCT_ENCODED,pctDecChars).toLowerCase()):G.toUnicode(f.host)}catch(e){f.error=f.error||"Host's domain name can not be converted to "+(!s.iri?"ASCII":"Unicode")+" via punycode: "+e}}}_normalizeComponentEncoding(f,l);if(s.reference!=="suffix"&&f.scheme){v.push(f.scheme);v.push(":")}var b=_recomposeAuthority(f,s);if(b!==undefined){if(s.reference!=="suffix"){v.push("//")}v.push(b);if(f.path&&f.path.charAt(0)!=="/"){v.push("/")}}if(f.path!==undefined){var g=f.path;if(!s.absolutePath&&(!r||!r.absolutePath)){g=removeDotSegments(g)}if(b===undefined){g=g.replace(/^\/\//,"/%2F")}v.push(g)}if(f.query!==undefined){v.push("?");v.push(f.query)}if(f.fragment!==undefined){v.push("#");v.push(f.fragment)}return v.join("")}function resolveComponents(f,e){var n=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var s=arguments[3];var l={};if(!s){f=parse(serialize(f,n),n);e=parse(serialize(e,n),n)}n=n||{};if(!n.tolerant&&e.scheme){l.scheme=e.scheme;l.userinfo=e.userinfo;l.host=e.host;l.port=e.port;l.path=removeDotSegments(e.path||"");l.query=e.query}else{if(e.userinfo!==undefined||e.host!==undefined||e.port!==undefined){l.userinfo=e.userinfo;l.host=e.host;l.port=e.port;l.path=removeDotSegments(e.path||"");l.query=e.query}else{if(!e.path){l.path=f.path;if(e.query!==undefined){l.query=e.query}else{l.query=f.query}}else{if(e.path.charAt(0)==="/"){l.path=removeDotSegments(e.path)}else{if((f.userinfo!==undefined||f.host!==undefined||f.port!==undefined)&&!f.path){l.path="/"+e.path}else if(!f.path){l.path=e.path}else{l.path=f.path.slice(0,f.path.lastIndexOf("/")+1)+e.path}l.path=removeDotSegments(l.path)}l.query=e.query}l.userinfo=f.userinfo;l.host=f.host;l.port=f.port}l.scheme=f.scheme}l.fragment=e.fragment;return l}function resolve(f,e,n){var s=assign({scheme:"null"},n);return serialize(resolveComponents(parse(f,s),parse(e,s),s,true),s)}function normalize(f,e){if(typeof f==="string"){f=serialize(parse(f,e),e)}else if(typeOf(f)==="object"){f=parse(serialize(f,e),e)}return f}function equal(f,e,n){if(typeof f==="string"){f=serialize(parse(f,n),n)}else if(typeOf(f)==="object"){f=serialize(f,n)}if(typeof e==="string"){e=serialize(parse(e,n),n)}else if(typeOf(e)==="object"){e=serialize(e,n)}return f===e}function escapeComponent(f,s){return f&&f.toString().replace(!s||!s.iri?e.ESCAPE:n.ESCAPE,pctEncChar)}function unescapeComponent(f,s){return f&&f.toString().replace(!s||!s.iri?e.PCT_ENCODED:n.PCT_ENCODED,pctDecChars)}var Z={scheme:"http",domainHost:true,parse:function parse(f,e){if(!f.host){f.error=f.error||"HTTP URIs must have a host."}return f},serialize:function serialize(f,e){if(f.port===(String(f.scheme).toLowerCase()!=="https"?80:443)||f.port===""){f.port=undefined}if(!f.path){f.path="/"}return f}};var D={scheme:"https",domainHost:Z.domainHost,parse:Z.parse,serialize:Z.serialize};var K={};var V=true;var y="[A-Za-z0-9\\-\\.\\_\\~"+(V?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]";var k="[0-9A-Fa-f]";var h=subexp(subexp("%[EFef]"+k+"%"+k+k+"%"+k+k)+"|"+subexp("%[89A-Fa-f]"+k+"%"+k+k)+"|"+subexp("%"+k+k));var a="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";var S="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";var m=merge(S,'[\\"\\\\]');var P="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";var i=new RegExp(y,"g");var _=new RegExp(h,"g");var u=new RegExp(merge("[^]",a,"[\\.]",'[\\"]',m),"g");var o=new RegExp(merge("[^]",y,P),"g");var $=o;function decodeUnreserved(f){var e=pctDecChars(f);return!e.match(i)?f:e}var t={scheme:"mailto",parse:function parse$$1(f,e){var n=f;var s=n.to=n.path?n.path.split(","):[];n.path=undefined;if(n.query){var l=false;var v={};var r=n.query.split("&");for(var b=0,g=r.length;b{"use strict";f.exports=require("assert")},6417:f=>{"use strict";f.exports=require("crypto")},8614:f=>{"use strict";f.exports=require("events")},5747:f=>{"use strict";f.exports=require("fs")},4442:f=>{"use strict";f.exports=require("next/dist/compiled/find-up")},2519:f=>{"use strict";f.exports=require("next/dist/compiled/semver")},2087:f=>{"use strict";f.exports=require("os")},5622:f=>{"use strict";f.exports=require("path")},1669:f=>{"use strict";f.exports=require("util")},5013:f=>{"use strict";f.exports=require("worker_threads")}};var e={};function __nccwpck_require__(n){if(e[n]){return e[n].exports}var s=e[n]={id:n,loaded:false,exports:{}};var l=true;try{f[n].call(s.exports,s,s.exports,__nccwpck_require__);l=false}finally{if(l)delete e[n]}s.loaded=true;return s.exports}(()=>{__nccwpck_require__.nmd=(f=>{f.paths=[];if(!f.children)f.children=[];return f})})();__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(3331)})(); \ No newline at end of file +module.exports=(()=>{var f={601:f=>{"use strict";f.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:f=>{"use strict";f.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}')},1414:(f,e,n)=>{"use strict";var s=n(1645),l=n(2630),v=n(7246),r=n(7837),b=n(3600),g=n(9290),w=n(1665),j=n(6989),d=n(6057);f.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=n(75);var E=n(8093);Ajv.prototype.addKeyword=E.add;Ajv.prototype.getKeyword=E.get;Ajv.prototype.removeKeyword=E.remove;Ajv.prototype.validateKeyword=E.validate;var R=n(2718);Ajv.ValidationError=R.Validation;Ajv.MissingRefError=R.MissingRef;Ajv.$dataMetaSchema=j;var A="http://json-schema.org/draft-07/schema";var F=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var p=["/properties"];function Ajv(f){if(!(this instanceof Ajv))return new Ajv(f);f=this._opts=d.copy(f)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=g(f.format);this._cache=f.cache||new v;this._loadingSchemas={};this._compilations=[];this.RULES=w();this._getId=chooseGetId(f);f.loopRequired=f.loopRequired||Infinity;if(f.errorDataPath=="property")f._errorDataPathProperty=true;if(f.serialize===undefined)f.serialize=b;this._metaOpts=getMetaSchemaOptions(this);if(f.formats)addInitialFormats(this);if(f.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof f.meta=="object")this.addMetaSchema(f.meta);if(f.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(f,e){var n;if(typeof f=="string"){n=this.getSchema(f);if(!n)throw new Error('no schema with key or ref "'+f+'"')}else{var s=this._addSchema(f);n=s.validate||this._compile(s)}var l=n(e);if(n.$async!==true)this.errors=n.errors;return l}function compile(f,e){var n=this._addSchema(f,undefined,e);return n.validate||this._compile(n)}function addSchema(f,e,n,s){if(Array.isArray(f)){for(var v=0;v{"use strict";var e=f.exports=function Cache(){this._cache={}};e.prototype.put=function Cache_put(f,e){this._cache[f]=e};e.prototype.get=function Cache_get(f){return this._cache[f]};e.prototype.del=function Cache_del(f){delete this._cache[f]};e.prototype.clear=function Cache_clear(){this._cache={}}},75:(f,e,n)=>{"use strict";var s=n(2718).MissingRef;f.exports=compileAsync;function compileAsync(f,e,n){var l=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof e=="function"){n=e;e=undefined}var v=loadMetaSchemaOf(f).then(function(){var n=l._addSchema(f,undefined,e);return n.validate||_compileAsync(n)});if(n){v.then(function(f){n(null,f)},n)}return v;function loadMetaSchemaOf(f){var e=f.$schema;return e&&!l.getSchema(e)?compileAsync.call(l,{$ref:e},true):Promise.resolve()}function _compileAsync(f){try{return l._compile(f)}catch(f){if(f instanceof s)return loadMissingSchema(f);throw f}function loadMissingSchema(n){var s=n.missingSchema;if(added(s))throw new Error("Schema "+s+" is loaded but "+n.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(f){if(!added(s)){return loadMetaSchemaOf(f).then(function(){if(!added(s))l.addSchema(f,s,undefined,e)})}}).then(function(){return _compileAsync(f)});function removePromise(){delete l._loadingSchemas[s]}function added(f){return l._refs[f]||l._schemas[f]}}}}},2718:(f,e,n)=>{"use strict";var s=n(2630);f.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(f){this.message="validation failed";this.errors=f;this.ajv=this.validation=true}MissingRefError.message=function(f,e){return"can't resolve reference "+e+" from id "+f};function MissingRefError(f,e,n){this.message=n||MissingRefError.message(f,e);this.missingRef=s.url(f,e);this.missingSchema=s.normalizeId(s.fullPath(this.missingRef))}function errorSubclass(f){f.prototype=Object.create(Error.prototype);f.prototype.constructor=f;return f}},9290:(f,e,n)=>{"use strict";var s=n(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 b=/^(?=.{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 g=/^(?:[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 w=/^(?:[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 j=/^(?:(?:[^\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 d=/^(?:(?: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 E=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var R=/^(?:\/(?:[^~/]|~0|~1)*)*$/;var A=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var F=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;f.exports=formats;function formats(f){f=f=="full"?"full":"fast";return s.copy(formats[f])}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":j,url:d,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:b,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:E,"json-pointer":R,"json-pointer-uri-fragment":A,"relative-json-pointer":F};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":w,"uri-template":j,url:d,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:b,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:E,"json-pointer":R,"json-pointer-uri-fragment":A,"relative-json-pointer":F};function isLeapYear(f){return f%4===0&&(f%100!==0||f%400===0)}function date(f){var e=f.match(l);if(!e)return false;var n=+e[1];var s=+e[2];var r=+e[3];return s>=1&&s<=12&&r>=1&&r<=(s==2&&isLeapYear(n)?29:v[s])}function time(f,e){var n=f.match(r);if(!n)return false;var s=n[1];var l=n[2];var v=n[3];var b=n[5];return(s<=23&&l<=59&&v<=59||s==23&&l==59&&v==60)&&(!e||b)}var p=/t|\s/i;function date_time(f){var e=f.split(p);return e.length==2&&date(e[0])&&time(e[1],true)}var I=/\/|:/;function uri(f){return I.test(f)&&g.test(f)}var x=/[^\\]\\Z/;function regex(f){if(x.test(f))return false;try{new RegExp(f);return true}catch(f){return false}}},1645:(f,e,n)=>{"use strict";var s=n(2630),l=n(6057),v=n(2718),r=n(3600);var b=n(6131);var g=l.ucs2length;var w=n(3933);var j=v.Validation;f.exports=compile;function compile(f,e,n,d){var E=this,R=this._opts,A=[undefined],F={},p=[],I={},x=[],z={},U=[];e=e||{schema:f,refVal:A,refs:F};var N=checkCompiling.call(this,f,e,d);var Q=this._compilations[N.index];if(N.compiling)return Q.callValidate=callValidate;var q=this._formats;var O=this.RULES;try{var C=localCompile(f,e,n,d);Q.validate=C;var L=Q.callValidate;if(L){L.schema=C.schema;L.errors=null;L.refs=C.refs;L.refVal=C.refVal;L.root=C.root;L.$async=C.$async;if(R.sourceCode)L.source=C.source}return C}finally{endCompiling.call(this,f,e,d)}function callValidate(){var f=Q.validate;var e=f.apply(this,arguments);callValidate.errors=f.errors;return e}function localCompile(f,n,r,d){var I=!n||n&&n.schema==f;if(n.schema!=e.schema)return compile.call(E,f,n,r,d);var z=f.$async===true;var N=b({isTop:true,schema:f,isRoot:I,baseId:d,root:n,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:v.MissingRef,RULES:O,validate:b,util:l,resolve:s,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:R,formats:q,logger:E.logger,self:E});N=vars(A,refValCode)+vars(p,patternCode)+vars(x,defaultCode)+vars(U,customRuleCode)+N;if(R.processCode)N=R.processCode(N,f);var Q;try{var C=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",N);Q=C(E,O,q,e,A,x,U,w,g,j);A[0]=Q}catch(f){E.logger.error("Error compiling schema, function code:",N);throw f}Q.schema=f;Q.errors=null;Q.refs=F;Q.refVal=A;Q.root=I?Q:n;if(z)Q.$async=true;if(R.sourceCode===true){Q.source={code:N,patterns:p,defaults:x}}return Q}function resolveRef(f,l,v){l=s.url(f,l);var r=F[l];var b,g;if(r!==undefined){b=A[r];g="refVal["+r+"]";return resolvedRef(b,g)}if(!v&&e.refs){var w=e.refs[l];if(w!==undefined){b=e.refVal[w];g=addLocalRef(l,b);return resolvedRef(b,g)}}g=addLocalRef(l);var j=s.call(E,localCompile,e,l);if(j===undefined){var d=n&&n[l];if(d){j=s.inlineRef(d,R.inlineRefs)?d:compile.call(E,d,e,n,f)}}if(j===undefined){removeLocalRef(l)}else{replaceLocalRef(l,j);return resolvedRef(j,g)}}function addLocalRef(f,e){var n=A.length;A[n]=e;F[f]=n;return"refVal"+n}function removeLocalRef(f){delete F[f]}function replaceLocalRef(f,e){var n=F[f];A[n]=e}function resolvedRef(f,e){return typeof f=="object"||typeof f=="boolean"?{code:e,schema:f,inline:true}:{code:e,$async:f&&!!f.$async}}function usePattern(f){var e=I[f];if(e===undefined){e=I[f]=p.length;p[e]=f}return"pattern"+e}function useDefault(f){switch(typeof f){case"boolean":case"number":return""+f;case"string":return l.toQuotedString(f);case"object":if(f===null)return"null";var e=r(f);var n=z[e];if(n===undefined){n=z[e]=x.length;x[n]=f}return"default"+n}}function useCustomRule(f,e,n,s){if(E._opts.validateSchema!==false){var l=f.definition.dependencies;if(l&&!l.every(function(f){return Object.prototype.hasOwnProperty.call(n,f)}))throw new Error("parent schema must have all required keywords: "+l.join(","));var v=f.definition.validateSchema;if(v){var r=v(e);if(!r){var b="keyword schema is invalid: "+E.errorsText(v.errors);if(E._opts.validateSchema=="log")E.logger.error(b);else throw new Error(b)}}}var g=f.definition.compile,w=f.definition.inline,j=f.definition.macro;var d;if(g){d=g.call(E,e,n,s)}else if(j){d=j.call(E,e,n,s);if(R.validateSchema!==false)E.validateSchema(d,true)}else if(w){d=w.call(E,s,f.keyword,e,n)}else{d=f.definition.validate;if(!d)return}if(d===undefined)throw new Error('custom keyword "'+f.keyword+'"failed to compile');var A=U.length;U[A]=d;return{code:"customRule"+A,validate:d}}}function checkCompiling(f,e,n){var s=compIndex.call(this,f,e,n);if(s>=0)return{index:s,compiling:true};s=this._compilations.length;this._compilations[s]={schema:f,root:e,baseId:n};return{index:s,compiling:false}}function endCompiling(f,e,n){var s=compIndex.call(this,f,e,n);if(s>=0)this._compilations.splice(s,1)}function compIndex(f,e,n){for(var s=0;s{"use strict";var s=n(4007),l=n(3933),v=n(6057),r=n(7837),b=n(2437);f.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(f,e,n){var s=this._refs[n];if(typeof s=="string"){if(this._refs[s])s=this._refs[s];else return resolve.call(this,f,e,s)}s=s||this._schemas[n];if(s instanceof r){return inlineRef(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s)}var l=resolveSchema.call(this,e,n);var v,b,g;if(l){v=l.schema;e=l.root;g=l.baseId}if(v instanceof r){b=v.validate||f.call(this,v.schema,e,undefined,g)}else if(v!==undefined){b=inlineRef(v,this._opts.inlineRefs)?v:f.call(this,v,e,undefined,g)}return b}function resolveSchema(f,e){var n=s.parse(e),l=_getFullPath(n),v=getFullPath(this._getId(f.schema));if(Object.keys(f.schema).length===0||l!==v){var b=normalizeId(l);var g=this._refs[b];if(typeof g=="string"){return resolveRecursive.call(this,f,g,n)}else if(g instanceof r){if(!g.validate)this._compile(g);f=g}else{g=this._schemas[b];if(g instanceof r){if(!g.validate)this._compile(g);if(b==normalizeId(e))return{schema:g,root:f,baseId:v};f=g}else{return}}if(!f.schema)return;v=getFullPath(this._getId(f.schema))}return getJsonPointer.call(this,n,v,f.schema,f)}function resolveRecursive(f,e,n){var s=resolveSchema.call(this,f,e);if(s){var l=s.schema;var v=s.baseId;f=s.root;var r=this._getId(l);if(r)v=resolveUrl(v,r);return getJsonPointer.call(this,n,v,l,f)}}var g=v.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(f,e,n,s){f.fragment=f.fragment||"";if(f.fragment.slice(0,1)!="/")return;var l=f.fragment.split("/");for(var r=1;r{"use strict";var s=n(4124),l=n(6057).toHash;f.exports=function rules(){var f=[{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 e=["type","$comment"];var n=["$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"];f.all=l(e);f.types=l(v);f.forEach(function(n){n.rules=n.rules.map(function(n){var l;if(typeof n=="object"){var v=Object.keys(n)[0];l=n[v];n=v;l.forEach(function(n){e.push(n);f.all[n]=true})}e.push(n);var r=f.all[n]={keyword:n,code:s[n],implements:l};return r});f.all.$comment={keyword:"$comment",code:s.$comment};if(n.type)f.types[n.type]=n});f.keywords=l(e.concat(n));f.custom={};return f}},7837:(f,e,n)=>{"use strict";var s=n(6057);f.exports=SchemaObject;function SchemaObject(f){s.copy(f,this)}},9652:f=>{"use strict";f.exports=function ucs2length(f){var e=0,n=f.length,s=0,l;while(s=55296&&l<=56319&&s{"use strict";f.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:n(3933),ucs2length:n(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(f,e){e=e||{};for(var n in f)e[n]=f[n];return e}function checkDataType(f,e,n,s){var l=s?" !== ":" === ",v=s?" || ":" && ",r=s?"!":"",b=s?"":"!";switch(f){case"null":return e+l+"null";case"array":return r+"Array.isArray("+e+")";case"object":return"("+r+e+v+"typeof "+e+l+'"object"'+v+b+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+l+'"number"'+v+b+"("+e+" % 1)"+v+e+l+e+(n?v+r+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+l+'"'+f+'"'+(n?v+r+"isFinite("+e+")":"")+")";default:return"typeof "+e+l+'"'+f+'"'}}function checkDataTypes(f,e,n){switch(f.length){case 1:return checkDataType(f[0],e,n,true);default:var s="";var l=toHash(f);if(l.array&&l.object){s=l.null?"(":"(!"+e+" || ";s+="typeof "+e+' !== "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,e,n,true);return s}}var s=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(f,e){if(Array.isArray(e)){var n=[];for(var l=0;l=e)throw new Error("Cannot access property/index "+s+" levels up, current level is "+e);return n[e-s]}if(s>e)throw new Error("Cannot access data "+s+" levels up, current level is "+e);v="data"+(e-s||"");if(!l)return v}var w=v;var j=l.split("/");for(var d=0;d{"use strict";var e=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];f.exports=function(f,n){for(var s=0;s{"use strict";var s=n(8938);f.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:f=>{"use strict";f.exports=function generate__limit(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A=e=="maximum",F=A?"exclusiveMaximum":"exclusiveMinimum",p=f.schema[F],I=f.opts.$data&&p&&p.$data,x=A?"<":">",z=A?">":"<",j=undefined;if(!(E||typeof r=="number"||r===undefined)){throw new Error(e+" must be number")}if(!(I||p===undefined||typeof p=="number"||typeof p=="boolean")){throw new Error(F+" must be number or boolean")}if(I){var U=f.util.getData(p.$data,v,f.dataPathArr),N="exclusive"+l,Q="exclType"+l,q="exclIsNumber"+l,O="op"+l,C="' + "+O+" + '";s+=" var schemaExcl"+l+" = "+U+"; ";U="schemaExcl"+l;s+=" var "+N+"; var "+Q+" = typeof "+U+"; if ("+Q+" != 'boolean' && "+Q+" != 'undefined' && "+Q+" != 'number') { ";var j=F;var L=L||[];L.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: '"+F+" should be boolean' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var J=s;s=L.pop();if(!f.compositeRule&&w){if(f.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(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+Q+" == 'number' ? ( ("+N+" = "+R+" === undefined || "+U+" "+x+"= "+R+") ? "+d+" "+z+"= "+U+" : "+d+" "+z+" "+R+" ) : ( ("+N+" = "+U+" === true) ? "+d+" "+z+"= "+R+" : "+d+" "+z+" "+R+" ) || "+d+" !== "+d+") { var op"+l+" = "+N+" ? '"+x+"' : '"+x+"='; ";if(r===undefined){j=F;g=f.errSchemaPath+"/"+F;R=U;E=I}}else{var q=typeof p=="number",C=x;if(q&&E){var O="'"+C+"'";s+=" if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" ( "+R+" === undefined || "+p+" "+x+"= "+R+" ? "+d+" "+z+"= "+p+" : "+d+" "+z+" "+R+" ) || "+d+" !== "+d+") { "}else{if(q&&r===undefined){N=true;j=F;g=f.errSchemaPath+"/"+F;R=p;z+="="}else{if(q)R=Math[A?"min":"max"](p,r);if(p===(q?R:true)){N=true;j=F;g=f.errSchemaPath+"/"+F;z+="="}else{N=false;C+="="}}var O="'"+C+"'";s+=" if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+d+" "+z+" "+R+" || "+d+" !== "+d+") { "}}j=j||e;var L=L||[];L.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limit")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { comparison: "+O+", limit: "+R+", exclusive: "+N+" } ";if(f.opts.messages!==false){s+=" , message: 'should be "+C+" ";if(E){s+="' + "+R}else{s+=""+R+"'"}}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var J=s;s=L.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},5675:f=>{"use strict";f.exports=function generate__limitItems(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxItems"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" "+d+".length "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitItems")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have ";if(e=="maxItems"){s+="more"}else{s+="fewer"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" items' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},6051:f=>{"use strict";f.exports=function generate__limitLength(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxLength"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}if(f.opts.unicode===false){s+=" "+d+".length "}else{s+=" ucs2length("+d+") "}s+=" "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitLength")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT be ";if(e=="maxLength"){s+="longer"}else{s+="shorter"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" characters' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},7043:f=>{"use strict";f.exports=function generate__limitProperties(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!(E||typeof r=="number")){throw new Error(e+" must be number")}var A=e=="maxProperties"?">":"<";s+="if ( ";if(E){s+=" ("+R+" !== undefined && typeof "+R+" != 'number') || "}s+=" Object.keys("+d+").length "+A+" "+R+") { ";var j=e;var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"_limitProperties")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+R+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have ";if(e=="maxProperties"){s+="more"}else{s+="fewer"}s+=" than ";if(E){s+="' + "+R+" + '"}else{s+=""+r}s+=" properties' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+="} ";if(w){s+=" else { "}return s}},3639:f=>{"use strict";f.exports=function generate_allOf(f,e,n){var s=" ";var l=f.schema[e];var v=f.schemaPath+f.util.getProperty(e);var r=f.errSchemaPath+"/"+e;var b=!f.opts.allErrors;var g=f.util.copy(f);var w="";g.level++;var j="valid"+g.level;var d=g.baseId,E=true;var R=l;if(R){var A,F=-1,p=R.length-1;while(F0||A===false:f.util.schemaHasRules(A,f.RULES.all)){E=false;g.schema=A;g.schemaPath=v+"["+F+"]";g.errSchemaPath=r+"/"+F;s+=" "+f.validate(g)+" ";g.baseId=d;if(b){s+=" if ("+j+") { ";w+="}"}}}}if(b){if(E){s+=" if (true) { "}else{s+=" "+w.slice(0,-1)+" "}}return s}},1256:f=>{"use strict";f.exports=function generate_anyOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p=r.every(function(e){return f.opts.strictKeywords?typeof e=="object"&&Object.keys(e).length>0||e===false:f.util.schemaHasRules(e,f.RULES.all)});if(p){var I=R.baseId;s+=" var "+E+" = errors; var "+d+" = false; ";var x=f.compositeRule;f.compositeRule=R.compositeRule=true;var z=r;if(z){var U,N=-1,Q=z.length-1;while(N{"use strict";f.exports=function generate_comment(f,e,n){var s=" ";var l=f.schema[e];var v=f.errSchemaPath+"/"+e;var r=!f.opts.allErrors;var b=f.util.toQuotedString(l);if(f.opts.$comment===true){s+=" console.log("+b+");"}else if(typeof f.opts.$comment=="function"){s+=" self._opts.$comment("+b+", "+f.util.toQuotedString(v)+", validate.root.schema);"}return s}},184:f=>{"use strict";f.exports=function generate_const(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if(!E){s+=" var schema"+l+" = validate.schema"+b+";"}s+="var "+d+" = equal("+j+", schema"+l+"); if (!"+d+") { ";var A=A||[];A.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { allowedValue: schema"+l+" } ";if(f.opts.messages!==false){s+=" , message: 'should be equal to constant' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var F=s;s=A.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},7419:f=>{"use strict";f.exports=function generate_contains(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p="i"+l,I=R.dataLevel=f.dataLevel+1,x="data"+I,z=f.baseId,U=f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all);s+="var "+E+" = errors;var "+d+";";if(U){var N=f.compositeRule;f.compositeRule=R.compositeRule=true;R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" var "+F+" = false; for (var "+p+" = 0; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var Q=j+"["+p+"]";R.dataPathArr[I]=p;var q=f.validate(R);R.baseId=z;if(f.util.varOccurences(q,x)<2){s+=" "+f.util.varReplace(q,x,Q)+" "}else{s+=" var "+x+" = "+Q+"; "+q+" "}s+=" if ("+F+") break; } ";f.compositeRule=R.compositeRule=N;s+=" "+A+" if (!"+F+") {"}else{s+=" if ("+j+".length == 0) {"}var O=O||[];O.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should contain a valid item' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var C=s;s=O.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+C+"]); "}else{s+=" validate.errors = ["+C+"]; return false; "}}else{s+=" var err = "+C+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { ";if(U){s+=" errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; } "}if(f.opts.allErrors){s+=" } "}return s}},7921:f=>{"use strict";f.exports=function generate_custom(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j;var d="data"+(v||"");var E="valid"+l;var R="errs__"+l;var A=f.opts.$data&&r&&r.$data,F;if(A){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";F="schema"+l}else{F=r}var p=this,I="definition"+l,x=p.definition,z="";var U,N,Q,q,O;if(A&&x.$data){O="keywordValidate"+l;var C=x.validateSchema;s+=" var "+I+" = RULES.custom['"+e+"'].definition; var "+O+" = "+I+".validate;"}else{q=f.useCustomRule(p,r,f.schema,f);if(!q)return;F="validate.schema"+b;O=q.code;U=x.compile;N=x.inline;Q=x.macro}var L=O+".errors",J="i"+l,T="ruleErr"+l,G=x.async;if(G&&!f.async)throw new Error("async keyword in sync schema");if(!(N||Q)){s+=""+L+" = null;"}s+="var "+R+" = errors;var "+E+";";if(A&&x.$data){z+="}";s+=" if ("+F+" === undefined) { "+E+" = true; } else { ";if(C){z+="}";s+=" "+E+" = "+I+".validateSchema("+F+"); if ("+E+") { "}}if(N){if(x.statements){s+=" "+q.validate+" "}else{s+=" "+E+" = "+q.validate+"; "}}else if(Q){var H=f.util.copy(f);var z="";H.level++;var X="valid"+H.level;H.schema=q.validate;H.schemaPath="";var M=f.compositeRule;f.compositeRule=H.compositeRule=true;var Y=f.validate(H).replace(/validate\.schema/g,O);f.compositeRule=H.compositeRule=M;s+=" "+Y}else{var W=W||[];W.push(s);s="";s+=" "+O+".call( ";if(f.opts.passContext){s+="this"}else{s+="self"}if(U||x.schema===false){s+=" , "+d+" "}else{s+=" , "+F+" , "+d+" , validate.schema"+f.schemaPath+" "}s+=" , (dataPath || '')";if(f.errorPath!='""'){s+=" + "+f.errorPath}var B=v?"data"+(v-1||""):"parentData",c=v?f.dataPathArr[v]:"parentDataProperty";s+=" , "+B+" , "+c+" , rootData ) ";var Z=s;s=W.pop();if(x.errors===false){s+=" "+E+" = ";if(G){s+="await "}s+=""+Z+"; "}else{if(G){L="customErrors"+l;s+=" var "+L+" = null; try { "+E+" = await "+Z+"; } catch (e) { "+E+" = false; if (e instanceof ValidationError) "+L+" = e.errors; else throw e; } "}else{s+=" "+L+" = null; "+E+" = "+Z+"; "}}}if(x.modifying){s+=" if ("+B+") "+d+" = "+B+"["+c+"];"}s+=""+z;if(x.valid){if(w){s+=" if (true) { "}}else{s+=" if ( ";if(x.valid===undefined){s+=" !";if(Q){s+=""+X}else{s+=""+E}}else{s+=" "+!x.valid+" "}s+=") { ";j=p.keyword;var W=W||[];W.push(s);s="";var W=W||[];W.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(j||"custom")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { keyword: '"+p.keyword+"' } ";if(f.opts.messages!==false){s+=" , message: 'should pass \""+p.keyword+"\" keyword validation' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+d+" "}s+=" } "}else{s+=" {} "}var D=s;s=W.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+D+"]); "}else{s+=" validate.errors = ["+D+"]; return false; "}}else{s+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var K=s;s=W.pop();if(N){if(x.errors){if(x.errors!="full"){s+=" for (var "+J+"="+R+"; "+J+"{"use strict";f.exports=function generate_dependencies(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;var F={},p={},I=f.opts.ownProperties;for(N in r){if(N=="__proto__")continue;var x=r[N];var z=Array.isArray(x)?p:F;z[N]=x}s+="var "+d+" = errors;";var U=f.errorPath;s+="var missing"+l+";";for(var N in p){z=p[N];if(z.length){s+=" if ( "+j+f.util.getProperty(N)+" !== undefined ";if(I){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(N)+"') "}if(w){s+=" && ( ";var Q=z;if(Q){var q,O=-1,C=Q.length-1;while(O0||x===false:f.util.schemaHasRules(x,f.RULES.all)){s+=" "+A+" = true; if ( "+j+f.util.getProperty(N)+" !== undefined ";if(I){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(N)+"') "}s+=") { ";E.schema=x;E.schemaPath=b+f.util.getProperty(N);E.errSchemaPath=g+"/"+f.util.escapeFragment(N);s+=" "+f.validate(E)+" ";E.baseId=B;s+=" } ";if(w){s+=" if ("+A+") { ";R+="}"}}}if(w){s+=" "+R+" if ("+d+" == errors) {"}return s}},9795:f=>{"use strict";f.exports=function generate_enum(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A="i"+l,F="schema"+l;if(!E){s+=" var "+F+" = validate.schema"+b+";"}s+="var "+d+";";if(E){s+=" if (schema"+l+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+l+")) "+d+" = false; else {"}s+=""+d+" = false;for (var "+A+"=0; "+A+"<"+F+".length; "+A+"++) if (equal("+j+", "+F+"["+A+"])) { "+d+" = true; break; }";if(E){s+=" } "}s+=" if (!"+d+") { ";var p=p||[];p.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { allowedValues: schema"+l+" } ";if(f.opts.messages!==false){s+=" , message: 'should be equal to one of the allowed values' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var I=s;s=p.pop();if(!f.compositeRule&&w){if(f.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+=" }";if(w){s+=" else { "}return s}},5801:f=>{"use strict";f.exports=function generate_format(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");if(f.opts.format===false){if(w){s+=" if (true) { "}return s}var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}var R=f.opts.unknownFormats,A=Array.isArray(R);if(d){var F="format"+l,p="isObject"+l,I="formatType"+l;s+=" var "+F+" = formats["+E+"]; var "+p+" = typeof "+F+" == 'object' && !("+F+" instanceof RegExp) && "+F+".validate; var "+I+" = "+p+" && "+F+".type || 'string'; if ("+p+") { ";if(f.async){s+=" var async"+l+" = "+F+".async; "}s+=" "+F+" = "+F+".validate; } if ( ";if(d){s+=" ("+E+" !== undefined && typeof "+E+" != 'string') || "}s+=" (";if(R!="ignore"){s+=" ("+E+" && !"+F+" ";if(A){s+=" && self._opts.unknownFormats.indexOf("+E+") == -1 "}s+=") || "}s+=" ("+F+" && "+I+" == '"+n+"' && !(typeof "+F+" == 'function' ? ";if(f.async){s+=" (async"+l+" ? await "+F+"("+j+") : "+F+"("+j+")) "}else{s+=" "+F+"("+j+") "}s+=" : "+F+".test("+j+"))))) {"}else{var F=f.formats[r];if(!F){if(R=="ignore"){f.logger.warn('unknown format "'+r+'" ignored in schema at path "'+f.errSchemaPath+'"');if(w){s+=" if (true) { "}return s}else if(A&&R.indexOf(r)>=0){if(w){s+=" if (true) { "}return s}else{throw new Error('unknown format "'+r+'" is used in schema at path "'+f.errSchemaPath+'"')}}var p=typeof F=="object"&&!(F instanceof RegExp)&&F.validate;var I=p&&F.type||"string";if(p){var x=F.async===true;F=F.validate}if(I!=n){if(w){s+=" if (true) { "}return s}if(x){if(!f.async)throw new Error("async format in sync schema");var z="formats"+f.util.getProperty(r)+".validate";s+=" if (!(await "+z+"("+j+"))) { "}else{s+=" if (! ";var z="formats"+f.util.getProperty(r);if(p)z+=".validate";if(typeof F=="function"){s+=" "+z+"("+j+") "}else{s+=" "+z+".test("+j+") "}s+=") { "}}var U=U||[];U.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { format: ";if(d){s+=""+E}else{s+=""+f.util.toQuotedString(r)}s+=" } ";if(f.opts.messages!==false){s+=" , message: 'should match format \"";if(d){s+="' + "+E+" + '"}else{s+=""+f.util.escapeQuotes(r)}s+="\"' "}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+f.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var N=s;s=U.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},4962:f=>{"use strict";f.exports=function generate_if(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);R.level++;var A="valid"+R.level;var F=f.schema["then"],p=f.schema["else"],I=F!==undefined&&(f.opts.strictKeywords?typeof F=="object"&&Object.keys(F).length>0||F===false:f.util.schemaHasRules(F,f.RULES.all)),x=p!==undefined&&(f.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===false:f.util.schemaHasRules(p,f.RULES.all)),z=R.baseId;if(I||x){var U;R.createErrors=false;R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" var "+E+" = errors; var "+d+" = true; ";var N=f.compositeRule;f.compositeRule=R.compositeRule=true;s+=" "+f.validate(R)+" ";R.baseId=z;R.createErrors=true;s+=" errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; } ";f.compositeRule=R.compositeRule=N;if(I){s+=" if ("+A+") { ";R.schema=f.schema["then"];R.schemaPath=f.schemaPath+".then";R.errSchemaPath=f.errSchemaPath+"/then";s+=" "+f.validate(R)+" ";R.baseId=z;s+=" "+d+" = "+A+"; ";if(I&&x){U="ifClause"+l;s+=" var "+U+" = 'then'; "}else{U="'then'"}s+=" } ";if(x){s+=" else { "}}else{s+=" if (!"+A+") { "}if(x){R.schema=f.schema["else"];R.schemaPath=f.schemaPath+".else";R.errSchemaPath=f.errSchemaPath+"/else";s+=" "+f.validate(R)+" ";R.baseId=z;s+=" "+d+" = "+A+"; ";if(I&&x){U="ifClause"+l;s+=" var "+U+" = 'else'; "}else{U="'else'"}s+=" } "}s+=" if (!"+d+") { var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { failingKeyword: "+U+" } ";if(f.opts.messages!==false){s+=" , message: 'should match \"' + "+U+" + '\" schema' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+=" } ";if(w){s+=" else { "}}else{if(w){s+=" if (true) { "}}return s}},4124:(f,e,n)=>{"use strict";f.exports={$ref:n(5746),allOf:n(3639),anyOf:n(1256),$comment:n(2660),const:n(184),contains:n(7419),dependencies:n(7299),enum:n(9795),format:n(5801),if:n(4962),items:n(9623),maximum:n(3711),minimum:n(3711),maxItems:n(5675),minItems:n(5675),maxLength:n(6051),minLength:n(6051),maxProperties:n(7043),minProperties:n(7043),multipleOf:n(9251),not:n(7739),oneOf:n(6857),pattern:n(8099),properties:n(9438),propertyNames:n(3466),required:n(8430),uniqueItems:n(2207),validate:n(6131)}},9623:f=>{"use strict";f.exports=function generate_items(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p="i"+l,I=R.dataLevel=f.dataLevel+1,x="data"+I,z=f.baseId;s+="var "+E+" = errors;var "+d+";";if(Array.isArray(r)){var U=f.schema.additionalItems;if(U===false){s+=" "+d+" = "+j+".length <= "+r.length+"; ";var N=g;g=f.errSchemaPath+"/additionalItems";s+=" if (!"+d+") { ";var Q=Q||[];Q.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { limit: "+r.length+" } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have more than "+r.length+" items' "}if(f.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var q=s;s=Q.pop();if(!f.compositeRule&&w){if(f.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+=" } ";g=N;if(w){A+="}";s+=" else { "}}var O=r;if(O){var C,L=-1,J=O.length-1;while(L0||C===false:f.util.schemaHasRules(C,f.RULES.all)){s+=" "+F+" = true; if ("+j+".length > "+L+") { ";var T=j+"["+L+"]";R.schema=C;R.schemaPath=b+"["+L+"]";R.errSchemaPath=g+"/"+L;R.errorPath=f.util.getPathExpr(f.errorPath,L,f.opts.jsonPointers,true);R.dataPathArr[I]=L;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}s+=" } ";if(w){s+=" if ("+F+") { ";A+="}"}}}}if(typeof U=="object"&&(f.opts.strictKeywords?typeof U=="object"&&Object.keys(U).length>0||U===false:f.util.schemaHasRules(U,f.RULES.all))){R.schema=U;R.schemaPath=f.schemaPath+".additionalItems";R.errSchemaPath=f.errSchemaPath+"/additionalItems";s+=" "+F+" = true; if ("+j+".length > "+r.length+") { for (var "+p+" = "+r.length+"; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var T=j+"["+p+"]";R.dataPathArr[I]=p;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}if(w){s+=" if (!"+F+") break; "}s+=" } } ";if(w){s+=" if ("+F+") { ";A+="}"}}}else if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){R.schema=r;R.schemaPath=b;R.errSchemaPath=g;s+=" for (var "+p+" = "+0+"; "+p+" < "+j+".length; "+p+"++) { ";R.errorPath=f.util.getPathExpr(f.errorPath,p,f.opts.jsonPointers,true);var T=j+"["+p+"]";R.dataPathArr[I]=p;var G=f.validate(R);R.baseId=z;if(f.util.varOccurences(G,x)<2){s+=" "+f.util.varReplace(G,x,T)+" "}else{s+=" var "+x+" = "+T+"; "+G+" "}if(w){s+=" if (!"+F+") break; "}s+=" }"}if(w){s+=" "+A+" if ("+E+" == errors) {"}return s}},9251:f=>{"use strict";f.exports=function generate_multipleOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}if(!(d||typeof r=="number")){throw new Error(e+" must be number")}s+="var division"+l+";if (";if(d){s+=" "+E+" !== undefined && ( typeof "+E+" != 'number' || "}s+=" (division"+l+" = "+j+" / "+E+", ";if(f.opts.multipleOfPrecision){s+=" Math.abs(Math.round(division"+l+") - division"+l+") > 1e-"+f.opts.multipleOfPrecision+" "}else{s+=" division"+l+" !== parseInt(division"+l+") "}s+=" ) ";if(d){s+=" ) "}s+=" ) { ";var R=R||[];R.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { multipleOf: "+E+" } ";if(f.opts.messages!==false){s+=" , message: 'should be multiple of ";if(d){s+="' + "+E}else{s+=""+E+"'"}}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var A=s;s=R.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},7739:f=>{"use strict";f.exports=function generate_not(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);E.level++;var R="valid"+E.level;if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){E.schema=r;E.schemaPath=b;E.errSchemaPath=g;s+=" var "+d+" = errors; ";var A=f.compositeRule;f.compositeRule=E.compositeRule=true;E.createErrors=false;var F;if(E.opts.allErrors){F=E.opts.allErrors;E.opts.allErrors=false}s+=" "+f.validate(E)+" ";E.createErrors=true;if(F)E.opts.allErrors=F;f.compositeRule=E.compositeRule=A;s+=" if ("+R+") { ";var p=p||[];p.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var I=s;s=p.pop();if(!f.compositeRule&&w){if(f.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 { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ";if(f.opts.allErrors){s+=" } "}}else{s+=" var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'should NOT be valid' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(w){s+=" if (false) { "}}return s}},6857:f=>{"use strict";f.exports=function generate_oneOf(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E="errs__"+l;var R=f.util.copy(f);var A="";R.level++;var F="valid"+R.level;var p=R.baseId,I="prevValid"+l,x="passingSchemas"+l;s+="var "+E+" = errors , "+I+" = false , "+d+" = false , "+x+" = null; ";var z=f.compositeRule;f.compositeRule=R.compositeRule=true;var U=r;if(U){var N,Q=-1,q=U.length-1;while(Q0||N===false:f.util.schemaHasRules(N,f.RULES.all)){R.schema=N;R.schemaPath=b+"["+Q+"]";R.errSchemaPath=g+"/"+Q;s+=" "+f.validate(R)+" ";R.baseId=p}else{s+=" var "+F+" = true; "}if(Q){s+=" if ("+F+" && "+I+") { "+d+" = false; "+x+" = ["+x+", "+Q+"]; } else { ";A+="}"}s+=" if ("+F+") { "+d+" = "+I+" = true; "+x+" = "+Q+"; }"}}f.compositeRule=R.compositeRule=z;s+=""+A+"if (!"+d+") { var err = ";if(f.createErrors!==false){s+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { passingSchemas: "+x+" } ";if(f.opts.messages!==false){s+=" , message: 'should match exactly one schema in oneOf' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(vErrors); "}else{s+=" validate.errors = vErrors; return false; "}}s+="} else { errors = "+E+"; if (vErrors !== null) { if ("+E+") vErrors.length = "+E+"; else vErrors = null; }";if(f.opts.allErrors){s+=" } "}return s}},8099:f=>{"use strict";f.exports=function generate_pattern(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d=f.opts.$data&&r&&r.$data,E;if(d){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";E="schema"+l}else{E=r}var R=d?"(new RegExp("+E+"))":f.usePattern(r);s+="if ( ";if(d){s+=" ("+E+" !== undefined && typeof "+E+" != 'string') || "}s+=" !"+R+".test("+j+") ) { ";var A=A||[];A.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { pattern: ";if(d){s+=""+E}else{s+=""+f.util.toQuotedString(r)}s+=" } ";if(f.opts.messages!==false){s+=" , message: 'should match pattern \"";if(d){s+="' + "+E+" + '"}else{s+=""+f.util.escapeQuotes(r)}s+="\"' "}if(f.opts.verbose){s+=" , schema: ";if(d){s+="validate.schema"+b}else{s+=""+f.util.toQuotedString(r)}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var F=s;s=A.pop();if(!f.compositeRule&&w){if(f.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(w){s+=" else { "}return s}},9438:f=>{"use strict";f.exports=function generate_properties(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;var F="key"+l,p="idx"+l,I=E.dataLevel=f.dataLevel+1,x="data"+I,z="dataProperties"+l;var U=Object.keys(r||{}).filter(notProto),N=f.schema.patternProperties||{},Q=Object.keys(N).filter(notProto),q=f.schema.additionalProperties,O=U.length||Q.length,C=q===false,L=typeof q=="object"&&Object.keys(q).length,J=f.opts.removeAdditional,T=C||L||J,G=f.opts.ownProperties,H=f.baseId;var X=f.schema.required;if(X&&!(f.opts.$data&&X.$data)&&X.length8){s+=" || validate.schema"+b+".hasOwnProperty("+F+") "}else{var Y=U;if(Y){var W,B=-1,c=Y.length-1;while(B0||t===false:f.util.schemaHasRules(t,f.RULES.all)){var ff=f.util.getProperty(W),P=j+ff,ef=_&&t.default!==undefined;E.schema=t;E.schemaPath=b+ff;E.errSchemaPath=g+"/"+f.util.escapeFragment(W);E.errorPath=f.util.getPath(f.errorPath,W,f.opts.jsonPointers);E.dataPathArr[I]=f.util.toQuotedString(W);var i=f.validate(E);E.baseId=H;if(f.util.varOccurences(i,x)<2){i=f.util.varReplace(i,x,P);var nf=P}else{var nf=x;s+=" var "+x+" = "+P+"; "}if(ef){s+=" "+i+" "}else{if(M&&M[W]){s+=" if ( "+nf+" === undefined ";if(G){s+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=") { "+A+" = false; ";var y=f.errorPath,h=g,sf=f.util.escapeQuotes(W);if(f.opts._errorDataPathProperty){f.errorPath=f.util.getPath(y,W,f.opts.jsonPointers)}g=f.errSchemaPath+"/required";var a=a||[];a.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { missingProperty: '"+sf+"' } ";if(f.opts.messages!==false){s+=" , message: '";if(f.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+sf+"\\'"}s+="' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var S=s;s=a.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+S+"]); "}else{s+=" validate.errors = ["+S+"]; return false; "}}else{s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}g=h;f.errorPath=y;s+=" } else { "}else{if(w){s+=" if ( "+nf+" === undefined ";if(G){s+=" || ! Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=") { "+A+" = true; } else { "}else{s+=" if ("+nf+" !== undefined ";if(G){s+=" && Object.prototype.hasOwnProperty.call("+j+", '"+f.util.escapeQuotes(W)+"') "}s+=" ) { "}}s+=" "+i+" } "}}if(w){s+=" if ("+A+") { ";R+="}"}}}}if(Q.length){var lf=Q;if(lf){var D,vf=-1,rf=lf.length-1;while(vf0||t===false:f.util.schemaHasRules(t,f.RULES.all)){E.schema=t;E.schemaPath=f.schemaPath+".patternProperties"+f.util.getProperty(D);E.errSchemaPath=f.errSchemaPath+"/patternProperties/"+f.util.escapeFragment(D);if(G){s+=" "+z+" = "+z+" || Object.keys("+j+"); for (var "+p+"=0; "+p+"<"+z+".length; "+p+"++) { var "+F+" = "+z+"["+p+"]; "}else{s+=" for (var "+F+" in "+j+") { "}s+=" if ("+f.usePattern(D)+".test("+F+")) { ";E.errorPath=f.util.getPathExpr(f.errorPath,F,f.opts.jsonPointers);var P=j+"["+F+"]";E.dataPathArr[I]=F;var i=f.validate(E);E.baseId=H;if(f.util.varOccurences(i,x)<2){s+=" "+f.util.varReplace(i,x,P)+" "}else{s+=" var "+x+" = "+P+"; "+i+" "}if(w){s+=" if (!"+A+") break; "}s+=" } ";if(w){s+=" else "+A+" = true; "}s+=" } ";if(w){s+=" if ("+A+") { ";R+="}"}}}}}if(w){s+=" "+R+" if ("+d+" == errors) {"}return s}},3466:f=>{"use strict";f.exports=function generate_propertyNames(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="errs__"+l;var E=f.util.copy(f);var R="";E.level++;var A="valid"+E.level;s+="var "+d+" = errors;";if(f.opts.strictKeywords?typeof r=="object"&&Object.keys(r).length>0||r===false:f.util.schemaHasRules(r,f.RULES.all)){E.schema=r;E.schemaPath=b;E.errSchemaPath=g;var F="key"+l,p="idx"+l,I="i"+l,x="' + "+F+" + '",z=E.dataLevel=f.dataLevel+1,U="data"+z,N="dataProperties"+l,Q=f.opts.ownProperties,q=f.baseId;if(Q){s+=" var "+N+" = undefined; "}if(Q){s+=" "+N+" = "+N+" || Object.keys("+j+"); for (var "+p+"=0; "+p+"<"+N+".length; "+p+"++) { var "+F+" = "+N+"["+p+"]; "}else{s+=" for (var "+F+" in "+j+") { "}s+=" var startErrs"+l+" = errors; ";var O=F;var C=f.compositeRule;f.compositeRule=E.compositeRule=true;var L=f.validate(E);E.baseId=q;if(f.util.varOccurences(L,U)<2){s+=" "+f.util.varReplace(L,U,O)+" "}else{s+=" var "+U+" = "+O+"; "+L+" "}f.compositeRule=E.compositeRule=C;s+=" if (!"+A+") { for (var "+I+"=startErrs"+l+"; "+I+"{"use strict";f.exports=function generate_ref(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.errSchemaPath+"/"+e;var g=!f.opts.allErrors;var w="data"+(v||"");var j="valid"+l;var d,E;if(r=="#"||r=="#/"){if(f.isRoot){d=f.async;E="validate"}else{d=f.root.schema.$async===true;E="root.refVal[0]"}}else{var R=f.resolveRef(f.baseId,r,f.isRoot);if(R===undefined){var A=f.MissingRefError.message(f.baseId,r);if(f.opts.missingRefs=="fail"){f.logger.error(A);var F=F||[];F.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"$ref"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(b)+" , params: { ref: '"+f.util.escapeQuotes(r)+"' } ";if(f.opts.messages!==false){s+=" , message: 'can\\'t resolve reference "+f.util.escapeQuotes(r)+"' "}if(f.opts.verbose){s+=" , schema: "+f.util.toQuotedString(r)+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+w+" "}s+=" } "}else{s+=" {} "}var p=s;s=F.pop();if(!f.compositeRule&&g){if(f.async){s+=" throw new ValidationError(["+p+"]); "}else{s+=" validate.errors = ["+p+"]; return false; "}}else{s+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}if(g){s+=" if (false) { "}}else if(f.opts.missingRefs=="ignore"){f.logger.warn(A);if(g){s+=" if (true) { "}}else{throw new f.MissingRefError(f.baseId,r,A)}}else if(R.inline){var I=f.util.copy(f);I.level++;var x="valid"+I.level;I.schema=R.schema;I.schemaPath="";I.errSchemaPath=r;var z=f.validate(I).replace(/validate\.schema/g,R.code);s+=" "+z+" ";if(g){s+=" if ("+x+") { "}}else{d=R.$async===true||f.async&&R.$async!==false;E=R.code}}if(E){var F=F||[];F.push(s);s="";if(f.opts.passContext){s+=" "+E+".call(this, "}else{s+=" "+E+"( "}s+=" "+w+", (dataPath || '')";if(f.errorPath!='""'){s+=" + "+f.errorPath}var U=v?"data"+(v-1||""):"parentData",N=v?f.dataPathArr[v]:"parentDataProperty";s+=" , "+U+" , "+N+", rootData) ";var Q=s;s=F.pop();if(d){if(!f.async)throw new Error("async schema referenced by sync schema");if(g){s+=" var "+j+"; "}s+=" try { await "+Q+"; ";if(g){s+=" "+j+" = 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(g){s+=" "+j+" = false; "}s+=" } ";if(g){s+=" if ("+j+") { "}}else{s+=" if (!"+Q+") { if (vErrors === null) vErrors = "+E+".errors; else vErrors = vErrors.concat("+E+".errors); errors = vErrors.length; } ";if(g){s+=" else { "}}}return s}},8430:f=>{"use strict";f.exports=function generate_required(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}var A="schema"+l;if(!E){if(r.length0||U===false:f.util.schemaHasRules(U,f.RULES.all)))){F[F.length]=I}}}}else{var F=r}}if(E||F.length){var N=f.errorPath,Q=E||F.length>=f.opts.loopRequired,q=f.opts.ownProperties;if(w){s+=" var missing"+l+"; ";if(Q){if(!E){s+=" var "+A+" = validate.schema"+b+"; "}var O="i"+l,C="schema"+l+"["+O+"]",L="' + "+C+" + '";if(f.opts._errorDataPathProperty){f.errorPath=f.util.getPathExpr(N,C,f.opts.jsonPointers)}s+=" var "+d+" = true; ";if(E){s+=" if (schema"+l+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+l+")) "+d+" = false; else {"}s+=" for (var "+O+" = 0; "+O+" < "+A+".length; "+O+"++) { "+d+" = "+j+"["+A+"["+O+"]] !== undefined ";if(q){s+=" && Object.prototype.hasOwnProperty.call("+j+", "+A+"["+O+"]) "}s+="; if (!"+d+") break; } ";if(E){s+=" } "}s+=" if (!"+d+") { ";var J=J||[];J.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { missingProperty: '"+L+"' } ";if(f.opts.messages!==false){s+=" , message: '";if(f.opts._errorDataPathProperty){s+="is a required property"}else{s+="should have required property \\'"+L+"\\'"}s+="' "}if(f.opts.verbose){s+=" , schema: validate.schema"+b+" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var T=s;s=J.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+T+"]); "}else{s+=" validate.errors = ["+T+"]; return false; "}}else{s+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } else { "}else{s+=" if ( ";var G=F;if(G){var H,O=-1,X=G.length-1;while(O{"use strict";f.exports=function generate_uniqueItems(f,e,n){var s=" ";var l=f.level;var v=f.dataLevel;var r=f.schema[e];var b=f.schemaPath+f.util.getProperty(e);var g=f.errSchemaPath+"/"+e;var w=!f.opts.allErrors;var j="data"+(v||"");var d="valid"+l;var E=f.opts.$data&&r&&r.$data,R;if(E){s+=" var schema"+l+" = "+f.util.getData(r.$data,v,f.dataPathArr)+"; ";R="schema"+l}else{R=r}if((r||E)&&f.opts.uniqueItems!==false){if(E){s+=" var "+d+"; if ("+R+" === false || "+R+" === undefined) "+d+" = true; else if (typeof "+R+" != 'boolean') "+d+" = false; else { "}s+=" var i = "+j+".length , "+d+" = true , j; if (i > 1) { ";var A=f.schema.items&&f.schema.items.type,F=Array.isArray(A);if(!A||A=="object"||A=="array"||F&&(A.indexOf("object")>=0||A.indexOf("array")>=0)){s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+j+"[i], "+j+"[j])) { "+d+" = false; break outer; } } } "}else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+j+"[i]; ";var p="checkDataType"+(F?"s":"");s+=" if ("+f.util[p](A,"item",f.opts.strictNumbers,true)+") continue; ";if(F){s+=" if (typeof item == 'string') item = '\"' + item; "}s+=" if (typeof itemIndices[item] == 'number') { "+d+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ";if(E){s+=" } "}s+=" if (!"+d+") { ";var I=I||[];I.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+"uniqueItems"+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(g)+" , params: { i: i, j: j } ";if(f.opts.messages!==false){s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "}if(f.opts.verbose){s+=" , schema: ";if(E){s+="validate.schema"+b}else{s+=""+r}s+=" , parentSchema: validate.schema"+f.schemaPath+" , data: "+j+" "}s+=" } "}else{s+=" {} "}var x=s;s=I.pop();if(!f.compositeRule&&w){if(f.async){s+=" throw new ValidationError(["+x+"]); "}else{s+=" validate.errors = ["+x+"]; return false; "}}else{s+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}s+=" } ";if(w){s+=" else { "}}else{if(w){s+=" if (true) { "}}return s}},6131:f=>{"use strict";f.exports=function generate_validate(f,e,n){var s="";var l=f.schema.$async===true,v=f.util.schemaHasRulesExcept(f.schema,f.RULES.all,"$ref"),r=f.self._getId(f.schema);if(f.opts.strictKeywords){var b=f.util.schemaUnknownRules(f.schema,f.RULES.keywords);if(b){var g="unknown keyword: "+b;if(f.opts.strictKeywords==="log")f.logger.warn(g);else throw new Error(g)}}if(f.isTop){s+=" var validate = ";if(l){f.async=true;s+="async "}s+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";if(r&&(f.opts.sourceCode||f.opts.processCode)){s+=" "+("/*# sourceURL="+r+" */")+" "}}if(typeof f.schema=="boolean"||!(v||f.schema.$ref)){var e="false schema";var w=f.level;var j=f.dataLevel;var d=f.schema[e];var E=f.schemaPath+f.util.getProperty(e);var R=f.errSchemaPath+"/"+e;var A=!f.opts.allErrors;var F;var p="data"+(j||"");var I="valid"+w;if(f.schema===false){if(f.isTop){A=true}else{s+=" var "+I+" = false; "}var x=x||[];x.push(s);s="";if(f.createErrors!==false){s+=" { keyword: '"+(F||"false schema")+"' , dataPath: (dataPath || '') + "+f.errorPath+" , schemaPath: "+f.util.toQuotedString(R)+" , params: {} ";if(f.opts.messages!==false){s+=" , message: 'boolean schema is false' "}if(f.opts.verbose){s+=" , schema: false , parentSchema: validate.schema"+f.schemaPath+" , data: "+p+" "}s+=" } "}else{s+=" {} "}var z=s;s=x.pop();if(!f.compositeRule&&A){if(f.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(f.isTop){if(l){s+=" return data; "}else{s+=" validate.errors = null; return true; "}}else{s+=" var "+I+" = true; "}}if(f.isTop){s+=" }; return validate; "}return s}if(f.isTop){var U=f.isTop,w=f.level=0,j=f.dataLevel=0,p="data";f.rootId=f.resolve.fullPath(f.self._getId(f.root.schema));f.baseId=f.baseId||f.rootId;delete f.isTop;f.dataPathArr=[""];if(f.schema.default!==undefined&&f.opts.useDefaults&&f.opts.strictDefaults){var N="default is ignored in the schema root";if(f.opts.strictDefaults==="log")f.logger.warn(N);else throw new Error(N)}s+=" var vErrors = null; ";s+=" var errors = 0; ";s+=" if (rootData === undefined) rootData = data; "}else{var w=f.level,j=f.dataLevel,p="data"+(j||"");if(r)f.baseId=f.resolve.url(f.baseId,r);if(l&&!f.async)throw new Error("async schema in sync schema");s+=" var errs_"+w+" = errors;"}var I="valid"+w,A=!f.opts.allErrors,Q="",q="";var F;var O=f.schema.type,C=Array.isArray(O);if(O&&f.opts.nullable&&f.schema.nullable===true){if(C){if(O.indexOf("null")==-1)O=O.concat("null")}else if(O!="null"){O=[O,"null"];C=true}}if(C&&O.length==1){O=O[0];C=false}if(f.schema.$ref&&v){if(f.opts.extendRefs=="fail"){throw new Error('$ref: validation keywords used in schema at path "'+f.errSchemaPath+'" (see option extendRefs)')}else if(f.opts.extendRefs!==true){v=false;f.logger.warn('$ref: keywords ignored in schema at path "'+f.errSchemaPath+'"')}}if(f.schema.$comment&&f.opts.$comment){s+=" "+f.RULES.all.$comment.code(f,"$comment")}if(O){if(f.opts.coerceTypes){var L=f.util.coerceToTypes(f.opts.coerceTypes,O)}var J=f.RULES.types[O];if(L||C||J===true||J&&!$shouldUseGroup(J)){var E=f.schemaPath+".type",R=f.errSchemaPath+"/type";var E=f.schemaPath+".type",R=f.errSchemaPath+"/type",T=C?"checkDataTypes":"checkDataType";s+=" if ("+f.util[T](O,p,f.opts.strictNumbers,true)+") { ";if(L){var G="dataType"+w,H="coerced"+w;s+=" var "+G+" = typeof "+p+"; var "+H+" = undefined; ";if(f.opts.coerceTypes=="array"){s+=" if ("+G+" == 'object' && Array.isArray("+p+") && "+p+".length == 1) { "+p+" = "+p+"[0]; "+G+" = typeof "+p+"; if ("+f.util.checkDataType(f.schema.type,p,f.opts.strictNumbers)+") "+H+" = "+p+"; } "}s+=" if ("+H+" !== undefined) ; ";var X=L;if(X){var M,Y=-1,W=X.length-1;while(Y{"use strict";var s=/^[a-z_$][a-z0-9_$-]*$/i;var l=n(7921);var v=n(5533);f.exports={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(f,e){var n=this.RULES;if(n.keywords[f])throw new Error("Keyword "+f+" is already defined");if(!s.test(f))throw new Error("Keyword "+f+" is not a valid identifier");if(e){this.validateKeyword(e,true);var v=e.type;if(Array.isArray(v)){for(var r=0;r{"use strict";f=n.nmd(f);const s=n(5747);const l=n(5622);const v=n(6417);const r=n(2357);const b=n(8614);const g=n(5514);const w=n(293);const j=n(6536);const d=n(7727);const E=n(175);const R=n(1414);const A=()=>Object.create(null);const F="aes-256-cbc";delete require.cache[__filename];const p=l.dirname(f.parent&&f.parent.filename||".");const I=(f,e)=>{const n=["undefined","symbol","function"];const s=typeof e;if(n.includes(s)){throw new TypeError(`Setting a value of type \`${s}\` for key \`${f}\` is not allowed as it's not supported by JSON`)}};class Conf{constructor(f){f={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:true,serialize:f=>JSON.stringify(f,null,"\t"),deserialize:JSON.parse,accessPropertiesByDotNotation:true,...f};if(!f.cwd){if(!f.projectName){const e=j.sync(p);f.projectName=e&&JSON.parse(s.readFileSync(e,"utf8")).name}if(!f.projectName){throw new Error("Project name could not be inferred. Please specify the `projectName` option.")}f.cwd=d(f.projectName,{suffix:f.projectSuffix}).config}this._options=f;if(f.schema){if(typeof f.schema!=="object"){throw new TypeError("The `schema` option must be an object.")}const e=new R({allErrors:true,format:"full",useDefaults:true,errorDataPath:"property"});const n={type:"object",properties:f.schema};this._validator=e.compile(n)}this.events=new b;this.encryptionKey=f.encryptionKey;this.serialize=f.serialize;this.deserialize=f.deserialize;const e=f.fileExtension?`.${f.fileExtension}`:"";this.path=l.resolve(f.cwd,`${f.configName}${e}`);const n=this.store;const v=Object.assign(A(),f.defaults,n);this._validate(v);try{r.deepEqual(n,v)}catch(f){this.store=v}}_validate(f){if(!this._validator){return}const e=this._validator(f);if(!e){const f=this._validator.errors.reduce((f,{dataPath:e,message:n})=>f+` \`${e.slice(1)}\` ${n};`,"");throw new Error("Config schema violation:"+f.slice(0,-1))}}get(f,e){if(this._options.accessPropertiesByDotNotation){return g.get(this.store,f,e)}return f in this.store?this.store[f]:e}set(f,e){if(typeof f!=="string"&&typeof f!=="object"){throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof f}`)}if(typeof f!=="object"&&e===undefined){throw new TypeError("Use `delete()` to clear values")}const{store:n}=this;const s=(f,e)=>{I(f,e);if(this._options.accessPropertiesByDotNotation){g.set(n,f,e)}else{n[f]=e}};if(typeof f==="object"){const e=f;for(const[f,n]of Object.entries(e)){s(f,n)}}else{s(f,e)}this.store=n}has(f){if(this._options.accessPropertiesByDotNotation){return g.has(this.store,f)}return f in this.store}delete(f){const{store:e}=this;if(this._options.accessPropertiesByDotNotation){g.delete(e,f)}else{delete e[f]}this.store=e}clear(){this.store=A()}onDidChange(f,e){if(typeof f!=="string"){throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof f}`)}if(typeof e!=="function"){throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`)}const n=()=>this.get(f);return this.handleChange(n,e)}onDidAnyChange(f){if(typeof f!=="function"){throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof f}`)}const e=()=>this.store;return this.handleChange(e,f)}handleChange(f,e){let n=f();const s=()=>{const s=n;const l=f();try{r.deepEqual(l,s)}catch(f){n=l;e.call(this,l,s)}};this.events.on("change",s);return()=>this.events.removeListener("change",s)}get size(){return Object.keys(this.store).length}get store(){try{let f=s.readFileSync(this.path,this.encryptionKey?null:"utf8");if(this.encryptionKey){try{if(f.slice(16,17).toString()===":"){const e=f.slice(0,16);const n=v.pbkdf2Sync(this.encryptionKey,e.toString(),1e4,32,"sha512");const s=v.createDecipheriv(F,n,e);f=Buffer.concat([s.update(f.slice(17)),s.final()])}else{const e=v.createDecipher(F,this.encryptionKey);f=Buffer.concat([e.update(f),e.final()])}}catch(f){}}f=this.deserialize(f);this._validate(f);return Object.assign(A(),f)}catch(f){if(f.code==="ENOENT"){w.sync(l.dirname(this.path));return A()}if(this._options.clearInvalidConfig&&f.name==="SyntaxError"){return A()}throw f}}set store(f){w.sync(l.dirname(this.path));this._validate(f);let e=this.serialize(f);if(this.encryptionKey){const f=v.randomBytes(16);const n=v.pbkdf2Sync(this.encryptionKey,f.toString(),1e4,32,"sha512");const s=v.createCipheriv(F,n,f);e=Buffer.concat([f,Buffer.from(":"),s.update(Buffer.from(e)),s.final()])}E.sync(this.path,e);this.events.emit("change")}*[Symbol.iterator](){for(const[f,e]of Object.entries(this.store)){yield[f,e]}}}f.exports=Conf},5514:(f,e,n)=>{"use strict";const s=n(1771);const l=["__proto__","prototype","constructor"];const v=f=>!f.some(f=>l.includes(f));function getPathSegments(f){const e=f.split(".");const n=[];for(let f=0;f{"use strict";f.exports=(f=>{const e=typeof f;return f!==null&&(e==="object"||e==="function")})},7727:(f,e,n)=>{"use strict";const s=n(5622);const l=n(2087);const v=l.homedir();const r=l.tmpdir();const{env:b}=process;const g=f=>{const e=s.join(v,"Library");return{data:s.join(e,"Application Support",f),config:s.join(e,"Preferences",f),cache:s.join(e,"Caches",f),log:s.join(e,"Logs",f),temp:s.join(r,f)}};const w=f=>{const e=b.APPDATA||s.join(v,"AppData","Roaming");const n=b.LOCALAPPDATA||s.join(v,"AppData","Local");return{data:s.join(n,f,"Data"),config:s.join(e,f,"Config"),cache:s.join(n,f,"Cache"),log:s.join(n,f,"Log"),temp:s.join(r,f)}};const j=f=>{const e=s.basename(v);return{data:s.join(b.XDG_DATA_HOME||s.join(v,".local","share"),f),config:s.join(b.XDG_CONFIG_HOME||s.join(v,".config"),f),cache:s.join(b.XDG_CACHE_HOME||s.join(v,".cache"),f),log:s.join(b.XDG_STATE_HOME||s.join(v,".local","state"),f),temp:s.join(r,e,f)}};const d=(f,e)=>{if(typeof f!=="string"){throw new TypeError(`Expected string, got ${typeof f}`)}e=Object.assign({suffix:"nodejs"},e);if(e.suffix){f+=`-${e.suffix}`}if(process.platform==="darwin"){return g(f)}if(process.platform==="win32"){return w(f)}return j(f)};f.exports=d;f.exports.default=d},3933:f=>{"use strict";f.exports=function equal(f,e){if(f===e)return true;if(f&&e&&typeof f=="object"&&typeof e=="object"){if(f.constructor!==e.constructor)return false;var n,s,l;if(Array.isArray(f)){n=f.length;if(n!=e.length)return false;for(s=n;s--!==0;)if(!equal(f[s],e[s]))return false;return true}if(f.constructor===RegExp)return f.source===e.source&&f.flags===e.flags;if(f.valueOf!==Object.prototype.valueOf)return f.valueOf()===e.valueOf();if(f.toString!==Object.prototype.toString)return f.toString()===e.toString();l=Object.keys(f);n=l.length;if(n!==Object.keys(e).length)return false;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(e,l[s]))return false;for(s=n;s--!==0;){var v=l[s];if(!equal(f[v],e[v]))return false}return true}return f!==f&&e!==e}},3600:f=>{"use strict";f.exports=function(f,e){if(!e)e={};if(typeof e==="function")e={cmp:e};var n=typeof e.cycles==="boolean"?e.cycles:false;var s=e.cmp&&function(f){return function(e){return function(n,s){var l={key:n,value:e[n]};var v={key:s,value:e[s]};return f(l,v)}}}(e.cmp);var l=[];return function stringify(f){if(f&&f.toJSON&&typeof f.toJSON==="function"){f=f.toJSON()}if(f===undefined)return;if(typeof f=="number")return isFinite(f)?""+f:"null";if(typeof f!=="object")return JSON.stringify(f);var e,v;if(Array.isArray(f)){v="[";for(e=0;e{(function(){var e;function MurmurHash3(f,n){var s=this instanceof MurmurHash3?this:e;s.reset(n);if(typeof f==="string"&&f.length>0){s.hash(f)}if(s!==this){return s}}MurmurHash3.prototype.hash=function(f){var e,n,s,l,v;v=f.length;this.len+=v;n=this.k1;s=0;switch(this.rem){case 0:n^=v>s?f.charCodeAt(s++)&65535:0;case 1:n^=v>s?(f.charCodeAt(s++)&65535)<<8:0;case 2:n^=v>s?(f.charCodeAt(s++)&65535)<<16:0;case 3:n^=v>s?(f.charCodeAt(s)&255)<<24:0;n^=v>s?(f.charCodeAt(s++)&65280)>>8:0}this.rem=v+this.rem&3;v-=this.rem;if(v>0){e=this.h1;while(1){n=n*11601+(n&65535)*3432906752&4294967295;n=n<<15|n>>>17;n=n*13715+(n&65535)*461832192&4294967295;e^=n;e=e<<13|e>>>19;e=e*5+3864292196&4294967295;if(s>=v){break}n=f.charCodeAt(s++)&65535^(f.charCodeAt(s++)&65535)<<8^(f.charCodeAt(s++)&65535)<<16;l=f.charCodeAt(s++);n^=(l&255)<<24^(l&65280)>>8}n=0;switch(this.rem){case 3:n^=(f.charCodeAt(s+2)&65535)<<16;case 2:n^=(f.charCodeAt(s+1)&65535)<<8;case 1:n^=f.charCodeAt(s)&65535}this.h1=e}this.k1=n;return this};MurmurHash3.prototype.result=function(){var f,e;f=this.k1;e=this.h1;if(f>0){f=f*11601+(f&65535)*3432906752&4294967295;f=f<<15|f>>>17;f=f*13715+(f&65535)*461832192&4294967295;e^=f}e^=this.len;e^=e>>>16;e=e*51819+(e&65535)*2246770688&4294967295;e^=e>>>13;e=e*44597+(e&65535)*3266445312&4294967295;e^=e>>>16;return e>>>0};MurmurHash3.prototype.reset=function(f){this.h1=typeof f==="number"?f:0;this.rem=this.k1=this.len=0;return this};e=new MurmurHash3;if(true){f.exports=MurmurHash3}else{}})()},3010:f=>{f.exports=isTypedArray;isTypedArray.strict=isStrictTypedArray;isTypedArray.loose=isLooseTypedArray;var e=Object.prototype.toString;var n={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function isTypedArray(f){return isStrictTypedArray(f)||isLooseTypedArray(f)}function isStrictTypedArray(f){return f instanceof Int8Array||f instanceof Int16Array||f instanceof Int32Array||f instanceof Uint8Array||f instanceof Uint8ClampedArray||f instanceof Uint16Array||f instanceof Uint32Array||f instanceof Float32Array||f instanceof Float64Array}function isLooseTypedArray(f){return n[e.call(f)]}},2437:f=>{"use strict";var e=f.exports=function(f,e,n){if(typeof e=="function"){n=e;e={}}n=e.cb||n;var s=typeof n=="function"?n:n.pre||function(){};var l=n.post||function(){};_traverse(e,s,l,f,"",f)};e.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true};e.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};e.propsKeywords={definitions:true,properties:true,patternProperties:true,dependencies:true};e.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(f,n,s,l,v,r,b,g,w,j){if(l&&typeof l=="object"&&!Array.isArray(l)){n(l,v,r,b,g,w,j);for(var d in l){var E=l[d];if(Array.isArray(E)){if(d in e.arrayKeywords){for(var R=0;R{"use strict";const s=n(5747);const l=n(5622);const{promisify:v}=n(1669);const r=n(2519);const b=r.satisfies(process.version,">=10.12.0");const g=f=>{if(process.platform==="win32"){const e=/[<>:"|?*]/.test(f.replace(l.parse(f).root,""));if(e){const e=new Error(`Path contains invalid characters: ${f}`);e.code="EINVAL";throw e}}};const w=f=>{const e={mode:511&~process.umask(),fs:s};return{...e,...f}};const j=f=>{const e=new Error(`operation not permitted, mkdir '${f}'`);e.code="EPERM";e.errno=-4048;e.path=f;e.syscall="mkdir";return e};const d=async(f,e)=>{g(f);e=w(e);const n=v(e.fs.mkdir);const r=v(e.fs.stat);if(b&&e.fs.mkdir===s.mkdir){const s=l.resolve(f);await n(s,{mode:e.mode,recursive:true});return s}const d=async f=>{try{await n(f,e.mode);return f}catch(e){if(e.code==="EPERM"){throw e}if(e.code==="ENOENT"){if(l.dirname(f)===f){throw j(f)}if(e.message.includes("null bytes")){throw e}await d(l.dirname(f));return d(f)}try{const n=await r(f);if(!n.isDirectory()){throw new Error("The path is not a directory")}}catch(f){throw e}return f}};return d(l.resolve(f))};f.exports=d;f.exports.sync=((f,e)=>{g(f);e=w(e);if(b&&e.fs.mkdirSync===s.mkdirSync){const n=l.resolve(f);s.mkdirSync(n,{mode:e.mode,recursive:true});return n}const n=f=>{try{e.fs.mkdirSync(f,e.mode)}catch(s){if(s.code==="EPERM"){throw s}if(s.code==="ENOENT"){if(l.dirname(f)===f){throw j(f)}if(s.message.includes("null bytes")){throw s}n(l.dirname(f));return n(f)}try{if(!e.fs.statSync(f).isDirectory()){throw new Error("The path is not a directory")}}catch(f){throw s}}return f};return n(l.resolve(f))})},6536:(f,e,n)=>{"use strict";const s=n(4442);f.exports=(async({cwd:f}={})=>s("package.json",{cwd:f}));f.exports.sync=(({cwd:f}={})=>s.sync("package.json",{cwd:f}))},2317:(f,e,n)=>{var s=n(2357);var l=n(2935);var v=n(8614);if(typeof v!=="function"){v=v.EventEmitter}var r;if(process.__signal_exit_emitter__){r=process.__signal_exit_emitter__}else{r=process.__signal_exit_emitter__=new v;r.count=0;r.emitted={}}if(!r.infinite){r.setMaxListeners(Infinity);r.infinite=true}f.exports=function(f,e){s.equal(typeof f,"function","a callback must be provided for exit handler");if(g===false){load()}var n="exit";if(e&&e.alwaysLast){n="afterexit"}var l=function(){r.removeListener(n,f);if(r.listeners("exit").length===0&&r.listeners("afterexit").length===0){unload()}};r.on(n,f);return l};f.exports.unload=unload;function unload(){if(!g){return}g=false;l.forEach(function(f){try{process.removeListener(f,b[f])}catch(f){}});process.emit=j;process.reallyExit=w;r.count-=1}function emit(f,e,n){if(r.emitted[f]){return}r.emitted[f]=true;r.emit(f,e,n)}var b={};l.forEach(function(f){b[f]=function listener(){var e=process.listeners(f);if(e.length===r.count){unload();emit("exit",null,f);emit("afterexit",null,f);process.kill(process.pid,f)}}});f.exports.signals=function(){return l};f.exports.load=load;var g=false;function load(){if(g){return}g=true;r.count+=1;l=l.filter(function(f){try{process.on(f,b[f]);return true}catch(f){return false}});process.emit=processEmit;process.reallyExit=processReallyExit}var w=process.reallyExit;function processReallyExit(f){process.exitCode=f||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);w.call(process,process.exitCode)}var j=process.emit;function processEmit(f,e){if(f==="exit"){if(e!==undefined){process.exitCode=e}var n=j.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return n}else{return j.apply(this,arguments)}}},2935:f=>{f.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){f.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){f.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},4005:(f,e,n)=>{var s=n(3010).strict;f.exports=function typedarrayToBuffer(f){if(s(f)){var e=Buffer.from(f.buffer);if(f.byteLength!==f.buffer.byteLength){e=e.slice(f.byteOffset,f.byteOffset+f.byteLength)}return e}else{return Buffer.from(f)}}},4007:function(f,e){(function(f,n){true?n(e):0})(this,function(f){"use strict";function merge(){for(var f=arguments.length,e=Array(f),n=0;n1){e[0]=e[0].slice(0,-1);var s=e.length-1;for(var l=1;l= 0x80 (not a basic code point)","invalid-input":"Invalid input"};var x=r-b;var z=Math.floor;var U=String.fromCharCode;function error$1(f){throw new RangeError(I[f])}function map(f,e){var n=[];var s=f.length;while(s--){n[s]=e(f[s])}return n}function mapDomain(f,e){var n=f.split("@");var s="";if(n.length>1){s=n[0]+"@";f=n[1]}f=f.replace(p,".");var l=f.split(".");var v=map(l,e).join(".");return s+v}function ucs2decode(f){var e=[];var n=0;var s=f.length;while(n=55296&&l<=56319&&n>1;f+=z(f/e);for(;f>x*g>>1;s+=r){f=z(f/x)}return z(s+(x+1)*f/(f+w))};var C=function decode(f){var e=[];var n=f.length;var s=0;var l=E;var w=d;var j=f.lastIndexOf(R);if(j<0){j=0}for(var A=0;A=128){error$1("not-basic")}e.push(f.charCodeAt(A))}for(var F=j>0?j+1:0;F=n){error$1("invalid-input")}var U=Q(f.charCodeAt(F++));if(U>=r||U>z((v-s)/I)){error$1("overflow")}s+=U*I;var N=x<=w?b:x>=w+g?g:x-w;if(Uz(v/q)){error$1("overflow")}I*=q}var C=e.length+1;w=O(s-p,C,p==0);if(z(s/C)>v-l){error$1("overflow")}l+=z(s/C);s%=C;e.splice(s++,0,l)}return String.fromCodePoint.apply(String,e)};var L=function encode(f){var e=[];f=ucs2decode(f);var n=f.length;var s=E;var l=0;var w=d;var j=true;var A=false;var F=undefined;try{for(var p=f[Symbol.iterator](),I;!(j=(I=p.next()).done);j=true){var x=I.value;if(x<128){e.push(U(x))}}}catch(f){A=true;F=f}finally{try{if(!j&&p.return){p.return()}}finally{if(A){throw F}}}var N=e.length;var Q=N;if(N){e.push(R)}while(Q=s&&Xz((v-l)/M)){error$1("overflow")}l+=(C-s)*M;s=C;var Y=true;var W=false;var B=undefined;try{for(var c=f[Symbol.iterator](),Z;!(Y=(Z=c.next()).done);Y=true){var D=Z.value;if(Dv){error$1("overflow")}if(D==s){var K=l;for(var V=r;;V+=r){var y=V<=w?b:V>=w+g?g:V-w;if(K>6|192).toString(16).toUpperCase()+"%"+(e&63|128).toString(16).toUpperCase();else n="%"+(e>>12|224).toString(16).toUpperCase()+"%"+(e>>6&63|128).toString(16).toUpperCase()+"%"+(e&63|128).toString(16).toUpperCase();return n}function pctDecChars(f){var e="";var n=0;var s=f.length;while(n=194&&l<224){if(s-n>=6){var v=parseInt(f.substr(n+4,2),16);e+=String.fromCharCode((l&31)<<6|v&63)}else{e+=f.substr(n,6)}n+=6}else if(l>=224){if(s-n>=9){var r=parseInt(f.substr(n+4,2),16);var b=parseInt(f.substr(n+7,2),16);e+=String.fromCharCode((l&15)<<12|(r&63)<<6|b&63)}else{e+=f.substr(n,9)}n+=9}else{e+=f.substr(n,3);n+=3}}return e}function _normalizeComponentEncoding(f,e){function decodeUnreserved(f){var n=pctDecChars(f);return!n.match(e.UNRESERVED)?f:n}if(f.scheme)f.scheme=String(f.scheme).replace(e.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(e.NOT_SCHEME,"");if(f.userinfo!==undefined)f.userinfo=String(f.userinfo).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_USERINFO,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.host!==undefined)f.host=String(f.host).replace(e.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(e.NOT_HOST,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.path!==undefined)f.path=String(f.path).replace(e.PCT_ENCODED,decodeUnreserved).replace(f.scheme?e.NOT_PATH:e.NOT_PATH_NOSCHEME,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.query!==undefined)f.query=String(f.query).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_QUERY,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);if(f.fragment!==undefined)f.fragment=String(f.fragment).replace(e.PCT_ENCODED,decodeUnreserved).replace(e.NOT_FRAGMENT,pctEncChar).replace(e.PCT_ENCODED,toUpperCase);return f}function _stripLeadingZeros(f){return f.replace(/^0*(.*)/,"$1")||"0"}function _normalizeIPv4(f,e){var n=f.match(e.IPV4ADDRESS)||[];var l=s(n,2),v=l[1];if(v){return v.split(".").map(_stripLeadingZeros).join(".")}else{return f}}function _normalizeIPv6(f,e){var n=f.match(e.IPV6ADDRESS)||[];var l=s(n,3),v=l[1],r=l[2];if(v){var b=v.toLowerCase().split("::").reverse(),g=s(b,2),w=g[0],j=g[1];var d=j?j.split(":").map(_stripLeadingZeros):[];var E=w.split(":").map(_stripLeadingZeros);var R=e.IPV4ADDRESS.test(E[E.length-1]);var A=R?7:8;var F=E.length-A;var p=Array(A);for(var I=0;I1){var N=p.slice(0,z.index);var Q=p.slice(z.index+z.length);U=N.join(":")+"::"+Q.join(":")}else{U=p.join(":")}if(r){U+="%"+r}return U}else{return f}}var X=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;var M="".match(/(){0}/)[1]===undefined;function parse(f){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l={};var v=s.iri!==false?n:e;if(s.reference==="suffix")f=(s.scheme?s.scheme+":":"")+"//"+f;var r=f.match(X);if(r){if(M){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=f.indexOf("@")!==-1?r[3]:undefined;l.host=f.indexOf("//")!==-1?r[4]:undefined;l.port=parseInt(r[5],10);l.path=r[6]||"";l.query=f.indexOf("?")!==-1?r[7]:undefined;l.fragment=f.indexOf("#")!==-1?r[8]:undefined;if(isNaN(l.port)){l.port=f.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 b=H[(s.scheme||l.scheme||"").toLowerCase()];if(!s.unicodeSupport&&(!b||!b.unicodeSupport)){if(l.host&&(s.domainHost||b&&b.domainHost)){try{l.host=G.toASCII(l.host.replace(v.PCT_ENCODED,pctDecChars).toLowerCase())}catch(f){l.error=l.error||"Host's domain name can not be converted to ASCII via punycode: "+f}}_normalizeComponentEncoding(l,e)}else{_normalizeComponentEncoding(l,v)}if(b&&b.parse){b.parse(l,s)}}else{l.error=l.error||"URI can not be parsed."}return l}function _recomposeAuthority(f,s){var l=s.iri!==false?n:e;var v=[];if(f.userinfo!==undefined){v.push(f.userinfo);v.push("@")}if(f.host!==undefined){v.push(_normalizeIPv6(_normalizeIPv4(String(f.host),l),l).replace(l.IPV6ADDRESS,function(f,e,n){return"["+e+(n?"%25"+n:"")+"]"}))}if(typeof f.port==="number"){v.push(":");v.push(f.port.toString(10))}return v.length?v.join(""):undefined}var Y=/^\.\.?\//;var W=/^\/\.(\/|$)/;var B=/^\/\.\.(\/|$)/;var c=/^\/?(?:.|\n)*?(?=\/|$)/;function removeDotSegments(f){var e=[];while(f.length){if(f.match(Y)){f=f.replace(Y,"")}else if(f.match(W)){f=f.replace(W,"/")}else if(f.match(B)){f=f.replace(B,"/");e.pop()}else if(f==="."||f===".."){f=""}else{var n=f.match(c);if(n){var s=n[0];f=f.slice(s.length);e.push(s)}else{throw new Error("Unexpected dot segment condition")}}}return e.join("")}function serialize(f){var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var l=s.iri?n:e;var v=[];var r=H[(s.scheme||f.scheme||"").toLowerCase()];if(r&&r.serialize)r.serialize(f,s);if(f.host){if(l.IPV6ADDRESS.test(f.host)){}else if(s.domainHost||r&&r.domainHost){try{f.host=!s.iri?G.toASCII(f.host.replace(l.PCT_ENCODED,pctDecChars).toLowerCase()):G.toUnicode(f.host)}catch(e){f.error=f.error||"Host's domain name can not be converted to "+(!s.iri?"ASCII":"Unicode")+" via punycode: "+e}}}_normalizeComponentEncoding(f,l);if(s.reference!=="suffix"&&f.scheme){v.push(f.scheme);v.push(":")}var b=_recomposeAuthority(f,s);if(b!==undefined){if(s.reference!=="suffix"){v.push("//")}v.push(b);if(f.path&&f.path.charAt(0)!=="/"){v.push("/")}}if(f.path!==undefined){var g=f.path;if(!s.absolutePath&&(!r||!r.absolutePath)){g=removeDotSegments(g)}if(b===undefined){g=g.replace(/^\/\//,"/%2F")}v.push(g)}if(f.query!==undefined){v.push("?");v.push(f.query)}if(f.fragment!==undefined){v.push("#");v.push(f.fragment)}return v.join("")}function resolveComponents(f,e){var n=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var s=arguments[3];var l={};if(!s){f=parse(serialize(f,n),n);e=parse(serialize(e,n),n)}n=n||{};if(!n.tolerant&&e.scheme){l.scheme=e.scheme;l.userinfo=e.userinfo;l.host=e.host;l.port=e.port;l.path=removeDotSegments(e.path||"");l.query=e.query}else{if(e.userinfo!==undefined||e.host!==undefined||e.port!==undefined){l.userinfo=e.userinfo;l.host=e.host;l.port=e.port;l.path=removeDotSegments(e.path||"");l.query=e.query}else{if(!e.path){l.path=f.path;if(e.query!==undefined){l.query=e.query}else{l.query=f.query}}else{if(e.path.charAt(0)==="/"){l.path=removeDotSegments(e.path)}else{if((f.userinfo!==undefined||f.host!==undefined||f.port!==undefined)&&!f.path){l.path="/"+e.path}else if(!f.path){l.path=e.path}else{l.path=f.path.slice(0,f.path.lastIndexOf("/")+1)+e.path}l.path=removeDotSegments(l.path)}l.query=e.query}l.userinfo=f.userinfo;l.host=f.host;l.port=f.port}l.scheme=f.scheme}l.fragment=e.fragment;return l}function resolve(f,e,n){var s=assign({scheme:"null"},n);return serialize(resolveComponents(parse(f,s),parse(e,s),s,true),s)}function normalize(f,e){if(typeof f==="string"){f=serialize(parse(f,e),e)}else if(typeOf(f)==="object"){f=parse(serialize(f,e),e)}return f}function equal(f,e,n){if(typeof f==="string"){f=serialize(parse(f,n),n)}else if(typeOf(f)==="object"){f=serialize(f,n)}if(typeof e==="string"){e=serialize(parse(e,n),n)}else if(typeOf(e)==="object"){e=serialize(e,n)}return f===e}function escapeComponent(f,s){return f&&f.toString().replace(!s||!s.iri?e.ESCAPE:n.ESCAPE,pctEncChar)}function unescapeComponent(f,s){return f&&f.toString().replace(!s||!s.iri?e.PCT_ENCODED:n.PCT_ENCODED,pctDecChars)}var Z={scheme:"http",domainHost:true,parse:function parse(f,e){if(!f.host){f.error=f.error||"HTTP URIs must have a host."}return f},serialize:function serialize(f,e){if(f.port===(String(f.scheme).toLowerCase()!=="https"?80:443)||f.port===""){f.port=undefined}if(!f.path){f.path="/"}return f}};var D={scheme:"https",domainHost:Z.domainHost,parse:Z.parse,serialize:Z.serialize};var K={};var V=true;var y="[A-Za-z0-9\\-\\.\\_\\~"+(V?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]";var k="[0-9A-Fa-f]";var h=subexp(subexp("%[EFef]"+k+"%"+k+k+"%"+k+k)+"|"+subexp("%[89A-Fa-f]"+k+"%"+k+k)+"|"+subexp("%"+k+k));var a="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";var S="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";var m=merge(S,'[\\"\\\\]');var P="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";var i=new RegExp(y,"g");var _=new RegExp(h,"g");var u=new RegExp(merge("[^]",a,"[\\.]",'[\\"]',m),"g");var o=new RegExp(merge("[^]",y,P),"g");var $=o;function decodeUnreserved(f){var e=pctDecChars(f);return!e.match(i)?f:e}var t={scheme:"mailto",parse:function parse$$1(f,e){var n=f;var s=n.to=n.path?n.path.split(","):[];n.path=undefined;if(n.query){var l=false;var v={};var r=n.query.split("&");for(var b=0,g=r.length;b{"use strict";f.exports=writeFile;f.exports.sync=writeFileSync;f.exports._getTmpname=getTmpname;f.exports._cleanupOnExit=cleanupOnExit;const s=n(5747);const l=n(8681);const v=n(2317);const r=n(5622);const b=n(3010);const g=n(4005);const{promisify:w}=n(1669);const j={};const d=function getId(){try{const f=n(5013);return f.threadId}catch(f){return 0}}();let E=0;function getTmpname(f){return f+"."+l(__filename).hash(String(process.pid)).hash(String(d)).hash(String(++E)).result()}function cleanupOnExit(f){return()=>{try{s.unlinkSync(typeof f==="function"?f():f)}catch(f){}}}function serializeActiveFile(f){return new Promise(e=>{if(!j[f])j[f]=[];j[f].push(e);if(j[f].length===1)e()})}async function writeFileAsync(f,e,n={}){if(typeof n==="string"){n={encoding:n}}let l;let d;const E=v(cleanupOnExit(()=>d));const R=r.resolve(f);try{await serializeActiveFile(R);const v=await w(s.realpath)(f).catch(()=>f);d=getTmpname(v);if(!n.mode||!n.chown){const f=await w(s.stat)(v).catch(()=>{});if(f){if(n.mode==null){n.mode=f.mode}if(n.chown==null&&process.getuid){n.chown={uid:f.uid,gid:f.gid}}}}l=await w(s.open)(d,"w",n.mode);if(n.tmpfileCreated){await n.tmpfileCreated(d)}if(b(e)){e=g(e)}if(Buffer.isBuffer(e)){await w(s.write)(l,e,0,e.length,0)}else if(e!=null){await w(s.write)(l,String(e),0,String(n.encoding||"utf8"))}if(n.fsync!==false){await w(s.fsync)(l)}await w(s.close)(l);l=null;if(n.chown){await w(s.chown)(d,n.chown.uid,n.chown.gid)}if(n.mode){await w(s.chmod)(d,n.mode)}await w(s.rename)(d,v)}finally{if(l){await w(s.close)(l).catch(()=>{})}E();await w(s.unlink)(d).catch(()=>{});j[R].shift();if(j[R].length>0){j[R][0]()}else delete j[R]}}function writeFile(f,e,n,s){if(n instanceof Function){s=n;n={}}const l=writeFileAsync(f,e,n);if(s){l.then(s,s)}return l}function writeFileSync(f,e,n){if(typeof n==="string")n={encoding:n};else if(!n)n={};try{f=s.realpathSync(f)}catch(f){}const l=getTmpname(f);if(!n.mode||!n.chown){try{const e=s.statSync(f);n=Object.assign({},n);if(!n.mode){n.mode=e.mode}if(!n.chown&&process.getuid){n.chown={uid:e.uid,gid:e.gid}}}catch(f){}}let r;const w=cleanupOnExit(l);const j=v(w);let d=true;try{r=s.openSync(l,"w",n.mode);if(n.tmpfileCreated){n.tmpfileCreated(l)}if(b(e)){e=g(e)}if(Buffer.isBuffer(e)){s.writeSync(r,e,0,e.length,0)}else if(e!=null){s.writeSync(r,String(e),0,String(n.encoding||"utf8"))}if(n.fsync!==false){s.fsyncSync(r)}s.closeSync(r);r=null;if(n.chown)s.chownSync(l,n.chown.uid,n.chown.gid);if(n.mode)s.chmodSync(l,n.mode);s.renameSync(l,f);d=false}finally{if(r){try{s.closeSync(r)}catch(f){}}j();if(d){w()}}}},2357:f=>{"use strict";f.exports=require("assert")},6417:f=>{"use strict";f.exports=require("crypto")},8614:f=>{"use strict";f.exports=require("events")},5747:f=>{"use strict";f.exports=require("fs")},4442:f=>{"use strict";f.exports=require("next/dist/compiled/find-up")},2519:f=>{"use strict";f.exports=require("next/dist/compiled/semver")},2087:f=>{"use strict";f.exports=require("os")},5622:f=>{"use strict";f.exports=require("path")},1669:f=>{"use strict";f.exports=require("util")},5013:f=>{"use strict";f.exports=require("worker_threads")}};var e={};function __nccwpck_require__(n){if(e[n]){return e[n].exports}var s=e[n]={id:n,loaded:false,exports:{}};var l=true;try{f[n].call(s.exports,s,s.exports,__nccwpck_require__);l=false}finally{if(l)delete e[n]}s.loaded=true;return s.exports}(()=>{__nccwpck_require__.nmd=(f=>{f.paths=[];if(!f.children)f.children=[];return f})})();__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(3331)})(); \ No newline at end of file diff --git a/packages/next/compiled/json5/index.js b/packages/next/compiled/json5/index.js index 212fd101debe4..f4ace338c664c 100644 --- a/packages/next/compiled/json5/index.js +++ b/packages/next/compiled/json5/index.js @@ -1 +1 @@ -module.exports=(()=>{var u={946:(u,D,e)=>{const r=e(975);const F=e(230);const C={parse:r,stringify:F};u.exports=C},975:(u,D,e)=>{const r=e(685);let F;let C;let A;let t;let n;let E;let i;let a;let B;u.exports=function parse(u,D){F=String(u);C="start";A=[];t=0;n=1;E=0;i=undefined;a=undefined;B=undefined;do{i=lex();h[C]()}while(i.type!=="eof");if(typeof D==="function"){return internalize({"":B},"",D)}return B};function internalize(u,D,e){const r=u[D];if(r!=null&&typeof r==="object"){for(const u in r){const D=internalize(r,u,e);if(D===undefined){delete r[u]}else{r[u]=D}}}return e.call(u,D,r)}let s;let o;let c;let d;let f;function lex(){s="default";o="";c=false;d=1;for(;;){f=peek();const u=l[s]();if(u){return u}}}function peek(){if(F[t]){return String.fromCodePoint(F.codePointAt(t))}}function read(){const u=peek();if(u==="\n"){n++;E=0}else if(u){E+=u.length}else{E++}if(u){t+=u.length}return u}const l={default(){switch(f){case"\t":case"\v":case"\f":case" ":case" ":case"\ufeff":case"\n":case"\r":case"\u2028":case"\u2029":read();return;case"/":read();s="comment";return;case undefined:read();return newToken("eof")}if(r.isSpaceSeparator(f)){read();return}return l[C]()},comment(){switch(f){case"*":read();s="multiLineComment";return;case"/":read();s="singleLineComment";return}throw invalidChar(read())},multiLineComment(){switch(f){case"*":read();s="multiLineCommentAsterisk";return;case undefined:throw invalidChar(read())}read()},multiLineCommentAsterisk(){switch(f){case"*":read();return;case"/":read();s="default";return;case undefined:throw invalidChar(read())}read();s="multiLineComment"},singleLineComment(){switch(f){case"\n":case"\r":case"\u2028":case"\u2029":read();s="default";return;case undefined:read();return newToken("eof")}read()},value(){switch(f){case"{":case"[":return newToken("punctuator",read());case"n":read();literal("ull");return newToken("null",null);case"t":read();literal("rue");return newToken("boolean",true);case"f":read();literal("alse");return newToken("boolean",false);case"-":case"+":if(read()==="-"){d=-1}s="sign";return;case".":o=read();s="decimalPointLeading";return;case"0":o=read();s="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o=read();s="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",Infinity);case"N":read();literal("aN");return newToken("numeric",NaN);case'"':case"'":c=read()==='"';o="";s="string";return}throw invalidChar(read())},identifierNameStartEscape(){if(f!=="u"){throw invalidChar(read())}read();const u=unicodeEscape();switch(u){case"$":case"_":break;default:if(!r.isIdStartChar(u)){throw invalidIdentifier()}break}o+=u;s="identifierName"},identifierName(){switch(f){case"$":case"_":case"‌":case"‍":o+=read();return;case"\\":read();s="identifierNameEscape";return}if(r.isIdContinueChar(f)){o+=read();return}return newToken("identifier",o)},identifierNameEscape(){if(f!=="u"){throw invalidChar(read())}read();const u=unicodeEscape();switch(u){case"$":case"_":case"‌":case"‍":break;default:if(!r.isIdContinueChar(u)){throw invalidIdentifier()}break}o+=u;s="identifierName"},sign(){switch(f){case".":o=read();s="decimalPointLeading";return;case"0":o=read();s="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o=read();s="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",d*Infinity);case"N":read();literal("aN");return newToken("numeric",NaN)}throw invalidChar(read())},zero(){switch(f){case".":o+=read();s="decimalPoint";return;case"e":case"E":o+=read();s="decimalExponent";return;case"x":case"X":o+=read();s="hexadecimal";return}return newToken("numeric",d*0)},decimalInteger(){switch(f){case".":o+=read();s="decimalPoint";return;case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},decimalPointLeading(){if(r.isDigit(f)){o+=read();s="decimalFraction";return}throw invalidChar(read())},decimalPoint(){switch(f){case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();s="decimalFraction";return}return newToken("numeric",d*Number(o))},decimalFraction(){switch(f){case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},decimalExponent(){switch(f){case"+":case"-":o+=read();s="decimalExponentSign";return}if(r.isDigit(f)){o+=read();s="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentSign(){if(r.isDigit(f)){o+=read();s="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentInteger(){if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},hexadecimal(){if(r.isHexDigit(f)){o+=read();s="hexadecimalInteger";return}throw invalidChar(read())},hexadecimalInteger(){if(r.isHexDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},string(){switch(f){case"\\":read();o+=escape();return;case'"':if(c){read();return newToken("string",o)}o+=read();return;case"'":if(!c){read();return newToken("string",o)}o+=read();return;case"\n":case"\r":throw invalidChar(read());case"\u2028":case"\u2029":separatorChar(f);break;case undefined:throw invalidChar(read())}o+=read()},start(){switch(f){case"{":case"[":return newToken("punctuator",read())}s="value"},beforePropertyName(){switch(f){case"$":case"_":o=read();s="identifierName";return;case"\\":read();s="identifierNameStartEscape";return;case"}":return newToken("punctuator",read());case'"':case"'":c=read()==='"';s="string";return}if(r.isIdStartChar(f)){o+=read();s="identifierName";return}throw invalidChar(read())},afterPropertyName(){if(f===":"){return newToken("punctuator",read())}throw invalidChar(read())},beforePropertyValue(){s="value"},afterPropertyValue(){switch(f){case",":case"}":return newToken("punctuator",read())}throw invalidChar(read())},beforeArrayValue(){if(f==="]"){return newToken("punctuator",read())}s="value"},afterArrayValue(){switch(f){case",":case"]":return newToken("punctuator",read())}throw invalidChar(read())},end(){throw invalidChar(read())}};function newToken(u,D){return{type:u,value:D,line:n,column:E}}function literal(u){for(const D of u){const u=peek();if(u!==D){throw invalidChar(read())}read()}}function escape(){const u=peek();switch(u){case"b":read();return"\b";case"f":read();return"\f";case"n":read();return"\n";case"r":read();return"\r";case"t":read();return"\t";case"v":read();return"\v";case"0":read();if(r.isDigit(peek())){throw invalidChar(read())}return"\0";case"x":read();return hexEscape();case"u":read();return unicodeEscape();case"\n":case"\u2028":case"\u2029":read();return"";case"\r":read();if(peek()==="\n"){read()}return"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw invalidChar(read());case undefined:throw invalidChar(read())}return read()}function hexEscape(){let u="";let D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read();D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read();return String.fromCodePoint(parseInt(u,16))}function unicodeEscape(){let u="";let D=4;while(D-- >0){const D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read()}return String.fromCodePoint(parseInt(u,16))}const h={start(){if(i.type==="eof"){throw invalidEOF()}push()},beforePropertyName(){switch(i.type){case"identifier":case"string":a=i.value;C="afterPropertyName";return;case"punctuator":pop();return;case"eof":throw invalidEOF()}},afterPropertyName(){if(i.type==="eof"){throw invalidEOF()}C="beforePropertyValue"},beforePropertyValue(){if(i.type==="eof"){throw invalidEOF()}push()},beforeArrayValue(){if(i.type==="eof"){throw invalidEOF()}if(i.type==="punctuator"&&i.value==="]"){pop();return}push()},afterPropertyValue(){if(i.type==="eof"){throw invalidEOF()}switch(i.value){case",":C="beforePropertyName";return;case"}":pop()}},afterArrayValue(){if(i.type==="eof"){throw invalidEOF()}switch(i.value){case",":C="beforeArrayValue";return;case"]":pop()}},end(){}};function push(){let u;switch(i.type){case"punctuator":switch(i.value){case"{":u={};break;case"[":u=[];break}break;case"null":case"boolean":case"numeric":case"string":u=i.value;break}if(B===undefined){B=u}else{const D=A[A.length-1];if(Array.isArray(D)){D.push(u)}else{D[a]=u}}if(u!==null&&typeof u==="object"){A.push(u);if(Array.isArray(u)){C="beforeArrayValue"}else{C="beforePropertyName"}}else{const u=A[A.length-1];if(u==null){C="end"}else if(Array.isArray(u)){C="afterArrayValue"}else{C="afterPropertyValue"}}}function pop(){A.pop();const u=A[A.length-1];if(u==null){C="end"}else if(Array.isArray(u)){C="afterArrayValue"}else{C="afterPropertyValue"}}function invalidChar(u){if(u===undefined){return syntaxError(`JSON5: invalid end of input at ${n}:${E}`)}return syntaxError(`JSON5: invalid character '${formatChar(u)}' at ${n}:${E}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${n}:${E}`)}function invalidIdentifier(){E-=5;return syntaxError(`JSON5: invalid identifier character at ${n}:${E}`)}function separatorChar(u){console.warn(`JSON5: '${formatChar(u)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(u){const D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(D[u]){return D[u]}if(u<" "){const D=u.charCodeAt(0).toString(16);return"\\x"+("00"+D).substring(D.length)}return u}function syntaxError(u){const D=new SyntaxError(u);D.lineNumber=n;D.columnNumber=E;return D}},230:(u,D,e)=>{const r=e(685);u.exports=function stringify(u,D,e){const F=[];let C="";let A;let t;let n="";let E;if(D!=null&&typeof D==="object"&&!Array.isArray(D)){e=D.space;E=D.quote;D=D.replacer}if(typeof D==="function"){t=D}else if(Array.isArray(D)){A=[];for(const u of D){let D;if(typeof u==="string"){D=u}else if(typeof u==="number"||u instanceof String||u instanceof Number){D=String(u)}if(D!==undefined&&A.indexOf(D)<0){A.push(D)}}}if(e instanceof Number){e=Number(e)}else if(e instanceof String){e=String(e)}if(typeof e==="number"){if(e>0){e=Math.min(10,Math.floor(e));n=" ".substr(0,e)}}else if(typeof e==="string"){n=e.substr(0,10)}return serializeProperty("",{"":u});function serializeProperty(u,D){let e=D[u];if(e!=null){if(typeof e.toJSON5==="function"){e=e.toJSON5(u)}else if(typeof e.toJSON==="function"){e=e.toJSON(u)}}if(t){e=t.call(D,u,e)}if(e instanceof Number){e=Number(e)}else if(e instanceof String){e=String(e)}else if(e instanceof Boolean){e=e.valueOf()}switch(e){case null:return"null";case true:return"true";case false:return"false"}if(typeof e==="string"){return quoteString(e,false)}if(typeof e==="number"){return String(e)}if(typeof e==="object"){return Array.isArray(e)?serializeArray(e):serializeObject(e)}return undefined}function quoteString(u){const D={"'":.1,'"':.2};const e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let F="";for(let C=0;CD[u]=0){throw TypeError("Converting circular structure to JSON5")}F.push(u);let D=C;C=C+n;let e=A||Object.keys(u);let r=[];for(const D of e){const e=serializeProperty(D,u);if(e!==undefined){let u=serializeKey(D)+":";if(n!==""){u+=" "}u+=e;r.push(u)}}let t;if(r.length===0){t="{}"}else{let u;if(n===""){u=r.join(",");t="{"+u+"}"}else{let e=",\n"+C;u=r.join(e);t="{\n"+C+u+",\n"+D+"}"}}F.pop();C=D;return t}function serializeKey(u){if(u.length===0){return quoteString(u,true)}const D=String.fromCodePoint(u.codePointAt(0));if(!r.isIdStartChar(D)){return quoteString(u,true)}for(let e=D.length;e=0){throw TypeError("Converting circular structure to JSON5")}F.push(u);let D=C;C=C+n;let e=[];for(let D=0;D{u.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;u.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;u.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},685:(u,D,e)=>{const r=e(875);u.exports={isSpaceSeparator(u){return typeof u==="string"&&r.Space_Separator.test(u)},isIdStartChar(u){return typeof u==="string"&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u==="$"||u==="_"||r.ID_Start.test(u))},isIdContinueChar(u){return typeof u==="string"&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u>="0"&&u<="9"||u==="$"||u==="_"||u==="‌"||u==="‍"||r.ID_Continue.test(u))},isDigit(u){return typeof u==="string"&&/[0-9]/.test(u)},isHexDigit(u){return typeof u==="string"&&/[0-9A-Fa-f]/.test(u)}}}};var D={};function __nccwpck_require__(e){if(D[e]){return D[e].exports}var r=D[e]={exports:{}};var F=true;try{u[e](r,r.exports,__nccwpck_require__);F=false}finally{if(F)delete D[e]}return r.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(946)})(); \ No newline at end of file +module.exports=(()=>{var u={904:(u,D,e)=>{const r=e(583);const F=e(749);const C={parse:r,stringify:F};u.exports=C},583:(u,D,e)=>{const r=e(393);let F;let C;let A;let t;let n;let E;let i;let a;let B;u.exports=function parse(u,D){F=String(u);C="start";A=[];t=0;n=1;E=0;i=undefined;a=undefined;B=undefined;do{i=lex();h[C]()}while(i.type!=="eof");if(typeof D==="function"){return internalize({"":B},"",D)}return B};function internalize(u,D,e){const r=u[D];if(r!=null&&typeof r==="object"){for(const u in r){const D=internalize(r,u,e);if(D===undefined){delete r[u]}else{r[u]=D}}}return e.call(u,D,r)}let s;let o;let c;let d;let f;function lex(){s="default";o="";c=false;d=1;for(;;){f=peek();const u=l[s]();if(u){return u}}}function peek(){if(F[t]){return String.fromCodePoint(F.codePointAt(t))}}function read(){const u=peek();if(u==="\n"){n++;E=0}else if(u){E+=u.length}else{E++}if(u){t+=u.length}return u}const l={default(){switch(f){case"\t":case"\v":case"\f":case" ":case" ":case"\ufeff":case"\n":case"\r":case"\u2028":case"\u2029":read();return;case"/":read();s="comment";return;case undefined:read();return newToken("eof")}if(r.isSpaceSeparator(f)){read();return}return l[C]()},comment(){switch(f){case"*":read();s="multiLineComment";return;case"/":read();s="singleLineComment";return}throw invalidChar(read())},multiLineComment(){switch(f){case"*":read();s="multiLineCommentAsterisk";return;case undefined:throw invalidChar(read())}read()},multiLineCommentAsterisk(){switch(f){case"*":read();return;case"/":read();s="default";return;case undefined:throw invalidChar(read())}read();s="multiLineComment"},singleLineComment(){switch(f){case"\n":case"\r":case"\u2028":case"\u2029":read();s="default";return;case undefined:read();return newToken("eof")}read()},value(){switch(f){case"{":case"[":return newToken("punctuator",read());case"n":read();literal("ull");return newToken("null",null);case"t":read();literal("rue");return newToken("boolean",true);case"f":read();literal("alse");return newToken("boolean",false);case"-":case"+":if(read()==="-"){d=-1}s="sign";return;case".":o=read();s="decimalPointLeading";return;case"0":o=read();s="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o=read();s="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",Infinity);case"N":read();literal("aN");return newToken("numeric",NaN);case'"':case"'":c=read()==='"';o="";s="string";return}throw invalidChar(read())},identifierNameStartEscape(){if(f!=="u"){throw invalidChar(read())}read();const u=unicodeEscape();switch(u){case"$":case"_":break;default:if(!r.isIdStartChar(u)){throw invalidIdentifier()}break}o+=u;s="identifierName"},identifierName(){switch(f){case"$":case"_":case"‌":case"‍":o+=read();return;case"\\":read();s="identifierNameEscape";return}if(r.isIdContinueChar(f)){o+=read();return}return newToken("identifier",o)},identifierNameEscape(){if(f!=="u"){throw invalidChar(read())}read();const u=unicodeEscape();switch(u){case"$":case"_":case"‌":case"‍":break;default:if(!r.isIdContinueChar(u)){throw invalidIdentifier()}break}o+=u;s="identifierName"},sign(){switch(f){case".":o=read();s="decimalPointLeading";return;case"0":o=read();s="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o=read();s="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",d*Infinity);case"N":read();literal("aN");return newToken("numeric",NaN)}throw invalidChar(read())},zero(){switch(f){case".":o+=read();s="decimalPoint";return;case"e":case"E":o+=read();s="decimalExponent";return;case"x":case"X":o+=read();s="hexadecimal";return}return newToken("numeric",d*0)},decimalInteger(){switch(f){case".":o+=read();s="decimalPoint";return;case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},decimalPointLeading(){if(r.isDigit(f)){o+=read();s="decimalFraction";return}throw invalidChar(read())},decimalPoint(){switch(f){case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();s="decimalFraction";return}return newToken("numeric",d*Number(o))},decimalFraction(){switch(f){case"e":case"E":o+=read();s="decimalExponent";return}if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},decimalExponent(){switch(f){case"+":case"-":o+=read();s="decimalExponentSign";return}if(r.isDigit(f)){o+=read();s="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentSign(){if(r.isDigit(f)){o+=read();s="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentInteger(){if(r.isDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},hexadecimal(){if(r.isHexDigit(f)){o+=read();s="hexadecimalInteger";return}throw invalidChar(read())},hexadecimalInteger(){if(r.isHexDigit(f)){o+=read();return}return newToken("numeric",d*Number(o))},string(){switch(f){case"\\":read();o+=escape();return;case'"':if(c){read();return newToken("string",o)}o+=read();return;case"'":if(!c){read();return newToken("string",o)}o+=read();return;case"\n":case"\r":throw invalidChar(read());case"\u2028":case"\u2029":separatorChar(f);break;case undefined:throw invalidChar(read())}o+=read()},start(){switch(f){case"{":case"[":return newToken("punctuator",read())}s="value"},beforePropertyName(){switch(f){case"$":case"_":o=read();s="identifierName";return;case"\\":read();s="identifierNameStartEscape";return;case"}":return newToken("punctuator",read());case'"':case"'":c=read()==='"';s="string";return}if(r.isIdStartChar(f)){o+=read();s="identifierName";return}throw invalidChar(read())},afterPropertyName(){if(f===":"){return newToken("punctuator",read())}throw invalidChar(read())},beforePropertyValue(){s="value"},afterPropertyValue(){switch(f){case",":case"}":return newToken("punctuator",read())}throw invalidChar(read())},beforeArrayValue(){if(f==="]"){return newToken("punctuator",read())}s="value"},afterArrayValue(){switch(f){case",":case"]":return newToken("punctuator",read())}throw invalidChar(read())},end(){throw invalidChar(read())}};function newToken(u,D){return{type:u,value:D,line:n,column:E}}function literal(u){for(const D of u){const u=peek();if(u!==D){throw invalidChar(read())}read()}}function escape(){const u=peek();switch(u){case"b":read();return"\b";case"f":read();return"\f";case"n":read();return"\n";case"r":read();return"\r";case"t":read();return"\t";case"v":read();return"\v";case"0":read();if(r.isDigit(peek())){throw invalidChar(read())}return"\0";case"x":read();return hexEscape();case"u":read();return unicodeEscape();case"\n":case"\u2028":case"\u2029":read();return"";case"\r":read();if(peek()==="\n"){read()}return"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw invalidChar(read());case undefined:throw invalidChar(read())}return read()}function hexEscape(){let u="";let D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read();D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read();return String.fromCodePoint(parseInt(u,16))}function unicodeEscape(){let u="";let D=4;while(D-- >0){const D=peek();if(!r.isHexDigit(D)){throw invalidChar(read())}u+=read()}return String.fromCodePoint(parseInt(u,16))}const h={start(){if(i.type==="eof"){throw invalidEOF()}push()},beforePropertyName(){switch(i.type){case"identifier":case"string":a=i.value;C="afterPropertyName";return;case"punctuator":pop();return;case"eof":throw invalidEOF()}},afterPropertyName(){if(i.type==="eof"){throw invalidEOF()}C="beforePropertyValue"},beforePropertyValue(){if(i.type==="eof"){throw invalidEOF()}push()},beforeArrayValue(){if(i.type==="eof"){throw invalidEOF()}if(i.type==="punctuator"&&i.value==="]"){pop();return}push()},afterPropertyValue(){if(i.type==="eof"){throw invalidEOF()}switch(i.value){case",":C="beforePropertyName";return;case"}":pop()}},afterArrayValue(){if(i.type==="eof"){throw invalidEOF()}switch(i.value){case",":C="beforeArrayValue";return;case"]":pop()}},end(){}};function push(){let u;switch(i.type){case"punctuator":switch(i.value){case"{":u={};break;case"[":u=[];break}break;case"null":case"boolean":case"numeric":case"string":u=i.value;break}if(B===undefined){B=u}else{const D=A[A.length-1];if(Array.isArray(D)){D.push(u)}else{D[a]=u}}if(u!==null&&typeof u==="object"){A.push(u);if(Array.isArray(u)){C="beforeArrayValue"}else{C="beforePropertyName"}}else{const u=A[A.length-1];if(u==null){C="end"}else if(Array.isArray(u)){C="afterArrayValue"}else{C="afterPropertyValue"}}}function pop(){A.pop();const u=A[A.length-1];if(u==null){C="end"}else if(Array.isArray(u)){C="afterArrayValue"}else{C="afterPropertyValue"}}function invalidChar(u){if(u===undefined){return syntaxError(`JSON5: invalid end of input at ${n}:${E}`)}return syntaxError(`JSON5: invalid character '${formatChar(u)}' at ${n}:${E}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${n}:${E}`)}function invalidIdentifier(){E-=5;return syntaxError(`JSON5: invalid identifier character at ${n}:${E}`)}function separatorChar(u){console.warn(`JSON5: '${formatChar(u)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(u){const D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(D[u]){return D[u]}if(u<" "){const D=u.charCodeAt(0).toString(16);return"\\x"+("00"+D).substring(D.length)}return u}function syntaxError(u){const D=new SyntaxError(u);D.lineNumber=n;D.columnNumber=E;return D}},749:(u,D,e)=>{const r=e(393);u.exports=function stringify(u,D,e){const F=[];let C="";let A;let t;let n="";let E;if(D!=null&&typeof D==="object"&&!Array.isArray(D)){e=D.space;E=D.quote;D=D.replacer}if(typeof D==="function"){t=D}else if(Array.isArray(D)){A=[];for(const u of D){let D;if(typeof u==="string"){D=u}else if(typeof u==="number"||u instanceof String||u instanceof Number){D=String(u)}if(D!==undefined&&A.indexOf(D)<0){A.push(D)}}}if(e instanceof Number){e=Number(e)}else if(e instanceof String){e=String(e)}if(typeof e==="number"){if(e>0){e=Math.min(10,Math.floor(e));n=" ".substr(0,e)}}else if(typeof e==="string"){n=e.substr(0,10)}return serializeProperty("",{"":u});function serializeProperty(u,D){let e=D[u];if(e!=null){if(typeof e.toJSON5==="function"){e=e.toJSON5(u)}else if(typeof e.toJSON==="function"){e=e.toJSON(u)}}if(t){e=t.call(D,u,e)}if(e instanceof Number){e=Number(e)}else if(e instanceof String){e=String(e)}else if(e instanceof Boolean){e=e.valueOf()}switch(e){case null:return"null";case true:return"true";case false:return"false"}if(typeof e==="string"){return quoteString(e,false)}if(typeof e==="number"){return String(e)}if(typeof e==="object"){return Array.isArray(e)?serializeArray(e):serializeObject(e)}return undefined}function quoteString(u){const D={"'":.1,'"':.2};const e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let F="";for(let C=0;CD[u]=0){throw TypeError("Converting circular structure to JSON5")}F.push(u);let D=C;C=C+n;let e=A||Object.keys(u);let r=[];for(const D of e){const e=serializeProperty(D,u);if(e!==undefined){let u=serializeKey(D)+":";if(n!==""){u+=" "}u+=e;r.push(u)}}let t;if(r.length===0){t="{}"}else{let u;if(n===""){u=r.join(",");t="{"+u+"}"}else{let e=",\n"+C;u=r.join(e);t="{\n"+C+u+",\n"+D+"}"}}F.pop();C=D;return t}function serializeKey(u){if(u.length===0){return quoteString(u,true)}const D=String.fromCodePoint(u.codePointAt(0));if(!r.isIdStartChar(D)){return quoteString(u,true)}for(let e=D.length;e=0){throw TypeError("Converting circular structure to JSON5")}F.push(u);let D=C;C=C+n;let e=[];for(let D=0;D{u.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;u.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;u.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},393:(u,D,e)=>{const r=e(927);u.exports={isSpaceSeparator(u){return typeof u==="string"&&r.Space_Separator.test(u)},isIdStartChar(u){return typeof u==="string"&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u==="$"||u==="_"||r.ID_Start.test(u))},isIdContinueChar(u){return typeof u==="string"&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u>="0"&&u<="9"||u==="$"||u==="_"||u==="‌"||u==="‍"||r.ID_Continue.test(u))},isDigit(u){return typeof u==="string"&&/[0-9]/.test(u)},isHexDigit(u){return typeof u==="string"&&/[0-9A-Fa-f]/.test(u)}}}};var D={};function __nccwpck_require__(e){if(D[e]){return D[e].exports}var r=D[e]={exports:{}};var F=true;try{u[e](r,r.exports,__nccwpck_require__);F=false}finally{if(F)delete D[e]}return r.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(904)})(); \ No newline at end of file diff --git a/packages/next/compiled/terser/bundle.min.js b/packages/next/compiled/terser/bundle.min.js index 0db7b0b3bf16b..92cf9f22491e8 100644 --- a/packages/next/compiled/terser/bundle.min.js +++ b/packages/next/compiled/terser/bundle.min.js @@ -1 +1 @@ -module.exports=(()=>{var e={89:function(e,t){(function(e,n){true?n(t):0})(this,function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var n="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-Ᶎꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭧꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var c=[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];var l=[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];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)||isInAstralSet(e,l)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var h={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return h[e]=new f(e,t)}var d={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var D=Object.prototype;var b=D.hasOwnProperty;var y=D.toString;function has(e,t){return b.call(e,t)}var k=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var T=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(k(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(k(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new T(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var C=1,R=2,x=C|R,F=4,O=8,w=16,M=32,N=64,I=128;function functionFlags(e,t){return R|(e?F:0)|(t?O:0)}var P=0,L=1,B=2,V=3,U=4,z=5;var K=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){for(var o=e.ecmaVersion;;o--){if(a=t[o]){break}}if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var s=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(s);this.reservedWordsStrictBind=wordsRegexp(s+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=d.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null};var G={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};K.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};G.inFunction.get=function(){return(this.currentVarScope().flags&R)>0};G.inGenerator.get=function(){return(this.currentVarScope().flags&O)>0};G.inAsync.get=function(){return(this.currentVarScope().flags&F)>0};G.allowSuper.get=function(){return(this.currentThisScope().flags&N)>0};G.allowDirectSuper.get=function(){return(this.currentThisScope().flags&I)>0};G.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};K.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&R)>0};K.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};X.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};X.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case d._class:if(e){this.unexpected()}return this.parseClass(r,true);case d._if:return this.parseIfStatement(r);case d._return:return this.parseReturnStatement(r);case d._switch:return this.parseSwitchStatement(r);case d._throw:return this.parseThrowStatement(r);case d._try:return this.parseTryStatement(r);case d._const:case d._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case d._while:return this.parseWhileStatement(r);case d._with:return this.parseWithStatement(r);case d.braceL:return this.parseBlock(true,r);case d.semi:return this.parseEmptyStatement(r);case d._export:case d._import:if(this.options.ecmaVersion>10&&i===d._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return i===d._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var c=this.value,l=this.parseExpression();if(i===d.name&&l.type==="Identifier"&&this.eat(d.colon)){return this.parseLabeledStatement(r,c,l,e)}else{return this.parseExpressionStatement(r,l)}}};W.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==d.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(d.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};W.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(q);this.enterScope(0);this.expect(d.parenL);if(this.type===d.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===d._var||this.type===d._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=new DestructuringErrors;var o=this.parseExpression(true,a);if(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(o,false,a);this.checkLVal(o);return this.parseForIn(e,o)}else{this.checkExpressionErrors(a,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,o)};W.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,$|(n?0:Z),false,t)};W.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(d._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};W.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};W.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(d.braceL);this.labels.push(Y);this.enterScope(0);var t;for(var n=false;this.type!==d.braceR;){if(this.type===d._case||this.type===d._default){var i=this.type===d._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(d.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};W.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var j=[];W.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===d._catch){var t=this.startNode();this.next();if(this.eat(d.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?M:0);this.checkLVal(t.param,n?U:B);this.expect(d.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(d._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};W.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};W.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(q);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};W.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};W.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};W.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var c=this.labels[u];if(c.statementStart===e.start){c.statementStart=this.start;c.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};W.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};W.parseBlock=function(e,t){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(d.braceL);if(e){this.enterScope(0)}while(!this.eat(d.braceR)){var n=this.parseStatement(null);t.body.push(n)}if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};W.parseFor=function(e,t){e.init=t;this.expect(d.semi);e.test=this.type===d.semi?null:this.parseExpression();this.expect(d.semi);e.update=this.type===d.parenR?null:this.parseExpression();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};W.parseForIn=function(e,t){var n=this.type===d._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(t.type==="AssignmentPattern"){this.raise(t.start,"Invalid left-hand side in for-loop")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};W.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(d.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===d._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(d.comma)){break}}return e};W.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLVal(e.id,t==="var"?L:B,false)};var $=1,Z=2,Q=4;W.parseFunction=function(e,t,n,i){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===d.star&&t&Z){this.unexpected()}e.generator=this.eat(d.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&$){e.id=t&Q&&this.type!==d.name?null:this.parseIdent();if(e.id&&!(t&Z)){this.checkLVal(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?L:B:V)}}var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&$)){e.id=this.type===d.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,t&$?"FunctionDeclaration":"FunctionExpression")};W.parseFunctionParams=function(e){this.expect(d.parenL);e.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};W.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.startNode();var r=false;i.body=[];this.expect(d.braceL);while(!this.eat(d.braceR)){var a=this.parseClassElement(e.superClass!==null);if(a){i.body.push(a);if(a.type==="MethodDefinition"&&a.kind==="constructor"){if(r){this.raise(a.start,"Duplicate constructor in the same class")}r=true}}}e.body=this.finishNode(i,"ClassBody");this.strict=n;return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};W.parseClassElement=function(e){var t=this;if(this.eat(d.semi)){return null}var n=this.startNode();var i=function(e,i){if(i===void 0)i=false;var r=t.start,a=t.startLoc;if(!t.eatContextual(e)){return false}if(t.type!==d.parenL&&(!i||!t.canInsertSemicolon())){return true}if(n.key){t.unexpected()}n.computed=false;n.key=t.startNodeAt(r,a);n.key.name=e;t.finishNode(n.key,"Identifier");return false};n.kind="method";n.static=i("static");var r=this.eat(d.star);var a=false;if(!r){if(this.options.ecmaVersion>=8&&i("async",true)){a=true;r=this.options.ecmaVersion>=9&&this.eat(d.star)}else if(i("get")){n.kind="get"}else if(i("set")){n.kind="set"}}if(!n.key){this.parsePropertyName(n)}var o=n.key;var s=false;if(!n.computed&&!n.static&&(o.type==="Identifier"&&o.name==="constructor"||o.type==="Literal"&&o.value==="constructor")){if(n.kind!=="method"){this.raise(o.start,"Constructor can't have get/set modifier")}if(r){this.raise(o.start,"Constructor can't be a generator")}if(a){this.raise(o.start,"Constructor can't be an async method")}n.kind="constructor";s=e}else if(n.static&&o.type==="Identifier"&&o.name==="prototype"){this.raise(o.start,"Classes may not have a static property named prototype")}this.parseClassMethod(n,r,a,s);if(n.kind==="get"&&n.value.params.length!==0){this.raiseRecoverable(n.value.start,"getter should have no params")}if(n.kind==="set"&&n.value.params.length!==1){this.raiseRecoverable(n.value.start,"setter should have exactly one param")}if(n.kind==="set"&&n.value.params[0].type==="RestElement"){this.raiseRecoverable(n.value.params[0].start,"Setter cannot use rest params")}return n};W.parseClassMethod=function(e,t,n,i){e.value=this.parseMethod(t,n,i);return this.finishNode(e,"MethodDefinition")};W.parseClassId=function(e,t){if(this.type===d.name){e.id=this.parseIdent();if(t){this.checkLVal(e.id,B,false)}}else{if(t===true){this.unexpected()}e.id=null}};W.parseClassSuper=function(e){e.superClass=this.eat(d._extends)?this.parseExprSubscripts():null};W.parseExport=function(e,t){this.next();if(this.eat(d.star)){this.expectContextual("from");if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(d._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===d._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,$|Q,false,n)}else if(this.type===d._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!a&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(d._function)){return this.parseFunction(this.startNodeAt(i,r),0,false,true)}if(n&&!this.canInsertSemicolon()){if(this.eat(d.arrow)){return this.parseArrowExpression(this.startNodeAt(i,r),[o],false)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===d.name&&!a){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(d.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(i,r),[o],true)}}return o;case d.regexp:var s=this.value;t=this.parseLiteral(s.value);t.regex={pattern:s.pattern,flags:s.flags};return t;case d.num:case d.string:return this.parseLiteral(this.value);case d._null:case d._true:case d._false:t=this.startNode();t.value=this.type===d._null?null:this.type===d._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case d.parenL:var u=this.start,c=this.parseParenAndDistinguishExpression(n);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=u}if(e.parenthesizedBind<0){e.parenthesizedBind=u}}return c;case d.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(d.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case d.braceL:return this.parseObj(false,e);case d._function:t=this.startNode();this.next();return this.parseFunction(t,0);case d._class:return this.parseClass(this.startNode(),false);case d._new:return this.parseNew();case d.backQuote:return this.parseTemplate();case d._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ee.parseExprImport=function(){var e=this.startNode();this.next();switch(this.type){case d.parenL:return this.parseDynamicImport(e);default:this.unexpected()}};ee.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(d.parenR)){var t=this.start;if(this.eat(d.comma)&&this.eat(d.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ee.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1)}this.next();return this.finishNode(t,"Literal")};ee.parseParenExpression=function(){this.expect(d.parenL);var e=this.parseExpression();this.expect(d.parenR);return e};ee.parseParenAndDistinguishExpression=function(e){var t=this.start,n=this.startLoc,i,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc;var s=[],u=true,c=false;var l=new DestructuringErrors,f=this.yieldPos,p=this.awaitPos,_;this.yieldPos=0;this.awaitPos=0;while(this.type!==d.parenR){u?u=false:this.expect(d.comma);if(r&&this.afterTrailingComma(d.parenR,true)){c=true;break}else if(this.type===d.ellipsis){_=this.start;s.push(this.parseParenItem(this.parseRestBinding()));if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{s.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var h=this.start,m=this.startLoc;this.expect(d.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(d.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=f;this.awaitPos=p;return this.parseParenArrowList(t,n,s)}if(!s.length||c){this.unexpected(this.lastTokStart)}if(_){this.unexpected(_)}this.checkExpressionErrors(l,true);this.yieldPos=f||this.yieldPos;this.awaitPos=p||this.awaitPos;if(s.length>1){i=this.startNodeAt(a,o);i.expressions=s;this.finishNodeAt(i,"SequenceExpression",h,m)}else{i=s[0]}}else{i=this.parseParenExpression()}if(this.options.preserveParens){var E=this.startNodeAt(t,n);E.expression=i;return this.finishNode(E,"ParenthesizedExpression")}else{return i}};ee.parseParenItem=function(e){return e};ee.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var te=[];ee.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(d.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"||n){this.raiseRecoverable(e.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(e.start,"new.target can only be used in functions")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===d._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(d.parenL)){e.arguments=this.parseExprList(d.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=te}return this.finishNode(e,"NewExpression")};ee.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===d.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===d.backQuote;return this.finishNode(n,"TemplateElement")};ee.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===d.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(d.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(d.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};ee.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===d.name||this.type===d.num||this.type===d.string||this.type===d.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===d.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};ee.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(d.braceR)){if(!i){this.expect(d.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(d.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};ee.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(d.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===d.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===d.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(d.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(d.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};ee.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===d.colon){this.unexpected()}if(this.eat(d.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===d.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==d.comma&&this.type!==d.braceR)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var c=e.value.start;if(e.kind==="get"){this.raiseRecoverable(c,"getter should have no params")}else{this.raiseRecoverable(c,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,e.key)}else if(this.type===d.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,e.key)}else{e.value=e.key}e.shorthand=true}else{this.unexpected()}};ee.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(d.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(d.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===d.num||this.type===d.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ee.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ee.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|N|(n?I:0));this.expect(d.parenL);i.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};ee.parseArrowExpression=function(e,t,n){var i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|w);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=i;this.awaitPos=r;this.awaitIdentPos=a;return this.finishNode(e,"ArrowFunctionExpression")};ee.parseFunctionBody=function(e,t,n){var i=t&&this.type!==d.braceL;var r=this.strict,a=false;if(i){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||o){a=this.strictDirective(this.end);if(a&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var s=this.labels;this.labels=[];if(a){this.strict=true}this.checkParams(e,!r&&!a&&!t&&!n&&this.isSimpleParamList(e.params));e.body=this.parseBlock(false);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=s}this.exitScope();if(this.strict&&e.id){this.checkLVal(e.id,z)}this.strict=r};ee.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===U){var a=this.currentScope();a.lexical.push(e)}else if(t===V){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&M&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&x){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};ie.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};ie.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ie.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x){return t}}};ie.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x&&!(t.flags&w)){return t}}};var ae=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var oe=K.prototype;oe.startNode=function(){return new ae(this,this.start,this.startLoc)};oe.startNodeAt=function(e,t){return new ae(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}oe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};oe.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};var se=function TokContext(e,t,n,i,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!n;this.override=i;this.generator=!!r};var ue={b_stat:new se("{",false),b_expr:new se("{",true),b_tmpl:new se("${",false),p_stat:new se("(",false),p_expr:new se("(",true),q_tmpl:new se("`",true,true,function(e){return e.tryReadTemplateToken()}),f_stat:new se("function",false),f_expr:new se("function",true),f_expr_gen:new se("function",true,false,null,true),f_gen:new se("function",false,false,null,true)};var ce=K.prototype;ce.initialContext=function(){return[ue.b_stat]};ce.braceIsBlock=function(e){var t=this.curContext();if(t===ue.f_expr||t===ue.f_stat){return true}if(e===d.colon&&(t===ue.b_stat||t===ue.b_expr)){return!t.isExpr}if(e===d._return||e===d.name&&this.exprAllowed){return m.test(this.input.slice(this.lastTokEnd,this.start))}if(e===d._else||e===d.semi||e===d.eof||e===d.parenR||e===d.arrow){return true}if(e===d.braceL){return t===ue.b_stat}if(e===d._var||e===d._const||e===d.name){return false}return!this.exprAllowed};ce.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};ce.updateContext=function(e){var t,n=this.type;if(n.keyword&&e===d.dot){this.exprAllowed=false}else if(t=n.updateContext){t.call(this,e)}else{this.exprAllowed=n.beforeExpr}};d.parenR.updateContext=d.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===ue.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};d.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?ue.b_stat:ue.b_expr);this.exprAllowed=true};d.dollarBraceL.updateContext=function(){this.context.push(ue.b_tmpl);this.exprAllowed=true};d.parenL.updateContext=function(e){var t=e===d._if||e===d._for||e===d._with||e===d._while;this.context.push(t?ue.p_stat:ue.p_expr);this.exprAllowed=true};d.incDec.updateContext=function(){};d._function.updateContext=d._class.updateContext=function(e){if(e.beforeExpr&&e!==d.semi&&e!==d._else&&!(e===d._return&&m.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===d.colon||e===d.braceL)&&this.curContext()===ue.b_stat)){this.context.push(ue.f_expr)}else{this.context.push(ue.f_stat)}this.exprAllowed=false};d.backQuote.updateContext=function(){if(this.curContext()===ue.q_tmpl){this.context.pop()}else{this.context.push(ue.q_tmpl)}this.exprAllowed=false};d.star.updateContext=function(e){if(e===d._function){var t=this.context.length-1;if(this.context[t]===ue.f_expr){this.context[t]=ue.f_expr_gen}else{this.context[t]=ue.f_gen}}this.exprAllowed=true};d.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==d.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var le="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var fe=le+" Extended_Pictographic";var pe=fe;var _e={9:le,10:fe,11:pe};var he="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var de="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 me=de+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var Ee=me+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ge={9:de,10:me,11:Ee};var ve={};function buildUnicodeData(e){var t=ve[e]={binary:wordsRegexp(_e[e]+" "+he),nonBinary:{General_Category:wordsRegexp(he),Script:wordsRegexp(ge[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var De=K.prototype;var be=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=ve[e.options.ecmaVersion>=11?11:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};be.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};be.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};be.prototype.at=function at(e){var t=this.source;var n=t.length;if(e>=n){return-1}var i=t.charCodeAt(e);if(!this.switchU||i<=55295||i>=57344||e+1>=n){return i}var r=t.charCodeAt(e+1);return r>=56320&&r<=57343?(i<<10)+r-56613888:i};be.prototype.nextIndex=function nextIndex(e){var t=this.source;var n=t.length;if(e>=n){return n}var i=t.charCodeAt(e),r;if(!this.switchU||i<=55295||i>=57344||e+1>=n||(r=t.charCodeAt(e+1))<56320||r>57343){return e+1}return e+2};be.prototype.current=function current(){return this.at(this.pos)};be.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};be.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};be.prototype.eat=function eat(e){if(this.current()===e){this.advance();return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}De.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};De.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};De.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};De.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};De.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};De.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};De.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};De.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};De.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}De.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};De.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};De.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};De.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};De.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};De.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=e.current();e.advance();if(n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e)){n=e.lastIntValue}if(isRegExpIdentifierStart(n)){e.lastIntValue=n;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}De.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=e.current();e.advance();if(n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e)){n=e.lastIntValue}if(isRegExpIdentifierPart(n)){e.lastIntValue=n;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}De.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};De.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};De.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};De.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};De.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};De.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};De.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};De.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}De.regexp_eatRegExpUnicodeEscapeSequence=function(e){var t=e.pos;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var n=e.lastIntValue;if(e.switchU&&n>=55296&&n<=56319){var i=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(r>=56320&&r<=57343){e.lastIntValue=(n-55296)*1024+(r-56320)+65536;return true}}e.pos=i;e.lastIntValue=n}return true}if(e.switchU&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(e.switchU){e.raise("Invalid unicode escape")}e.pos=t}return false};function isValidUnicode(e){return e>=0&&e<=1114111}De.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};De.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};De.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}De.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};De.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};De.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};De.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}De.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}De.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};De.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};De.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};De.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};De.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};De.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};De.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};De.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}De.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}De.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};De.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}De.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(d.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};ke.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};ke.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344){return e}var t=this.input.charCodeAt(this.pos+1);return(e<<10)+t-56613888};ke.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};ke.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};ke.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(d.ellipsis)}else{++this.pos;return this.finishToken(d.dot)}};ke.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.slash,1)};ke.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?d.star:d.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=d.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(d.assign,n+1)}return this.finishOp(i,n)};ke.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){return this.finishOp(e===124?d.logicalOR:d.logicalAND,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(e===124?d.bitwiseOR:d.bitwiseAND,1)};ke.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.bitwiseXOR,1)};ke.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(d.incDec,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(d.plusMin,1)};ke.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(d.assign,n+1)}return this.finishOp(d.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(d.relational,n)};ke.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(d.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(d.arrow)}return this.finishOp(e===61?d.eq:d.prefix,1)};ke.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(d.parenL);case 41:++this.pos;return this.finishToken(d.parenR);case 59:++this.pos;return this.finishToken(d.semi);case 44:++this.pos;return this.finishToken(d.comma);case 91:++this.pos;return this.finishToken(d.bracketL);case 93:++this.pos;return this.finishToken(d.bracketR);case 123:++this.pos;return this.finishToken(d.braceL);case 125:++this.pos;return this.finishToken(d.braceR);case 58:++this.pos;return this.finishToken(d.colon);case 63:++this.pos;return this.finishToken(d.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(d.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(d.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};ke.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};ke.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new be(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(d.regexp,{pattern:r,flags:o,value:u})};ke.readInt=function(e,t){var n=this.pos,i=0;for(var r=0,a=t==null?Infinity:t;r=97){s=o-97+10}else if(o>=65){s=o-65+10}else if(o>=48&&o<=57){s=o-48}else{s=Infinity}if(s>=e){break}++this.pos;i=i*e+s}if(this.pos===n||t!=null&&this.pos-n!==t){return null}return i};ke.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=typeof BigInt!=="undefined"?BigInt(this.input.slice(t,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,n)};ke.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=this.input.slice(t,this.pos);var a=typeof BigInt!=="undefined"?BigInt(r):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,a)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var o=this.input.slice(t,this.pos);var s=n?parseInt(o,8):parseFloat(o);return this.finishToken(d.num,s)};ke.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}ke.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else{if(isNewLine(i,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(d.string,t)};var Se={};ke.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Se){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};ke.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Se}else{this.raise(e,t)}};ke.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===d.template||this.type===d.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(d.dollarBraceL)}else{++this.pos;return this.finishToken(d.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(d.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};ke.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};ke.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};ke.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var i=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e})}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var o="";var s=true;var u="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var l="enum implements import interface package private protected public static super this "+c+" "+u;var f="return new delete throw else case yield await";u=makePredicate(u);l=makePredicate(l);f=makePredicate(f);c=makePredicate(c);var p=makePredicate(characters("+-*&%=<>!?|~^"));var _=/[0-9a-f]/i;var h=/^0x[0-9a-f]+$/i;var d=/^0[0-7]+$/;var m=/^0o[0-7]+$/i;var E=/^0b[01]+$/i;var g=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var v=/^(0[xob])?[0-9a-f]+n$/i;var D=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var b=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var y=makePredicate(characters("\n\r\u2028\u2029"));var k=makePredicate(characters(";]),:"));var S=makePredicate(characters("[{(,;:"));var T=makePredicate(characters("[]{}(),;:"));var A={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return A.ID_Start.test(e)}function is_identifier_char(e){return A.ID_Continue.test(e)}const C=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return C.test(e)}function is_identifier_string(e,t){if(C.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=A.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=A.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(h.test(e)){return parseInt(e.substr(2),16)}else if(d.test(e)){return parseInt(e.substr(1),8)}else if(m.test(e)){return parseInt(e.substr(2),8)}else if(E.test(e)){return parseInt(e.substr(2),2)}else if(g.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var R={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw R;if(y.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));o=r.text.slice(e,r.pos);a.quote=t;return a});var g=with_eof_error("Unterminated template",function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);o=n;s=false;return a}n+=i;if(i=="\\"){var u=r.pos;var c=m&&(m.type==="name"||m.type==="punc"&&(m.value===")"||m.value==="]"));i=read_escaped_char(true,!c,true);n+=r.text.substr(u,r.pos-u)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);o=n;s=true;return a});function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var k=with_eof_error("Unterminated multiline comment",function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token});var A=with_eof_error("Unterminated identifier name",function(){var e=[],t,n=false;var i=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=i();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=i();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(l.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r});var C=with_eof_error("Unterminated regular expression",function(e){var t=false,n,i=false;while(n=next(true))if(y.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=A();return token("regexp","/"+e+"/"+r)});function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(D.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return k()}return r.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=A();if(a)return token("name",e);return c.has(e)?token("atom",e):!u.has(e)?token("name",e):D.has(e)?token("operator",e):token("keyword",e)}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===R)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(T.has(t))return token("punc",next());if(p.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var x=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var F=makePredicate(["--","++"]);var O=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var w=makePredicate(["??=","&&=","||="]);var M=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var N=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every(e=>!e.nlb)}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=S(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens(function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!o.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var s=i.in_directives,l=simple_statement();return s&&l.body instanceof Bt?new G(l.body):l;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return u(fe,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var _=import_();semicolon();return _}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new W({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new q;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(be);case"continue":next();return break_cont(ye);case"debugger":next();semicolon();return new K;case"do":next();var h=in_loop(statement);expect_token("keyword","while");var d=parenthesised();semicolon(true);return new Q({body:h,condition:d});case"while":next();return new J({condition:parenthesised(),body:in_loop(function(){return statement(false,true)})});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(ft);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return u(fe,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var m=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){m=S(true);semicolon()}return new ge({value:m});case"switch":next();return new Ae({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var m=S(true);semicolon();return new ve({value:m});case"try":next();return try_();case"var":next();var _=c();semicolon();return _;case"let":next();var _=f();semicolon();return _;case"const":next();var _=p();semicolon();return _;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ie({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var _=export_();if(is("punc",";"))semicolon();return _}}}unexpected()});function labeled_statement(){var e=as_symbol(Ft);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some(t=>t.name===e.name)){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof $)){e.references.forEach(function(t){if(t instanceof ye){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}})}return new j({body:t,label:e})}function simple_statement(e){return new X({body:(e=S(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Nt,true)}if(t!=null){n=i.labels.find(e=>e.name===t.name);if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!is_in_async()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),c(true)):is("keyword","let")?(next(),f(true)):is("keyword","const")?(next(),p(true)):S(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Me){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof pe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:S(true);expect(";");var n=is("punc",")")?null:S(true);expect(")");return new ee({init:e,condition:t,step:n,body:in_loop(function(){return r(false,true)})})}function for_of(e,t){var n=e instanceof Me?e.definitions[0].name:null;var i=S(true);expect(")");return new ne({await:t,init:e,name:n,object:i,body:in_loop(function(){return r(false,true)})})}function for_in(e){var t=S(true);expect(")");return new te({init:e,object:t,body:in_loop(function(){return r(false,true)})})}var a=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new le({start:e,end:a,async:n,argnames:t,body:r})};var u=function(e,t,n,i){var r=e===fe;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?bt:St):null;if(r&&!o){if(i){e=ce}else{unexpected()}}if(o&&e!==ue&&!(o instanceof dt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(l.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof oe){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new tt({start:n.start,left:n,operator:"=",right:S(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new oe({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?Dt:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Wt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:S(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new oe({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new pe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var c=as_symbol(t);if(a){n.push(new oe({start:o,expression:c,end:c.end}))}else{n.push(new at({start:u,key:c.name,value:c,end:c.end}))}}else if(is("punc","}")){continue}else{var l=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new at({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new at({start:l,quote:l.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:S(false),end:i.token})}}expect("}");e.check_strict();return new pe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new oe({start:prev(),expression:S(),end:i.token}))}else{o.push(S())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var c=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var l=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var l=[new ge({start:i.token,value:S(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=c;return l}function _await_expression(){if(!is_in_async()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new ke({start:prev(),end:i.token,expression:v(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&k.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Se({start:e,is_star:t,expression:n?S():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Te({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),a),expression:S(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new Re({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Ct);expect(")")}t=new Oe({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new we({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Fe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?mt:t==="const"?gt:t==="let"?vt:null;if(is("punc","{")||is("punc","[")){r=new Le({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),S(false,e)):null,end:prev()})}else{r=new Le({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),S(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var c=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var f=function(e){return new Ie({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var p=function(e){return new Pe({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var _=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return g(new ht({start:t,end:prev()}),e)}var n=h(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Ge({start:t,expression:n,args:r,end:prev()});annotate(a);return g(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Ot);break;case"num":t=new Vt({start:e,end:e,value:e.value,raw:o});break;case"big_int":t=new Ut({start:e,end:e,value:e.value});break;case"string":t=new Bt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new zt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new jt({start:e,end:e});break;case"true":t=new $t({start:e,end:e});break;case"null":t=new Gt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var n=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof it){return n(new pe({start:e.start,end:e.end,is_array:false,names:e.properties.map(e=>to_fun_args(e))}),t)}else if(e instanceof at){e.value=to_fun_args(e.value);return n(e,t)}else if(e instanceof Wt){return e}else if(e instanceof pe){e.names=e.names.map(e=>to_fun_args(e));return n(e,t)}else if(e instanceof Ot){return n(new Dt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof oe){e.expression=to_fun_args(e.expression);return n(e,t)}else if(e instanceof nt){return n(new pe({start:e.start,end:e.end,is_array:true,names:e.elements.map(e=>to_fun_args(e))}),t)}else if(e instanceof et){return n(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var h=function(e,t){if(is("operator","new")){return _(e)}if(is("operator","import")){return import_meta()}var r=i.token;var o;var s=is("name","async")&&(o=peek()).value!="["&&o.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(s&&!e)break;var c=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return a(r,c.map(e=>to_fun_args(e)),!!s)}var l=s?new Ke({expression:s,args:c}):c.length==1?c[0]:new Xe({expressions:c});if(l.start){const e=r.comments_before.length;n.set(r,e);l.start.comments_before.unshift(...r.comments_before);r.comments_before=l.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=l.start.comments_after}l.start=r;var p=prev();if(l.end){p.comments_before=l.end.comments_before;l.end.comments_after.push(...p.comments_after);p.comments_after=l.end.comments_after}l.end=p;if(l instanceof Ke)annotate(l);return g(l,e);case"[":return g(d(),e);case"{":return g(E(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var h=new Dt({name:i.token.value,start:r,end:r});next();return a(r,[h],!!s)}if(is("keyword","function")){next();var m=u(ce,false,!!s);m.start=r;m.end=prev();return g(m,e)}if(s)return g(s,e);if(is("keyword","class")){next();var v=class_(pt);v.start=r;v.end=prev();return g(v,e)}if(is("template_head")){return g(template_string(),e)}if(N.has(i.token.type)){return g(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new de({start:i.token,raw:o,value:i.token.value,end:i.token}));while(!s){next();handle_regexp();e.push(S(true));e.push(new de({start:i.token,raw:o,value:i.token.value,end:i.token}))}next();return new he({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Wt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new oe({start:prev(),expression:S(),end:i.token}))}else{a.push(S(false))}}next();return a}var d=embed_tokens(function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})});var m=embed_tokens((e,t)=>{return u(ue,e,t)});var E=embed_tokens(function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new oe({start:e,expression:S(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Ot({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=S(false)}if(is("operator","=")){next();o=new et({start:e,left:o,operator:"=",right:S(false),logical:false,end:prev()})}r.push(new at({start:e,quote:e.quote,key:a instanceof U?a:""+a,value:o,end:prev()}))}next();return new it({properties:r})});function class_(e){var t,n,r,a,o=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){r=as_symbol(e===ft?Tt:At)}if(e===ft&&!r){unexpected()}if(i.token.value=="extends"){next();a=S(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){t=i.token;n=concise_method_or_getset(as_property_name(),t,true);if(!n){unexpected()}o.push(n);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:t,name:r,extends:a,properties:o,end:prev()})}function concise_method_or_getset(e,t,n){var r=function(e,t){if(typeof e==="string"||typeof e==="number"){return new yt({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const a=e=>{if(typeof e==="string"||typeof e==="number"){return new kt({start:c,end:c,name:""+e})}else if(e===null){unexpected()}return e};var o=false;var s=false;var u=false;var c=t;if(n&&e==="static"&&!is("punc","(")){s=true;c=i.token;e=as_property_name()}if(e==="async"&&!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=")){o=true;c=i.token;e=as_property_name()}if(e===null){u=true;c=i.token;e=as_property_name();if(e===null){unexpected()}}if(is("punc","(")){e=r(e,t);var l=new ut({start:t,static:s,is_generator:u,async:o,key:e,quote:e instanceof yt?c.quote:undefined,value:m(u,o),end:prev()});return l}const f=i.token;if(e=="get"){if(!is("punc")||is("punc","[")){e=r(as_property_name(),t);return new st({start:t,static:s,key:e,quote:e instanceof yt?f.quote:undefined,value:m(),end:prev()})}}else if(e=="set"){if(!is("punc")||is("punc","[")){e=r(as_property_name(),t);return new ot({start:t,static:s,key:e,quote:e instanceof yt?f.quote:undefined,value:m(),end:prev()})}}if(n){const n=a(e);const i=n instanceof kt?c.quote:undefined;if(is("operator","=")){next();return new lt({start:t,static:s,quote:i,key:n,value:S(false),end:prev()})}else if(is("name")||is("punc",";")||is("punc","}")){return new lt({start:t,static:s,quote:i,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Rt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Ve({start:e,imported_name:t,imported_names:n,module_name:new Bt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return g(new Ue({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?xt:Mt;var n=e?Rt:wt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Be({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?xt:Mt;var r=e?Rt:wt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Be({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Rt:Mt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new ze({start:e,is_default:t,exported_names:n,module_name:new Bt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new ze({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=S(false);semicolon()}else if((o=r(t))instanceof Me&&t){unexpected(o.start)}else if(o instanceof Me||o instanceof se||o instanceof ft){u=o}else if(o instanceof X){s=o.body}else{unexpected(o.start)}return new ze({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=S(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?It:t=="super"?Pt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof dt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,Qt);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,Jt);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,en);break}}}}var g=function(e,t,n){var i=e.start;if(is("punc",".")){next();return g(new We({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=S(true);expect("]");return g(new qe({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new Ke({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return g(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new Ke({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=g(t,true,true)}else if(is("name")){n=g(new We({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=S(true);expect("]");n=g(new qe({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return g(new _e({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new oe({start:prev(),expression:S(false),end:prev()}))}else{e.push(S(false))}if(!is("punc",")")){expect(",")}}next();return e}var v=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"){if(is_in_async()){next();return _await_expression()}else if(i.input.has_directive("use strict")){token_error(i.token,"Unexpected await identifier inside strict mode")}}if(is("operator")&&x.has(n.value)){next();handle_regexp();var r=make_unary($e,n,v(e));r.start=n;r.end=prev();return r}var a=h(e,t);while(is("operator")&&F.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof le)unexpected();a=make_unary(Ze,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Ot&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var D=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?M[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=D(v(true),a,n);return D(new Qe({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return D(v(true,true),0,e)}var b=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=S(false);expect(":");return new Je({start:t,condition:n,consequent:r,alternative:S(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof Ot}function to_destructuring(e){if(e instanceof it){e=new pe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const I=(e,t)=>Boolean(e.flags&t);const P=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const L=1;const B=2;const V=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return I(this,L)}set nlb(e){P(this,L,e)}get quote(){return!I(this,V)?"":I(this,B)?"'":'"'}set quote(e){P(this,B,e==="'");P(this,V,!!e)}}var U=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer(function(e){if(e!==t){return e.clone(true)}}))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var z=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var K=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},z);var G=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},z);var X=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,function(){this.body._walk(e)})},_children_backwards(e){e(this.body)}},z);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",functions:"[Map/S] like `variables`, but only lists function declarations",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.functions)n.functions=new Map(this.functions);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var ae=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer(function(e){if(e instanceof G&&e.value=="$ORIG"){return i.splice(t)}}));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer(function(e){if(e instanceof G&&e.value=="$ORIG"){return i.splice(n)}}))}},re);var oe=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,function(){this.expression.walk(e)})},_children_backwards(e){e(this.expression)}});var se=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},se);var fe=DEFNODE("Defun",null,{$documentation:"A function definition"},se);var pe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,function(){this.names.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker(function(t){if(t instanceof _t){e.push(t)}}));return e}});var _e=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,function(){this.prefix._walk(e);this.template_string._walk(e)})},_children_backwards(e){e(this.template_string);e(this.prefix)}});var he=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,function(){this.segments.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var me=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},z);var Ee=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},me);var ge=DEFNODE("Return",null,{$documentation:"A `return` statement"},Ee);var ve=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},Ee);var De=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},me);var be=DEFNODE("Break",null,{$documentation:"A `break` statement"},De);var ye=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},De);var ke=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})},_children_backwards(e){e(this.expression)}});var Se=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Te=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)})},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},Y);var Ae=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var Ce=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var Re=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Ce);var xe=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Ce);var Fe=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)})},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var Oe=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,function(){if(this.argname)this.argname._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var we=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var Me=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e))})},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},re);var lt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,function(){if(this.key instanceof U)this.key._walk(e);if(this.value instanceof U)this.value._walk(e)})},_children_backwards(e){if(this.value instanceof U)e(this.value);if(this.key instanceof U)e(this.key)},computed_key(){return!(this.key instanceof kt)}},rt);var ft=DEFNODE("DefClass",null,{$documentation:"A class definition"},ct);var pt=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},ct);var _t=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var ht=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var dt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},_t);var mt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},dt);var Et=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},dt);var gt=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},Et);var vt=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},Et);var Dt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},mt);var bt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},dt);var yt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},_t);var kt=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},_t);var St=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},dt);var Tt=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},Et);var At=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},dt);var Ct=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},Et);var Rt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},Et);var xt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},_t);var Ft=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},_t);var Ot=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},_t);var wt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Ot);var Mt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},_t);var Nt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},_t);var It=DEFNODE("This",null,{$documentation:"The `this` symbol"},_t);var Pt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},It);var Lt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Bt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Lt);var Vt=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Lt);var Ut=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Lt);var zt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Lt);var Kt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Lt);var Gt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Kt);var Xt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Kt);var Ht=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Kt);var Wt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Kt);var qt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Kt);var Yt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Kt);var jt=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Yt);var $t=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Yt);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===Zt)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===Zt)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const Zt=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof se){this.directives=Object.create(this.directives)}else if(e instanceof G&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof ct){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof se||e instanceof ct){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof re&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof j&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof $||e instanceof be&&i instanceof Ae)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const Qt=1;const Jt=2;const en=4;var tn=Object.freeze({__proto__:null,AST_Accessor:ue,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:Kt,AST_Await:ke,AST_BigInt:Ut,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:W,AST_Boolean:Yt,AST_Break:be,AST_Call:Ke,AST_Case:xe,AST_Catch:Oe,AST_Chain:Ye,AST_Class:ct,AST_ClassExpression:pt,AST_ClassProperty:lt,AST_ConciseMethod:ut,AST_Conditional:Je,AST_Const:Pe,AST_Constant:Lt,AST_Continue:ye,AST_Debugger:K,AST_Default:Re,AST_DefaultAssign:tt,AST_DefClass:ft,AST_Definitions:Me,AST_Defun:fe,AST_Destructuring:pe,AST_Directive:G,AST_Do:Q,AST_Dot:We,AST_DWLoop:Z,AST_EmptyStatement:q,AST_Exit:Ee,AST_Expansion:oe,AST_Export:ze,AST_False:jt,AST_Finally:we,AST_For:ee,AST_ForIn:te,AST_ForOf:ne,AST_Function:ce,AST_Hole:Wt,AST_If:Te,AST_Import:Ve,AST_ImportMeta:Ue,AST_Infinity:qt,AST_IterationStatement:$,AST_Jump:me,AST_Label:Ft,AST_LabeledStatement:j,AST_LabelRef:Nt,AST_Lambda:se,AST_Let:Ie,AST_LoopControl:De,AST_NameMapping:Be,AST_NaN:Xt,AST_New:Ge,AST_NewTarget:ht,AST_Node:U,AST_Null:Gt,AST_Number:Vt,AST_Object:it,AST_ObjectGetter:st,AST_ObjectKeyVal:at,AST_ObjectProperty:rt,AST_ObjectSetter:ot,AST_PrefixedTemplateString:_e,AST_PropAccess:He,AST_RegExp:zt,AST_Return:ge,AST_Scope:re,AST_Sequence:Xe,AST_SimpleStatement:X,AST_Statement:z,AST_StatementWithBody:Y,AST_String:Bt,AST_Sub:qe,AST_Super:Pt,AST_Switch:Ae,AST_SwitchBranch:Ce,AST_Symbol:_t,AST_SymbolBlockDeclaration:Et,AST_SymbolCatch:Ct,AST_SymbolClass:At,AST_SymbolClassProperty:kt,AST_SymbolConst:gt,AST_SymbolDeclaration:dt,AST_SymbolDefClass:Tt,AST_SymbolDefun:bt,AST_SymbolExport:wt,AST_SymbolExportForeign:Mt,AST_SymbolFunarg:Dt,AST_SymbolImport:Rt,AST_SymbolImportForeign:xt,AST_SymbolLambda:St,AST_SymbolLet:vt,AST_SymbolMethod:yt,AST_SymbolRef:Ot,AST_SymbolVar:mt,AST_TemplateSegment:de,AST_TemplateString:he,AST_This:It,AST_Throw:ve,AST_Token:AST_Token,AST_Toplevel:ae,AST_True:$t,AST_Try:Fe,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:Ht,AST_Var:Ne,AST_VarDef:Le,AST_While:J,AST_With:ie,AST_Yield:Se,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:Zt,walk_body:walk_body,walk_parent:walk_parent,_INLINE:Jt,_NOINLINE:en,_PURE:Qt});function def_transform(e,t){e.DEFMETHOD("transform",function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i})}function do_list(e,t){return i(e,function(e){return e.transform(t,true)})}def_transform(U,noop);def_transform(j,function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)});def_transform(X,function(e,t){e.body=e.body.transform(t)});def_transform(H,function(e,t){e.body=do_list(e.body,t)});def_transform(Q,function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)});def_transform(J,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)});def_transform(ee,function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)});def_transform(te,function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)});def_transform(ie,function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)});def_transform(Ee,function(e,t){if(e.value)e.value=e.value.transform(t)});def_transform(De,function(e,t){if(e.label)e.label=e.label.transform(t)});def_transform(Te,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)});def_transform(Ae,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(xe,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Fe,function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)});def_transform(Oe,function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)});def_transform(Me,function(e,t){e.definitions=do_list(e.definitions,t)});def_transform(Le,function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)});def_transform(pe,function(e,t){e.names=do_list(e.names,t)});def_transform(se,function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof U){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}});def_transform(Ke,function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)});def_transform(Xe,function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Vt({value:0})]});def_transform(We,function(e,t){e.expression=e.expression.transform(t)});def_transform(qe,function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)});def_transform(Ye,function(e,t){e.expression=e.expression.transform(t)});def_transform(Se,function(e,t){if(e.expression)e.expression=e.expression.transform(t)});def_transform(ke,function(e,t){e.expression=e.expression.transform(t)});def_transform(je,function(e,t){e.expression=e.expression.transform(t)});def_transform(Qe,function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)});def_transform(Je,function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)});def_transform(nt,function(e,t){e.elements=do_list(e.elements,t)});def_transform(it,function(e,t){e.properties=do_list(e.properties,t)});def_transform(rt,function(e,t){if(e.key instanceof U){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)});def_transform(ct,function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)});def_transform(oe,function(e,t){e.expression=e.expression.transform(t)});def_transform(Be,function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)});def_transform(Ve,function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)});def_transform(ze,function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)});def_transform(he,function(e,t){e.segments=do_list(e.segments,t)});def_transform(_e,function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)});(function(){var e=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Fe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new we(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new yt({name:n.key})}else{n.key=from_moz(e.key)}return new ut(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new at(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new yt({name:n.key})}n.value=new ue(n.value);if(e.kind=="get")return new st(n);if(e.kind=="set")return new ot(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ut(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new yt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new st(t)}if(e.kind=="set"){return new ot(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ut(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new lt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map(function(e){return e===null?new Wt:from_moz(e)})})},ObjectExpression:function(e){return new it({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map(function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)})})},SequenceExpression:function(e){return new Xe({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:We)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?xe:Re)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Pe:e.kind==="let"?Ie:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach(function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:new xt({name:"*"}),name:from_moz(e.local)}))}});return new Ve({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_names:[new Be({name:new Mt({name:"*"}),foreign_name:new Mt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map(function(e){return new Be({foreign_name:from_moz(e.exported),name:from_moz(e.local)})}):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new zt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new zt(n)}if(t===null)return new Gt(n);switch(typeof t){case"string":n.value=t;return new Bt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Vt(n);case"boolean":return new(t?$t:jt)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new ht({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ue({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var t=n[n.length-2];return new(t.type=="LabeledStatement"?Ft:t.type=="VariableDeclarator"&&t.id===e?t.kind=="const"?gt:t.kind=="let"?vt:mt:/Import.*Specifier/.test(t.type)?t.local===e?Rt:xt:t.type=="ExportSpecifier"?t.local===e?wt:Mt:t.type=="FunctionExpression"?t.id===e?St:Dt:t.type=="FunctionDeclaration"?t.id===e?bt:Dt:t.type=="ArrowFunctionExpression"?t.params.includes(e)?Dt:Ot:t.type=="ClassExpression"?t.id===e?At:Ot:t.type=="Property"?t.key===e&&t.computed||t.value===e?Ot:yt:t.type=="FieldDefinition"?t.key===e&&t.computed||t.value===e?Ot:kt:t.type=="ClassDeclaration"?t.id===e?Tt:Ot:t.type=="MethodDefinition"?t.computed?Ot:yt:t.type=="CatchClause"?Ct:t.type=="BreakStatement"||t.type=="ContinueStatement"?Nt:Ot)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Ut({start:my_start_token(e),end:my_end_token(e),value:e.value})}};t.UpdateExpression=t.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};t.ClassDeclaration=t.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?ft:pt)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",q);map("BlockStatement",W,"body@body");map("IfStatement",Te,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",j,"label>label, body>body");map("BreakStatement",be,"label>label");map("ContinueStatement",ye,"label>label");map("WithStatement",ie,"object>expression, body>body");map("SwitchStatement",Ae,"discriminant>expression, cases@body");map("ReturnStatement",ge,"argument>value");map("ThrowStatement",ve,"argument>value");map("WhileStatement",J,"test>condition, body>body");map("DoWhileStatement",Q,"test>condition, body>body");map("ForStatement",ee,"init>init, test>condition, update>step, body>body");map("ForInStatement",te,"left>init, right>object, body>body");map("ForOfStatement",ne,"left>init, right>object, body>body, await=await");map("AwaitExpression",ke,"argument>expression");map("YieldExpression",Se,"argument>expression, delegate=is_star");map("DebuggerStatement",K);map("VariableDeclarator",Le,"id>name, init>value");map("CatchClause",Oe,"param>argname, body%body");map("ThisExpression",It);map("Super",Pt);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ge,"callee>expression, arguments@args");map("CallExpression",Ke,"callee>expression, optional=optional, arguments@args");def_to_moz(ae,function To_Moz_Program(e){return to_moz_scope("Program",e)});def_to_moz(oe,function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}});def_to_moz(_e,function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}});def_to_moz(he,function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value}));Yt.DEFMETHOD("to_mozilla_ast",Lt.prototype.to_mozilla_ast);Gt.DEFMETHOD("to_mozilla_ast",Lt.prototype.to_mozilla_ast);Wt.DEFMETHOD("to_mozilla_ast",function To_Moz_ArrayHole(){return null});H.DEFMETHOD("to_mozilla_ast",W.prototype.to_mozilla_ast);se.DEFMETHOD("to_mozilla_ast",ce.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(e,n,i){var r="function From_Moz_"+e+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+e+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(e);if(i)i.split(/\s*,\s*/).forEach(function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}});r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(tn,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);t[e]=r;def_to_moz(n,a)}var n=null;function from_moz(e){n.push(e);var i=e!=null?t[e.type](e):null;n.pop();return i}U.from_mozilla_ast=function(e){var t=n;n=[];var i=from_moz(e);n=t;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",function(e){return set_moz_loc(this,t(this,e))})}var i=null;function to_moz(e){if(i===null){i=[]}i.push(e);var t=e!=null?e.to_mozilla_ast(i[i.length-2]):null;i.pop();if(i.length===0){i=null}return t}function to_moz_in_destructuring(){var e=i.length;while(e--){if(i[e]instanceof pe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof X&&t.body[0].body instanceof Bt){n.unshift(to_moz(new q(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof z&&i.body===t)return true;if(i instanceof Xe&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof _e&&i.prefix===t||i instanceof We&&i.expression===t||i instanceof qe&&i.expression===t||i instanceof Je&&i.condition===t||i instanceof Qe&&i.left===t||i instanceof Ze&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof it)return true;if(e instanceof Xe)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof _e)return left_is_object(e.prefix);if(e instanceof We||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const nn=/^$|[;{][\s\n]*$/;const rn=10;const an=32;const on=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let c=new Set;var l=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"})}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}})}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e})};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n});function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=l(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=l(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var h=0;var d=false;var m=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var y=b?function(){b.forEach(function(t){try{e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,!t.name&&t.token.type=="name"?t.token.value:t.name)}catch(e){}});b=[]}:noop;var k=e.max_line_len?function(){if(a>e.max_line_len){if(h){var t=u.slice(0,h);var n=u.slice(h);if(b){var i=n.length-a;b.forEach(function(e){e.line++;e.col+=i})}u=t+"\n"+n;o++;s++;a=n.length}}if(h){h=0;y()}}:noop;var S=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(d&&n){d=false;if(n!=="\n"){print("\n");C()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){A()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||S.has(n)){u+=";";a++;s++}else{k();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){b.push({token:v,name:D,line:o,col:a});v=false;if(!h)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),c=r.length-1;o+=c;a+=r[0].length;if(c>0){k();a=r[c].length}g=t}var T=function(){print("*")};var A=e.beautify?function(){print(" ")}:function(){p=true};var C=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var R=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var x=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){k();h=u.length}:noop;var F=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");x();R(next_indent(),function(){t=e()});C();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");A()}function colon(){print(":");A()}var O=b?function(e,t){v=e;D=t}:noop;function get(){if(h){k()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===rn){return true}if(t!==an){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(on," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof Ee&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var c=new TreeWalker(function(e){var t=c.parent();if(t instanceof Ee||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof We&&t.expression===e||t instanceof Xe&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}});c.push(t);t.value.walk(c)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");C()}var l=e.preamble;if(l){print(l.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter(e=>!a.has(e));if(u.length==0)return;var f=has_nlb();u.forEach(function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");C();f=true}else if(t>0){A()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");C()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}});if(!f){if(r.nlb){print("\n");C()}else{A()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof z||o.every(e=>!/comment[134]/.test(e.type))))return;a.add(o);var s=u.length;o.filter(n,e).forEach(function(e,n){if(a.has(e))return;a.add(e);m=false;if(d){print("\n");C();d=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");C()}else if(n>0||!t){A()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}d=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}});if(u.length>s)E=s}var w=[];return{get:get,toString:get,indent:C,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:x,print:print,star:T,space:A,comma:comma,colon:colon,last:function(){return g},semicolon:F,force_semicolon:force_semicolon,to_utf8:l,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!nn.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:R,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:O,option:function(t){return e[t]},printed_comments:c,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){w.push(e)},pop_node:function(){return w.pop()},parent:function(e){return w[w.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}U.DEFMETHOD("print",function(e,t){var n=this,i=n._codegen;if(n instanceof re){e.active_scope=n}else if(!e.use_asm&&n instanceof G&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}});U.DEFMETHOD("_print",U.prototype.print);U.DEFMETHOD("print_to_string",function(e){var t=OutputStream(e);this.print(t);return t.get()});function PARENS(e,t){if(Array.isArray(e)){e.forEach(function(e){PARENS(e,t)})}else{e.DEFMETHOD("needs_parens",t)}}PARENS(U,return_false);PARENS(ce,function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof Ke&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof Ke&&t.args.includes(this)){return true}}return false});PARENS(le,function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof Ke&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this});PARENS(it,function(e){return!e.has_parens()&&first_in_statement(e)});PARENS(pt,first_in_statement);PARENS(je,function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof Ke&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"});PARENS(ke,function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof Ke&&t.expression===this||e.option("safari10")&&t instanceof $e});PARENS(Xe,function(e){var t=e.parent();return t instanceof Ke||t instanceof je||t instanceof Qe||t instanceof Le||t instanceof He||t instanceof nt||t instanceof rt||t instanceof Je||t instanceof le||t instanceof tt||t instanceof oe||t instanceof ne&&this===t.object||t instanceof Se||t instanceof ze});PARENS(Qe,function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=M[e];const r=M[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}});PARENS(Se,function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof Ke&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true});PARENS(He,function(e){var t=e.parent();if(t instanceof Ge&&t.expression===this){return walk(this,e=>{if(e instanceof re)return true;if(e instanceof Ke){return Zt}})}});PARENS(Ke,function(e){var t=e.parent(),n;if(t instanceof Ge&&t.expression===this||t instanceof ze&&t.is_default&&this.expression instanceof ce)return true;return this.expression instanceof ce&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t});PARENS(Ge,function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof Ke&&t.expression===this))return true});PARENS(Vt,function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}});PARENS(Ut,function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}});PARENS([et,Je],function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof Ke&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof pe&&this.left.is_array===false)return true});DEFPRINT(G,function(e,t){t.print_string(e.value,e.quote);t.semicolon()});DEFPRINT(oe,function(e,t){t.print("...");e.expression.print(t)});DEFPRINT(pe,function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach(function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Wt)t.comma()});t.print(e.is_array?"]":"}")});DEFPRINT(K,function(e,t){t.print("debugger");t.semicolon()});function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach(function(e,i){if(n.in_directive===true&&!(e instanceof G||e instanceof q||e instanceof X&&e.body instanceof Bt)){n.in_directive=false}if(!(e instanceof q)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof X&&e.body instanceof Bt){n.in_directive=false}});n.in_directive=false}Y.DEFMETHOD("_do_print_body",function(e){force_statement(this.body,e)});DEFPRINT(z,function(e,t){e.body.print(t);t.semicolon()});DEFPRINT(ae,function(e,t){display_body(e.body,true,t,true);t.print("")});DEFPRINT(j,function(e,t){e.label.print(t);t.colon();e.body.print(t)});DEFPRINT(X,function(e,t){e.body.print(t);t.semicolon()});function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),function(){t.append_comments(e,true)});t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block(function(){display_body(e.body,false,t,n)})}else print_braced_empty(e,t)}DEFPRINT(W,function(e,t){print_braced(e,t)});DEFPRINT(q,function(e,t){t.semicolon()});DEFPRINT(Q,function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.semicolon()});DEFPRINT(J,function(e,t){t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.space();e._do_print_body(t)});DEFPRINT(ee,function(e,t){t.print("for");t.space();t.with_parens(function(){if(e.init){if(e.init instanceof Me){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}});t.space();e._do_print_body(t)});DEFPRINT(te,function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens(function(){e.init.print(t);t.space();t.print(e instanceof ne?"of":"in");t.space();e.object.print(t)});t.space();e._do_print_body(t)});DEFPRINT(ie,function(e,t){t.print("with");t.space();t.with_parens(function(){e.expression.print(t)});t.space();e._do_print_body(t)});se.DEFMETHOD("_do_print",function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof _t){n.name.print(e)}else if(t&&n.name instanceof U){e.with_square(function(){n.name.print(e)})}e.with_parens(function(){n.argnames.forEach(function(t,n){if(n)e.comma();t.print(e)})});e.space();print_braced(n,e,true)});DEFPRINT(se,function(e,t){e._do_print(t)});DEFPRINT(_e,function(e,t){var n=e.prefix;var i=n instanceof se||n instanceof Qe||n instanceof Je||n instanceof Xe||n instanceof je||n instanceof We&&n.expression instanceof it;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)});DEFPRINT(he,function(e,t){var n=t.parent()instanceof _e;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof ge){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}});Ee.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()});DEFPRINT(ge,function(e,t){e._do_print(t,"return")});DEFPRINT(ve,function(e,t){e._do_print(t,"throw")});DEFPRINT(Se,function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}});DEFPRINT(ke,function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof Ke||n instanceof Ot||n instanceof He||n instanceof je||n instanceof Lt||n instanceof ke||n instanceof it);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")});De.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()});DEFPRINT(be,function(e,t){e._do_print(t,"break")});DEFPRINT(ye,function(e,t){e._do_print(t,"continue")});function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Q)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Te){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof Y){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Te,function(e,t){t.print("if");t.space();t.with_parens(function(){e.condition.print(t)});t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Te)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}});DEFPRINT(Ae,function(e,t){t.print("switch");t.space();t.with_parens(function(){e.expression.print(t)});t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block(function(){e.body.forEach(function(e,i){t.indent(true);e.print(t);if(i0)t.newline()})})});Ce.DEFMETHOD("_do_print_body",function(e){e.newline();this.body.forEach(function(t){e.indent();t.print(e);e.newline()})});DEFPRINT(Re,function(e,t){t.print("default:");e._do_print_body(t)});DEFPRINT(xe,function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)});DEFPRINT(Fe,function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}});DEFPRINT(Oe,function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens(function(){e.argname.print(t)})}t.space();print_braced(e,t)});DEFPRINT(we,function(e,t){t.print("finally");t.space();print_braced(e,t)});Me.DEFMETHOD("_do_print",function(e,t){e.print(t);e.space();this.definitions.forEach(function(t,n){if(n)e.comma();t.print(e)});var n=e.parent();var i=n instanceof ee||n instanceof te;var r=!i||n&&n.init!==this;if(r)e.semicolon()});DEFPRINT(Ie,function(e,t){e._do_print(t,"let")});DEFPRINT(Ne,function(e,t){e._do_print(t,"var")});DEFPRINT(Pe,function(e,t){e._do_print(t,"const")});DEFPRINT(Ve,function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach(function(n,i){t.space();n.print(t);if(i{if(e instanceof re)return true;if(e instanceof Qe&&e.operator=="in"){return Zt}})}e.print(t,i)}DEFPRINT(Le,function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof ee||n instanceof te;parenthesize_for_noin(e.value,t,i)}});DEFPRINT(Ke,function(e,t){e.expression.print(t);if(e instanceof Ge&&e.args.length===0)return;if(e.expression instanceof Ke||e.expression instanceof se){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens(function(){e.args.forEach(function(e,n){if(n)t.comma();e.print(t)})})});DEFPRINT(Ge,function(e,t){t.print("new");t.space();Ke.prototype._codegen(e,t)});Xe.DEFMETHOD("_do_print",function(e){this.expressions.forEach(function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)})});DEFPRINT(Xe,function(e,t){e._do_print(t)});DEFPRINT(We,function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=l.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Vt&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}});DEFPRINT(qe,function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")});DEFPRINT(Ye,function(e,t){e.expression.print(t)});DEFPRINT($e,function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)});DEFPRINT(Ze,function(e,t){e.expression.print(t);t.print(e.operator)});DEFPRINT(Qe,function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)});DEFPRINT(Je,function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)});DEFPRINT(nt,function(e,t){t.with_square(function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach(function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Wt)t.comma()});if(i>0)t.space()})});DEFPRINT(it,function(e,t){if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)});t.newline()});else print_braced_empty(e,t)});DEFPRINT(ct,function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Ot)&&!(e.extends instanceof He)&&!(e.extends instanceof pt)&&!(e.extends instanceof ce);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.newline()}t.indent();e.print(t)});t.newline()});else t.print("{}")});DEFPRINT(ht,function(e,t){t.print("new.target")});function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=l.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(at,function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof _t&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!l.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof _t&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof U)){print_property_name(e.key,e.quote,t)}else{t.with_square(function(){e.key.print(t)})}t.colon();e.value.print(t)}});DEFPRINT(lt,(e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof kt){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()});rt.DEFMETHOD("_print_getter_setter",function(e,t){var n=this;if(n.static){t.print("static");t.space()}if(e){t.print(e);t.space()}if(n.key instanceof yt){print_property_name(n.key.name,n.quote,t)}else{t.with_square(function(){n.key.print(t)})}n.value._do_print(t,true)});DEFPRINT(ot,function(e,t){e._print_getter_setter("set",t)});DEFPRINT(st,function(e,t){e._print_getter_setter("get",t)});DEFPRINT(ut,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,t)});_t.DEFMETHOD("_do_print",function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)});DEFPRINT(_t,function(e,t){e._do_print(t)});DEFPRINT(Wt,noop);DEFPRINT(It,function(e,t){t.print("this")});DEFPRINT(Pt,function(e,t){t.print("super")});DEFPRINT(Lt,function(e,t){t.print(e.getValue())});DEFPRINT(Bt,function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)});DEFPRINT(Vt,function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}});DEFPRINT(Ut,function(e,t){t.print(e.getValue()+"n")});const e=/(<\s*\/\s*script)/i;const t=(e,t)=>t.replace("/","\\/");DEFPRINT(zt,function(n,i){let{source:r,flags:a}=n.getValue();r=regexp_source_fix(r);a=a?sort_regexp_flags(a):"";r=r.replace(e,t);i.print(i.to_utf8(`/${r}/${a}`));const o=i.parent();if(o instanceof Qe&&/^\w/.test(o.operator)&&o.left===n){i.print(" ")}});function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof q)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;i{return e===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t)};const un=(e,t)=>{if(!sn(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!sn(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const cn=e=>{const t=Object.keys(e).map(t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}}).join(" && ");return new Function("other","return "+t)};const ln=()=>true;U.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};K.prototype.shallow_cmp=ln;G.prototype.shallow_cmp=cn({value:"eq"});X.prototype.shallow_cmp=ln;H.prototype.shallow_cmp=ln;q.prototype.shallow_cmp=ln;j.prototype.shallow_cmp=cn({"label.name":"eq"});Q.prototype.shallow_cmp=ln;J.prototype.shallow_cmp=ln;ee.prototype.shallow_cmp=cn({init:"exist",condition:"exist",step:"exist"});te.prototype.shallow_cmp=ln;ne.prototype.shallow_cmp=ln;ie.prototype.shallow_cmp=ln;ae.prototype.shallow_cmp=ln;oe.prototype.shallow_cmp=ln;se.prototype.shallow_cmp=cn({is_generator:"eq",async:"eq"});pe.prototype.shallow_cmp=cn({is_array:"eq"});_e.prototype.shallow_cmp=ln;he.prototype.shallow_cmp=ln;de.prototype.shallow_cmp=cn({value:"eq"});me.prototype.shallow_cmp=ln;De.prototype.shallow_cmp=ln;ke.prototype.shallow_cmp=ln;Se.prototype.shallow_cmp=cn({is_star:"eq"});Te.prototype.shallow_cmp=cn({alternative:"exist"});Ae.prototype.shallow_cmp=ln;Ce.prototype.shallow_cmp=ln;Fe.prototype.shallow_cmp=cn({bcatch:"exist",bfinally:"exist"});Oe.prototype.shallow_cmp=cn({argname:"exist"});we.prototype.shallow_cmp=ln;Me.prototype.shallow_cmp=ln;Le.prototype.shallow_cmp=cn({value:"exist"});Be.prototype.shallow_cmp=ln;Ve.prototype.shallow_cmp=cn({imported_name:"exist",imported_names:"exist"});Ue.prototype.shallow_cmp=ln;ze.prototype.shallow_cmp=cn({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});Ke.prototype.shallow_cmp=ln;Xe.prototype.shallow_cmp=ln;He.prototype.shallow_cmp=ln;Ye.prototype.shallow_cmp=ln;We.prototype.shallow_cmp=cn({property:"eq"});je.prototype.shallow_cmp=cn({operator:"eq"});Qe.prototype.shallow_cmp=cn({operator:"eq"});Je.prototype.shallow_cmp=ln;nt.prototype.shallow_cmp=ln;it.prototype.shallow_cmp=ln;rt.prototype.shallow_cmp=ln;at.prototype.shallow_cmp=cn({key:"eq"});ot.prototype.shallow_cmp=cn({static:"eq"});st.prototype.shallow_cmp=cn({static:"eq"});ut.prototype.shallow_cmp=cn({static:"eq",is_generator:"eq",async:"eq"});ct.prototype.shallow_cmp=cn({name:"exist",extends:"exist"});lt.prototype.shallow_cmp=cn({static:"eq"});_t.prototype.shallow_cmp=cn({name:"eq"});ht.prototype.shallow_cmp=ln;It.prototype.shallow_cmp=ln;Pt.prototype.shallow_cmp=ln;Bt.prototype.shallow_cmp=cn({value:"eq"});Vt.prototype.shallow_cmp=cn({value:"eq"});Ut.prototype.shallow_cmp=cn({value:"eq"});zt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Kt.prototype.shallow_cmp=ln;const fn=1<<0;const pn=1<<1;let _n=null;let hn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof U)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(_n&&_n.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&fn||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof St||this.orig[0]instanceof bt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof yt||(this.orig[0]instanceof At||this.orig[0]instanceof Tt)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof St)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Ct&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}re.DEFMETHOD("figure_out_scope",function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof ae)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new re(t);i._block_scope=true;const a=t instanceof Oe?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof ee||t instanceof te){s.push(i)}}if(t instanceof Ae){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof Et){return e instanceof St}return!(e instanceof vt||e instanceof gt)})){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof Dt))mark_export(h,2);if(a!==i){t.mark_enclosed();var h=i.find_variable(t);if(t.thedef!==h){t.thedef=h;t.reference()}}}else if(t instanceof Nt){var d=r.get(t.name);if(!d)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=d}if(!(i instanceof ae)&&(t instanceof ze||t instanceof Ve)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}});this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof ze?fn:0){var r=i.exported_definition;if((r instanceof fe||r instanceof ft)&&i.is_default){e.export=pn}}}const c=this instanceof ae;if(c){this.globals=new Map}var u=new TreeWalker(e=>{if(e instanceof De&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Ot){var t=e.name;if(t=="eval"&&u.parent()instanceof Ke){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Be&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof wt)r.export=fn}else if(r.scope instanceof se&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof Et)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Ct&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}});this.walk(u);if(e.ie8||e.safari10){walk(this,e=>{if(e instanceof Ct){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach(function(e){e.thedef=a;e.reference()});e.thedef=a;e.reference();return true}})}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach(function(t){push_uniq(e.enclosed,t)})}}});ae.DEFMETHOD("def_global",function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}});re.DEFMETHOD("init_scope_vars",function(e){this.variables=new Map;this.functions=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1});re.DEFMETHOD("conflicting_def",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)});re.DEFMETHOD("conflicting_def_shallow",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)});re.DEFMETHOD("add_child_scope",function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach(t=>push_uniq(e.enclosed,t));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}});function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}re.DEFMETHOD("create_symbol",function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find(e=>e.conflicting_def_shallow(o))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s});U.DEFMETHOD("is_block_scope",return_false);ct.DEFMETHOD("is_block_scope",return_false);se.DEFMETHOD("is_block_scope",return_false);ae.DEFMETHOD("is_block_scope",return_false);Ce.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);re.DEFMETHOD("is_block_scope",function(){return this._block_scope||false});$.DEFMETHOD("is_block_scope",return_true);se.DEFMETHOD("init_scope_vars",function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new Dt({name:"arguments",start:this.start,end:this.end}))});le.DEFMETHOD("init_scope_vars",function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false});_t.DEFMETHOD("mark_enclosed",function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}});_t.DEFMETHOD("reference",function(){this.definition().references.push(this);this.mark_enclosed()});re.DEFMETHOD("find_variable",function(e){if(e instanceof _t)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)});re.DEFMETHOD("def_function",function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof fe)n.init=t;this.functions.set(e.name,n);return n});re.DEFMETHOD("def_variable",function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ce)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n});function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=dn(++e.cname);if(l.has(i))continue;if(t.reserved.has(i))continue;if(hn&&hn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}re.DEFMETHOD("next_mangled",function(e){return next_mangled(this,e)});ae.DEFMETHOD("next_mangled",function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t});ce.DEFMETHOD("next_mangled",function(e,t){var n=t.orig[0]instanceof Dt&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}});_t.DEFMETHOD("unmangleable",function(e){var t=this.definition();return!t||t.unmangleable(e)});Ft.DEFMETHOD("unmangleable",return_false);_t.DEFMETHOD("unreferenced",function(){return!this.definition().references.length&&!this.scope.pinned()});_t.DEFMETHOD("definition",function(){return this.thedef});_t.DEFMETHOD("global",function(){return this.thedef.global});ae.DEFMETHOD("_default_mangler_options",function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e});ae.DEFMETHOD("mangle_names",function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){_n=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach(function(e){i.add(e)})}}var r=new TreeWalker(function(i,r){if(i instanceof j){var a=t;r();t=a;return true}if(i instanceof re){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(_n&&i instanceof Le&&i.value instanceof se&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){_n.add(i.name.definition().id);return}if(i instanceof Ft){let e;do{e=dn(++t)}while(l.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Ct){n.push(i.definition());return}});this.walk(r);if(e.keep_fnames||e.keep_classnames){hn=new Set;n.forEach(t=>{if(t.name.length<6&&t.unmangleable(e)){hn.add(t.name)}})}n.forEach(t=>{t.mangle(e)});_n=null;hn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&fn);if(i){n.push(t)}}});ae.DEFMETHOD("find_colliding_names",function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker(function(e){if(e instanceof re)e.variables.forEach(add_def);if(e instanceof Ct)add_def(e.definition())}));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}});ae.DEFMETHOD("expand_names",function(e){dn.reset();dn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker(function(e){if(e instanceof re)e.variables.forEach(rename);if(e instanceof Ct)rename(e.definition())}));function next_name(){var e;do{e=dn(n++)}while(t.has(e)||l.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach(function(e){e.name=i});t.references.forEach(function(e){e.name=i})}});U.DEFMETHOD("tail_node",return_this);Xe.DEFMETHOD("tail_node",function(){return this.expressions[this.expressions.length-1]});ae.DEFMETHOD("compute_char_frequency",function(e){e=this._default_mangler_options(e);try{U.prototype.print=function(t,n){this._print(t,n);if(this instanceof _t&&!this.unmangleable(e)){dn.consider(this.name,-1)}else if(e.properties){if(this instanceof We){dn.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};dn.consider(this.print_to_string(),1)}finally{U.prototype.print=U.prototype._print}dn.sort();function skip_string(e){if(e instanceof Bt){dn.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Xe){skip_string(e.tail_node())}}});const dn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach(function(e){i.set(e,0)});t.forEach(function(e){i.set(e,0)})}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let mn=undefined;U.prototype.size=function(e,t){mn=e&&e.mangle_options;let n=0;walk_parent(this,(e,t)=>{n+=e._size(t)},t||e&&e.stack);mn=undefined;return n};U.prototype._size=(()=>0);K.prototype._size=(()=>8);G.prototype._size=function(){return 2+this.value.length};const En=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+En(this.body)};ae.prototype._size=function(){return En(this.body)};q.prototype._size=(()=>1);j.prototype._size=(()=>2);Q.prototype._size=(()=>9);J.prototype._size=(()=>7);ee.prototype._size=(()=>8);te.prototype._size=(()=>8);ie.prototype._size=(()=>6);oe.prototype._size=(()=>3);const gn=e=>(e.is_generator?1:0)+(e.async?6:0);ue.prototype._size=function(){return gn(this)+4+En(this.argnames)+En(this.body)};ce.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+gn(this)+12+En(this.argnames)+En(this.body)};fe.prototype._size=function(){return gn(this)+13+En(this.argnames)+En(this.body)};le.prototype._size=function(){let e=2+En(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof _t)){e+=2}return gn(this)+e+(Array.isArray(this.body)?En(this.body):this.body._size())};pe.prototype._size=(()=>2);he.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};ge.prototype._size=function(){return this.value?7:6};ve.prototype._size=(()=>6);be.prototype._size=function(){return this.label?6:5};ye.prototype._size=function(){return this.label?9:8};Te.prototype._size=(()=>4);Ae.prototype._size=function(){return 8+En(this.body)};xe.prototype._size=function(){return 5+En(this.body)};Re.prototype._size=function(){return 8+En(this.body)};Fe.prototype._size=function(){return 3+En(this.body)};Oe.prototype._size=function(){let e=7+En(this.body);if(this.argname){e+=2}return e};we.prototype._size=function(){return 7+En(this.body)};const vn=(e,t)=>e+En(t.definitions);Ne.prototype._size=function(){return vn(4,this)};Ie.prototype._size=function(){return vn(4,this)};Pe.prototype._size=function(){return vn(6,this)};Le.prototype._size=function(){return this.value?1:0};Be.prototype._size=function(){return this.name?4:0};Ve.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+En(this.imported_names)}return e};Ue.prototype._size=(()=>11);ze.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+En(this.exported_names)}if(this.module_name){e+=5}return e};Ke.prototype._size=function(){if(this.optional){return 4+En(this.args)}return 2+En(this.args)};Ge.prototype._size=function(){return 6+En(this.args)};Xe.prototype._size=function(){return En(this.expressions)};We.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=(()=>3);nt.prototype._size=function(){return 2+En(this.elements)};it.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+En(this.properties)};const Dn=e=>typeof e==="string"?e.length:0;at.prototype._size=function(){return Dn(this.key)+1};const bn=e=>e?7:0;st.prototype._size=function(){return 5+bn(this.static)+Dn(this.key)};ot.prototype._size=function(){return 5+bn(this.static)+Dn(this.key)};ut.prototype._size=function(){return bn(this.static)+Dn(this.key)+gn(this)};ct.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};lt.prototype._size=function(){return bn(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};_t.prototype._size=function(){return!mn||this.definition().unmangleable(mn)?this.name.length:1};kt.prototype._size=function(){return this.name.length};Ot.prototype._size=dt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return _t.prototype._size.call(this)};ht.prototype._size=(()=>10);xt.prototype._size=function(){return this.name.length};Mt.prototype._size=function(){return this.name.length};It.prototype._size=(()=>4);Pt.prototype._size=(()=>5);Bt.prototype._size=function(){return this.value.length+2};Vt.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Ut.prototype._size=function(){return this.value.length};zt.prototype._size=function(){return this.value.toString().length};Gt.prototype._size=(()=>4);Xt.prototype._size=(()=>3);Ht.prototype._size=(()=>6);Wt.prototype._size=(()=>0);qt.prototype._size=(()=>8);$t.prototype._size=(()=>4);jt.prototype._size=(()=>5);ke.prototype._size=(()=>6);Se.prototype._size=(()=>6);const yn=1;const kn=2;const Sn=4;const Tn=8;const An=16;const Cn=32;const Rn=256;const xn=512;const Fn=1024;const On=Rn|xn|Fn;const wn=(e,t)=>e.flags&t;const Mn=(e,t)=>{e.flags|=t};const Nn=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:null,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,()=>{e++});if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Te){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof ie){r.body=r.body.transform(i)}return r});n.transform(i)});function read_property(e,t){t=get_value(t);if(t instanceof U)return;var n;if(e instanceof nt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof it){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof at))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Ot&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof Ke&&o.expression===n&&!(i instanceof le)&&!(i instanceof ct)&&!o.is_expr_pure(e)&&(!(i instanceof ce)||!(o instanceof Ge)&&i.contains_this())){return true}if(o instanceof nt){return is_modified(e,t,o,o,r+1)}if(o instanceof at&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof He&&o.expression===n){var c=read_property(i,o.property);return!a&&is_modified(e,t,o,c,r+1)}}(function(e){e(U,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof gt||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach(function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}})}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach(t=>{reset_def(e,t)})}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof Dt||n.name=="arguments")return false;t.fixed=make_node(Ht,n)}return true}return t.fixed instanceof fe}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof fe){return i instanceof U&&t.fixed.parent_scope===n}return t.orig.every(e=>{return!(e instanceof gt||e instanceof bt||e instanceof St)})}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof se||e instanceof It}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof pt)return}if(s instanceof et&&(s.operator==="="||s.logical)&&i===s.right||s instanceof Ke&&(i!==s.expression||s instanceof Ge)||s instanceof Ee&&i===s.value&&i.scope!==t.scope||s instanceof Le&&i===s.value||s instanceof Se&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof nt||s instanceof ke||s instanceof Qe&&Ln.has(s.operator)||s instanceof Je&&i!==s.condition||s instanceof oe||s instanceof Xe&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof at&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof He&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof Xe&&i!==s.tail_node())return;if(s instanceof X)return;t.direct_access=true}const t=e=>walk(e,e=>{if(!(e instanceof _t))return;var t=e.definition();if(!t)return;if(e instanceof Ot)t.references.push(e);t.fixed=false});e(ue,function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true});e(et,function(e,n,i){var r=this;if(r.left instanceof pe){t(r.left);return}const a=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var o=r.left;if(!(o instanceof Ot))return a();var s=o.definition();var u=safe_to_assign(e,s,o.scope,r.right);s.assignments++;if(!u)return a();var c=s.fixed;if(!c&&r.operator!="="&&!r.logical)return a();var l=r.operator=="=";var f=l?r.right:r;if(is_modified(i,e,r,f,0))return a();s.references.push(o);if(!r.logical){if(!l)s.chained=true;s.fixed=l?function(){return r.right}:function(){return make_node(Qe,r,{operator:r.operator.slice(0,-1),left:c instanceof U?c:c(),right:r.right})}}if(r.logical){mark(e,s,false);push(e);r.right.walk(e);pop(e);return true}mark(e,s,false);r.right.walk(e);mark(e,s,true);mark_escaped(e,s,o.scope,r,f,0,1);return true});e(Qe,function(e){if(!Ln.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true});e(H,function(e,t,n){reset_block_variables(n,this)});e(xe,function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true});e(ct,function(e,t){Nn(this,An);push(e);t();pop(e);return true});e(Je,function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true});e(Ye,function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true});e(Ke,function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true});e(He,function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof U)this.property.walk(e);return true});e(Re,function(e,t){push(e);t();pop(e);return true});function mark_lambda(e,t,n){Nn(this,An);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof Ke&&i.expression===this&&!i.args.some(e=>e instanceof oe)&&this.argnames.every(e=>e instanceof _t)){this.argnames.forEach((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node(Ht,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}})}t();pop(e);return true}e(se,mark_lambda);e(Q,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true});e(ee,function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true});e(te,function(e,n,i){reset_block_variables(i,this);t(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true});e(Te,function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true});e(j,function(e){push(e);this.body.walk(e);pop(e);return true});e(Ct,function(){this.definition().fixed=false});e(Ot,function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof bt){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof se&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof se&&!r.pinned()||r instanceof ct||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)});e(ae,function(e,t,n){this.globals.forEach(function(e){reset_def(n,e)});reset_variables(e,n,this)});e(Fe,function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true});e(je,function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Ot))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:a instanceof U?a:a()}),right:make_node(Vt,t,{value:1})})};mark(e,i,true);return true});e(Le,function(e,n){var i=this;if(i.name instanceof pe){t(i.name);return}var r=i.name.definition();if(i.value){if(safe_to_assign(e,r,i.name.scope,i.value)){r.fixed=function(){return i.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);n();mark(e,r,true);return true}else{r.fixed=false}}});e(J,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true})})(function(e,t){e.DEFMETHOD("reduce_vars",t)});ae.DEFMETHOD("reset_opt_flags",function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker(function(r,a){Nn(r,On);if(n){if(e.top_retain&&r instanceof fe&&i.parent()===t){Mn(r,Fn)}return r.reduce_vars(i,a,e)}});i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)});_t.DEFMETHOD("fixed_value",function(){var e=this.thedef.fixed;if(!e||e instanceof U)return e;return e()});Ot.DEFMETHOD("is_immutable",function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof St});function is_func_expr(e){return e instanceof le||e instanceof ce}function is_lhs_read_only(e){if(e instanceof It)return true;if(e instanceof Ot)return e.definition().orig[0]instanceof St;if(e instanceof He){e=e.expression;if(e instanceof Ot){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof zt)return false;if(e instanceof Lt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Ot))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof ae)return n;if(n instanceof se)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof re)break;if(n instanceof Oe&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Xe,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Bt,t,{value:e});case"number":if(isNaN(e))return make_node(Xt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Vt,t,{value:-e})}):make_node(Vt,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(qt,t)}):make_node(qt,t);case"boolean":return make_node(e?$t:jt,t);case"undefined":return make_node(Ht,t);default:if(e===null){return make_node(Gt,t,{value:null})}if(e instanceof RegExp){return make_node(zt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof Ke&&e.expression===t&&(n instanceof He||n instanceof Ot&&n.name=="eval")){return make_sequence(t,[make_node(Vt,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Xe){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof W)return e.body;if(e instanceof q)return[];if(e instanceof z)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof q)return true;if(e instanceof W)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof ft||e instanceof fe||e instanceof Ie||e instanceof Pe||e instanceof ze||e instanceof Ve)}function loop_body(e){if(e instanceof $){return e.body instanceof W?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ce||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Ot&&e.definition().undeclared}var In=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Ot.DEFMETHOD("is_declared",function(e){return!this.definition().undeclared||e.option("unsafe")&&In.has(this.name)});var Pn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof qt||e instanceof Xt||e instanceof Ht}function tighten_body(e,t){var n,r;var a=t.find_parent(re).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),i=0;do{if(e instanceof Oe||e instanceof we){i++}else if(e instanceof $){n=true}else if(e instanceof re){a=e;break}else if(e instanceof Fe){r=true}}while(e=t.parent(i++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var c=e.length;var l=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_1||e instanceof $&&!(e instanceof ee)||e instanceof De||e instanceof Fe||e instanceof ie||e instanceof Se||e instanceof ze||e instanceof ct||n instanceof ee&&e!==n.init||!y&&(e instanceof Ot&&!e.is_declared(t)&&!Gn.has(e))||e instanceof Ot&&n instanceof Ke&&has_annotation(n,en)){A=true;return e}if(!E&&(!D||!y)&&(n instanceof Qe&&Ln.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof Te&&n.condition!==e)){E=n}if(R&&!(e instanceof dt)&&g.equivalent_to(e)){if(E){A=true;return e}if(is_lhs(e,n)){if(d)C++;return e}else{C++;if(d&&h instanceof Le)return e}o=A=true;if(h instanceof Ze){return make_node($e,h,h)}if(h instanceof Le){var i=h.name.definition();var a=h.value;if(i.references.length-i.replaced==1&&!t.exposed(i)){i.replaced++;if(S&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(et,h,{operator:"=",logical:false,left:make_node(Ot,h.name,h.name),right:a})}Nn(h,Cn);return h}var s;if(e instanceof Ke||e instanceof Ee&&(b||g instanceof He||may_modify(g))||e instanceof He&&(b||e.expression.may_throw_on_access(t))||e instanceof Ot&&(v.get(e.name)||b&&may_modify(e))||e instanceof Le&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||k&&(r?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof re)A=true}return handle_custom_scan_order(e)},function(e){if(A)return;if(m===e)A=true;if(E===e)E=null});var f=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_=0){if(c==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[c]);while(u.length>0){p=u.pop();var _=0;var h=p[p.length-1];var d=null;var m=null;var E=null;var g=get_lhs(h);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(h);var D=is_lhs_local(g);if(g instanceof Ot)v.set(g.name,false);var b=value_has_side_effects(h);var y=replace_all_symbols();var k=h.may_throw(t);var S=h.name instanceof Dt;var T=S;var A=false,C=0,R=!s||!T;if(!R){for(var x=t.self().argnames.lastIndexOf(h.name)+1;!A&&xC)C=false;else{A=false;_=0;T=S;for(var F=c;!A&&F!(e instanceof oe))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var c=n.argnames[o];var l=e.args[o];const r=c.definition&&c.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Le,c,{name:c,value:l}));if(a.has(c.name))continue;a.add(c.name);if(c instanceof oe){var f=e.args.slice(o);if(f.every(e=>!has_overlapping_symbol(n,e,i))){u.unshift([make_node(Le,c,{name:c.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!l){l=make_node(Ht,c).transform(t)}else if(l instanceof se&&l.pinned()||has_overlapping_symbol(n,l,i)){l=null}if(l)u.unshift([make_node(Le,c,{name:c,value:l})])}}}}function extract_candidates(e){p.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof Ke&&!has_annotation(e,en)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof xe){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Me){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof Dt)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Ot,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,gt)&&!is_ref_of(t,vt)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var i=new TreeWalker(function(e){var r=e;while(r instanceof He)r=r.expression;if(r instanceof Ot||r instanceof It){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}});get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof Dt){var r=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){r.args.length=Math.min(r.args.length,a.length-1)}else{var s=r.args;if(s[o])s[o]=make_node(Vt,s[o],{value:0})}return true}var u=false;return e[c].transform(new TreeTransformer(function(e,t,r){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Le){e.value=e.name instanceof gt?make_node(Ht,e.value):null;return e}return r?i.skip:null}},function(e){if(e instanceof Xe)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}}))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof Ot&&e.definition().scope===a&&!(n&&(v.has(e.name)||h instanceof je||h instanceof et&&!h.logical&&h.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Bn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(d)return true;if(g instanceof Ot){var e=g.definition();if(e.references.length-e.replaced==(h instanceof Le?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof bt)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every(e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a})}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Le)return e.value&&side_effects_external(e.value);if(t){if(e instanceof We)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof Ot)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var c=e[u];if(r&&!c&&s instanceof ge){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){o=true;e[a]=make_node(X,s,{body:s.value.expression});continue}}if(s instanceof Te){var l=aborts(s.body);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,l);s.body=make_node(W,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(W,s,{body:f});e[a]=s.transform(t);continue}var l=aborts(s.alternative);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.body=make_node(W,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,l);s.alternative=make_node(W,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Te&&s.body instanceof ge){var p=s.body.value;if(!p&&!s.alternative&&(r&&!c||c instanceof ge&&!c.value)){o=true;e[a]=make_node(X,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&c instanceof ge&&c.value){o=true;s=s.clone();s.alternative=c;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!c&&r&&i||c instanceof ge)){o=true;s=s.clone();s.alternative=c||make_node(ge,s,{value:null});e[a]=s.transform(t);if(c)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Te&&_.body instanceof ge&&next_index(u)==e.length&&c instanceof X){o=true;s=s.clone();s.alternative=make_node(W,c,{body:[c,make_node(ge,c,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Te&&i.body instanceof ge){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ne&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value)}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(X,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Me&&declarations_only(s)||s instanceof fe){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof W))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof re)return true;if(e instanceof Qe&&e.operator==="in"){return Zt}});if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof te){if(!(a.init instanceof Pe)&&!(a.init instanceof Ie)){a.object=cons_seq(a.object)}}else if(a instanceof Te){a.condition=cons_seq(a.condition)}else if(a instanceof Ae){a.expression=cons_seq(a.expression)}else if(a instanceof ie){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Te){var s=[];var u=to_simple_statement(a.body,s);var c=to_simple_statement(a.alternative,s);if(u!==false&&c!==false&&s.length>0){var l=s.length;s.push(make_node(Te,a,{condition:a.condition,body:u||make_node(q,a.body),alternative:c}));s.unshift(n,1);[].splice.apply(e,s);r+=l;n+=l+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof X?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Me))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof it))return;var r;if(n instanceof et&&!n.logical){r=[n]}else if(n instanceof Xe){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof Ot))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var c=s.left.property;if(c instanceof U){c=c.evaluate(t)}if(c instanceof U)break;c=""+c;var l=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=c&&(e.key&&e.key.name!=c)}:function(e){return e.key&&e.key.name!=c};if(!i.value.properties.every(l))break;var f=i.value.properties.filter(function(e){return e.key===c})[0];if(!f){i.value.properties.push(make_node(at,s,{key:c,value:s.right}))}else{f.value=new Xe({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ne){i.remove_initializers();n.push(i);return true}if(i instanceof fe&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ne,i,{definitions:[make_node(Le,i,{name:make_node(mt,i.name,i.name),value:null})]}));return true}if(i instanceof ze||i instanceof Ve){n.push(i);return true}if(i instanceof re){return true}})}function get_value(e){if(e instanceof Lt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof Lt){return}return e}function is_undefined(e,t){return wn(e,Tn)||e instanceof Ht||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){U.DEFMETHOD("may_throw_on_access",function(e){return!e.option("pure_getters")||this._dot_throw(e)});function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(U,is_strict);e(Gt,return_true);e(Ht,return_true);e(Lt,return_false);e(nt,return_false);e(it,function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false});e(ct,return_false);e(rt,return_false);e(st,return_true);e(oe,function(e){return this.expression._dot_throw(e)});e(ce,return_false);e(le,return_false);e(Ze,return_false);e($e,function(){return this.operator=="void"});e(Qe,function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))});e(et,function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)});e(Je,function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)});e(We,function(e){if(!is_strict(e))return false;if(this.expression instanceof ce&&this.property=="prototype")return false;return true});e(Ye,function(e){return this.expression._dot_throw(e)});e(Xe,function(e){return this.tail_node()._dot_throw(e)});e(Ot,function(e){if(this.name==="arguments")return false;if(wn(this,Tn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)})})(function(e,t){e.DEFMETHOD("_dot_throw",t)});(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(U,return_false);e($e,function(){return t.has(this.operator)});e(Qe,function(){return n.has(this.operator)||Ln.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()});e(Je,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()});e(et,function(){return this.operator=="="&&this.right.is_boolean()});e(Xe,function(){return this.tail_node().is_boolean()});e($t,return_true);e(jt,return_true)})(function(e,t){e.DEFMETHOD("is_boolean",t)});(function(e){e(U,return_false);e(Vt,return_true);var t=makePredicate("+ - ~ ++ --");e(je,function(){return t.has(this.operator)});var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)});e(et,function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)});e(Xe,function(e){return this.tail_node().is_number(e)});e(Je,function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)})})(function(e,t){e.DEFMETHOD("is_number",t)});(function(e){e(U,return_false);e(Bt,return_true);e(he,return_true);e($e,function(){return this.operator=="typeof"});e(Qe,function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))});e(et,function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)});e(Xe,function(e){return this.tail_node().is_string(e)});e(Je,function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)})})(function(e,t){e.DEFMETHOD("is_string",t)});var Ln=makePredicate("&& || ??");var Bn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Bn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof U)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map(function(e){return to_node(e,t)})});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(at,t,{key:i,value:to_node(e[i],t)}))}return make_node(it,t,{properties:n})}return make_node_from_constant(e,t)}ae.DEFMETHOD("resolve_defines",function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer(function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof He))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n}))});e(U,noop);e(Ye,function(e,t){return this.expression._find_defs(e,t)});e(We,function(e,t){return this.expression._find_defs(e,"."+this.property+t)});e(dt,function(){if(!this.global())return});e(Ot,function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)})})(function(e,t){e.DEFMETHOD("_find_defs",t)});function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(X,e,{body:e}),make_node(X,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Vn=["constructor","toString","valueOf"];var Un=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Vn),Boolean:Vn,Function:Vn,Number:["toExponential","toFixed","toPrecision"].concat(Vn),Object:Vn,RegExp:["test"].concat(Vn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Vn)});var zn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){U.DEFMETHOD("evaluate",function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t});var t=makePredicate("! ~ - + void");U.DEFMETHOD("is_constant",function(){if(this instanceof Lt){return!(this instanceof zt)}else{return this instanceof $e&&this.expression instanceof Lt&&t.has(this.operator)}});e(z,function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))});e(se,return_this);e(ct,return_this);e(U,return_this);e(Lt,function(){return this.getValue()});e(Ut,return_this);e(zt,function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this});e(he,function(){if(this.segments.length!==1)return this;return this.segments[0].value});e(ce,function(e){if(e.option("unsafe")){var t=function(){};t.node=this;t.toString=function(){return this.node.print_to_string()};return t}return this});e(nt,function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var s;if(n!=null&&o!=null&&r.has(this.operator)&&a(n)&&a(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":s=n&&o;break;case"||":s=n||o;break;case"??":s=n!=null?n:o;break;case"|":s=n|o;break;case"&":s=n&o;break;case"^":s=n^o;break;case"+":s=n+o;break;case"*":s=n*o;break;case"**":s=Math.pow(n,o);break;case"/":s=n/o;break;case"%":s=n%o;break;case"-":s=n-o;break;case"<<":s=n<>":s=n>>o;break;case">>>":s=n>>>o;break;case"==":s=n==o;break;case"===":s=n===o;break;case"!=":s=n!=o;break;case"!==":s=n!==o;break;case"<":s=n":s=n>o;break;case">=":s=n>=o;break;default:return this}if(isNaN(s)&&e.find_parent(ie)){return this}return s});e(Je,function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r});const o=new Set;e(Ot,function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const i=n._eval(e,t);o.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i});var s={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var u=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});e(He,function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof U){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var o=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));o=o instanceof We?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var c=u.get(i.name);if(!c||!c.has(n))return this;r=s[i.name]}else{r=i._eval(e,t+1);if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.argnames.length;default:return this}}return r[n]}return this});e(Ye,function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n});e(Ke,function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var i=n.property;if(i instanceof U){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var o=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));o=o instanceof We?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var u=zn.get(a.name);if(!u||!u.has(i))return this;r=s[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var c=Un.get(r.constructor.name);if(!c||!c.has(i))return this}var l=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)})})(function(e,t){e.DEFMETHOD("negate",function(e,n){return t.call(this,e,n)})});var Kn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");Ke.DEFMETHOD("is_expr_pure",function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Kn.has(t.name))return true;let i;if(t instanceof We&&is_undeclared_ref(t.expression)&&(i=zn.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,Qt)||!e.pure_funcs(this)});U.DEFMETHOD("is_call_pure",return_false);We.DEFMETHOD("is_call_pure",function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Un.get("Array")}else if(t.is_boolean()){n=Un.get("Boolean")}else if(t.is_number(e)){n=Un.get("Number")}else if(t instanceof zt){n=Un.get("RegExp")}else if(t.is_string(e)){n=Un.get("String")}else if(!this.may_throw_on_access(e)){n=Un.get("Object")}return n&&n.has(this.property)});const Gn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(U,return_true);e(q,return_false);e(Lt,return_false);e(It,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,function(e){return any(this.body,e)});e(Ke,function(e){if(!this.is_expr_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)});e(Ae,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(xe,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Fe,function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)});e(Te,function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)});e(j,function(e){return this.body.has_side_effects(e)});e(X,function(e){return this.body.has_side_effects(e)});e(se,return_false);e(ct,function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)});e(Qe,function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)});e(et,return_true);e(Je,function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)});e(je,function(e){return Bn.has(this.operator)||this.expression.has_side_effects(e)});e(Ot,function(e){return!this.is_declared(e)&&!Gn.has(this.name)});e(kt,return_false);e(dt,return_false);e(it,function(e){return any(this.properties,e)});e(rt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value.has_side_effects(e)});e(lt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)});e(ut,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(st,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(ot,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(nt,function(e){return any(this.elements,e)});e(We,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)});e(qe,function(e){if(this.optional&&is_nullish(this.expression)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)});e(Ye,function(e){return this.expression.has_side_effects(e)});e(Xe,function(e){return any(this.expressions,e)});e(Me,function(e){return any(this.definitions,e)});e(Le,function(){return this.value});e(de,return_false);e(he,function(e){return any(this.segments,e)})})(function(e,t){e.DEFMETHOD("has_side_effects",t)});(function(e){e(U,return_true);e(Lt,return_false);e(q,return_false);e(se,return_false);e(dt,return_false);e(It,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(ct,function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)});e(nt,function(e){return any(this.elements,e)});e(et,function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Ot){return false}return this.left.may_throw(e)});e(Qe,function(e){return this.left.may_throw(e)||this.right.may_throw(e)});e(H,function(e){return any(this.body,e)});e(Ke,function(e){if(this.optional&&is_nullish(this.expression))return false;if(any(this.args,e))return true;if(this.is_expr_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof se)||any(this.expression.body,e)});e(xe,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Je,function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)});e(Me,function(e){return any(this.definitions,e)});e(Te,function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)});e(j,function(e){return this.body.may_throw(e)});e(it,function(e){return any(this.properties,e)});e(rt,function(e){return this.value.may_throw(e)});e(lt,function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)});e(ut,function(e){return this.computed_key()&&this.key.may_throw(e)});e(st,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ot,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ge,function(e){return this.value&&this.value.may_throw(e)});e(Xe,function(e){return any(this.expressions,e)});e(X,function(e){return this.body.may_throw(e)});e(We,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)});e(qe,function(e){if(this.optional&&is_nullish(this.expression))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)});e(Ye,function(e){return this.expression.may_throw(e)});e(Ae,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Ot,function(e){return!this.is_declared(e)&&!Gn.has(this.name)});e(kt,return_false);e(Fe,function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)});e(je,function(e){if(this.operator=="typeof"&&this.expression instanceof Ot)return false;return this.expression.may_throw(e)});e(Le,function(e){if(!this.value)return false;return this.value.may_throw(e)})})(function(e,t){e.DEFMETHOD("may_throw",t)});(function(e){function all_refs_local(e){let t=true;walk(this,n=>{if(n instanceof Ot){if(wn(this,An)){t=false;return Zt}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return Zt}return true}if(n instanceof It&&this instanceof le){t=false;return Zt}});return t}e(U,return_false);e(Lt,return_true);e(ct,function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)});e(se,all_refs_local);e(je,function(){return this.expression.is_constant_expression()});e(Qe,function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()});e(nt,function(){return this.elements.every(e=>e.is_constant_expression())});e(it,function(){return this.properties.every(e=>e.is_constant_expression())});e(rt,function(){return!(this.key instanceof U)&&this.value.is_constant_expression()})})(function(e,t){e.DEFMETHOD("is_constant_expression",t)});function aborts(e){return e&&e.aborts()}(function(e){e(z,return_null);e(me,return_this);function block_aborts(){for(var e=0;e{if(e instanceof dt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}})}if(n.value){if(n.name instanceof pe){n.walk(f)}else{var i=n.name.definition();map_add(c,i.id,n.value);if(!i.chained&&n.name.fixed_value()===n.value){s.set(i.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}});return true}return scan_ref_scoped(i,a)});t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach(function(e){var t=c.get(e.id);if(t)t.forEach(function(e){e.walk(f)})});var p=new TreeTransformer(function before(c,f,_){var h=p.parent();if(r){const e=a(c);if(e instanceof Ot){var d=e.definition();var m=o.has(d.id);if(c instanceof et){if(!m||s.has(d.id)&&s.get(d.id)!==c){return maintain_this_binding(h,c,c.right.transform(p))}}else if(!m)return _?i.skip:make_node(Vt,c,{value:0})}}if(l!==t)return;var d;if(c.name&&(c instanceof pt&&!keep_name(e.option("keep_classnames"),(d=c.name.definition()).name)||c instanceof ce&&!keep_name(e.option("keep_fnames"),(d=c.name.definition()).name))){if(!o.has(d.id)||d.orig.length>1)c.name=null}if(c instanceof se&&!(c instanceof ue)){var E=!e.option("keep_fargs");for(var g=c.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof oe){D=D.expression}if(D instanceof tt){D=D.left}if(!(D instanceof pe)&&!o.has(D.definition().id)){Mn(D,yn);if(E){g.pop()}}else{E=false}}}if((c instanceof fe||c instanceof ft)&&c!==t){const t=c.name.definition();let r=t.global&&!n||o.has(t.id);if(!r){t.eliminated++;if(c instanceof ft){const t=c.drop_side_effect_free(e);if(t){return make_node(X,c,{body:t})}}return _?i.skip:make_node(q,c)}}if(c instanceof Me&&!(h instanceof te&&h.init===c)){var b=!(h instanceof ae)&&!(c instanceof Ne);var y=[],k=[],S=[];var T=[];c.definitions.forEach(function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof pe;var i=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&i.global)return S.push(t);if(!(r||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(i.id)){if(t.value&&s.has(i.id)&&s.get(i.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof mt){var a=u.get(i.id);if(a.length>1&&(!t.value||i.orig.indexOf(t.name)>i.eliminated)){if(t.value){var l=make_node(Ot,t.name,t.name);i.references.push(l);var f=make_node(et,t,{operator:"=",logical:false,left:l,right:t.value});if(s.get(i.id)===t){s.set(i.id,f)}T.push(f.transform(p))}remove(a,t);i.eliminated++;return}}if(t.value){if(T.length>0){if(S.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{y.push(make_node(X,c,{body:make_sequence(c,T)}))}T=[]}S.push(t)}else{k.push(t)}}else if(i.orig[0]instanceof Ct){var _=t.value&&t.value.drop_side_effect_free(e);if(_)T.push(_);t.value=null;k.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){T.push(_)}i.eliminated++}});if(k.length>0||S.length>0){c.definitions=k.concat(S);y.push(c)}if(T.length>0){y.push(make_node(X,c,{body:make_sequence(c,T)}))}switch(y.length){case 0:return _?i.skip:make_node(q,c);case 1:return y[0];default:return _?i.splice(y):make_node(W,c,{body:y})}}if(c instanceof ee){f(c,this);var A;if(c.init instanceof W){A=c.init;c.init=A.body.pop();A.body.push(c)}if(c.init instanceof X){c.init=c.init.body}else if(is_empty(c.init)){c.init=null}return!A?c:_?i.splice(A.body):A}if(c instanceof j&&c.body instanceof ee){f(c,this);if(c.body instanceof W){var A=c.body;c.body=A.body.pop();A.body.push(c);return _?i.splice(A.body):A}return c}if(c instanceof W){f(c,this);if(_&&c.body.every(can_be_evicted_from_block)){return i.splice(c.body)}return c}if(c instanceof re){const e=l;l=c;f(c,this);l=e;return c}});t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Ot&&!is_ref_of(e.left,Et)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof et){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Ot){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Ct){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof re){var u=l;l=e;n();l=u;return true}}});re.DEFMETHOD("hoist_declarations",function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,e=>{if(e instanceof re&&e!==t)return true;if(e instanceof Ne){++u;return true}});i=i&&u>1;var c=new TreeTransformer(function before(u){if(u!==t){if(u instanceof G){r.push(u);return make_node(q,u)}if(n&&u instanceof fe&&!(c.parent()instanceof ze)&&c.parent()===t){a.push(u);return make_node(q,u)}if(i&&u instanceof Ne&&!u.definitions.some(e=>e.name instanceof pe)){u.definitions.forEach(function(e){o.set(e.name.name,e);++s});var l=u.to_assignments(e);var f=c.parent();if(f instanceof te&&f.init===u){if(l==null){var p=u.definitions[0].name;return make_node(Ot,p,p)}return l}if(f instanceof ee&&f.init===u){return l}if(!l)return make_node(q,u);return make_node(X,u,{body:l})}if(u instanceof re)return u}});t=t.transform(c);if(s>0){var l=[];const e=t instanceof se;const n=e?t.args_as_names():null;o.forEach((t,i)=>{if(e&&n.some(e=>e.name===t.name.name)){o.delete(i)}else{t=t.clone();t.value=null;l.push(t);o.set(i,t)}});if(l.length>0){for(var f=0;fe instanceof oe||e.computed_key())){s(o,this);const e=new Map;const n=[];l.properties.forEach(({key:i,value:r})=>{const s=find_scope(a);const c=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map(e=>e.scope)]),tentative_name:u.name+"_"+i});e.set(String(i),c.definition());n.push(make_node(Le,o,{name:c,value:r}))});r.set(c.id,e);return i.splice(n)}}else if(o instanceof He&&o.expression instanceof Ot){const e=r.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Ot,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}});return t.transform(a)});(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var h=n.body[n.body.length-1];if(h instanceof be&&t.loopcontrol_target(h)===e)n.body.pop();if(n.body.length||n instanceof xe&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(W,e,{body:a.concat(make_node(X,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var d=false;var m=new TreeWalker(function(t){if(d||t instanceof se||t instanceof X)return true;if(t instanceof be&&m.loopcontrol_target(t)===e)d=true});e.walk(m);if(!d){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(X,f,{body:f}));E.unshift(make_node(X,e.expression,{body:e.expression}));return make_node(W,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}});def_optimize(Fe,function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(W,e,{body:n}).optimize(t)}return e});Me.DEFMETHOD("remove_initializers",function(){var e=[];this.definitions.forEach(function(t){if(t.name instanceof dt){t.value=null;e.push(t)}else{walk(t.name,n=>{if(n instanceof dt){e.push(make_node(Le,t,{name:n,value:null}))}})}});this.definitions=e});Me.DEFMETHOD("to_assignments",function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Ot,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Le,e,{name:e.name,value:e.value});var a=make_node(Ne,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)});def_optimize(Me,function(e){if(e.definitions.length==0)return make_node(q,e);return e});def_optimize(Le,function(e){if(e.name instanceof vt&&e.value!=null&&is_undefined(e.value)){e.value=null}return e});def_optimize(Ve,function(e){return e});function retain_top_func(e,t){return t.top_retain&&e instanceof fe&&wn(e,Fn)&&e.name&&t.top_retain(e.name)}def_optimize(Ke,function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every(e=>!(e instanceof oe));if(t.option("reduce_vars")&&i instanceof Ot&&!has_annotation(e,en)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i)){return make_node(Ht,e)}var a=i instanceof se;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,c=e.args.length;u=i.argnames.length;if(f||wn(i.argnames[u],yn)){var l=e.args[u].drop_side_effect_free(t);if(l){e.args[o++]=l}else if(!f){e.args[o++]=make_node(Vt,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Vt&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every(e=>{var n=e.evaluate(t);p.push(n);return e!==n})){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(zt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof We)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Bt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var h=[];var d=[];for(var u=0,c=n.expression.elements.length;u0){h.push(make_node(Bt,e,{value:d.join(_)}));d.length=0}h.push(m)}}if(d.length>0){h.push(make_node(Bt,e,{value:d.join(_)}))}if(h.length==0)return make_node(Bt,e,{value:""});if(h.length==1){if(h[0].is_string(t)){return h[0]}return make_node(Qe,h[0],{operator:"+",left:make_node(Bt,e,{value:""}),right:h[0]})}if(_==""){var g;if(h[0].is_string(t)||h[1].is_string(t)){g=h.shift()}else{g=make_node(Bt,e,{value:""})}return h.reduce(function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})},g).optimize(t)}var l=e.clone();l.expression=l.expression.clone();l.expression.expression=l.expression.expression.clone();l.expression.expression.elements=h;return best_of(t,e,l)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(Ke,e,{expression:make_node(We,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Ot){y=y.fixed_value()}if(y instanceof se&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(Ke,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(Ke,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ce,e,{argnames:[],body:[]}).optimize(t);if(e.args.every(e=>e instanceof Bt)){try{var k="n(function("+e.args.slice(0,-1).map(function(e){return e.value}).join(",")+"){"+e.args[e.args.length-1].value+"})";var S=parse(k);var T={ie8:t.option("ie8")};S.figure_out_scope(T);var A=new Compressor(t.options,{mangle_options:t.mangle_options});S=S.transform(A);S.figure_out_scope(T);dn.reset();S.compute_char_frequency(T);S.mangle_names(T);var C;walk(S,e=>{if(is_func_expr(e)){C=e;return Zt}});var k=OutputStream();W.prototype._codegen.call(C,C,k);e.args=[make_node(Bt,e,{value:C.argnames.map(function(e){return e.print_to_string()}).join(",")}),make_node(Bt,e.args[e.args.length-1],{value:k.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=a&&i.body[0];var x=a&&!i.is_generator&&!i.async;var F=x&&t.option("inline")&&!e.is_expr_pure(t);if(F&&R instanceof ge){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(Ht,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof Dt&&e.args.length<2&&n instanceof Ot&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node(Ht)).optimize(t);let i;if(n instanceof He&&(i=t.parent())instanceof Ke&&i.expression===e){return make_sequence(e,[make_node(Vt,e,{value:0}),n])}return n}}if(F){var O,w,M=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof ct)&&!(i.name&&i instanceof ce)&&(o=can_flatten_body(R))&&(n===i||has_annotation(e,Jt)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,Qt|en)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(O instanceof ct)){Mn(i,Rn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(F&&has_annotation(e,Jt)){Mn(i,Rn);i=make_node(i.CTOR===fe?ce:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(Ke,e,{expression:i,args:e.args}).optimize(t)}const N=x&&t.option("side_effects")&&i.body.every(is_empty);if(N){var b=e.args.concat(make_node(Ht,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof X&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(Ht,e);if(t instanceof ge){if(!t.value)return make_node(Ht,e);return t.value.clone(true)}if(t instanceof X){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value)){return false}}else if(e){return false}else if(!(o instanceof q)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof pe||e.has(s.name)||Pn.has(s.name)||O.conflicting_def(s.name)){return false}if(w)w.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{O=t.parent(++M);if(O.is_block_scope()&&O.block_scope){O.block_scope.variables.forEach(function(t){e.add(t.name)})}if(O instanceof Oe){if(O.argname){e.add(O.argname.name)}}else if(O instanceof $){w=[]}else if(O instanceof Ot){if(O.fixed_value()instanceof re)return false}}while(!(O instanceof re));var n=!(O instanceof ae)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!w||w.length==0||!is_reachable(i,w)}function append_var(t,n,i,r){var a=i.definition();const o=O.variables.has(i.name);if(!o){O.variables.set(i.name,a);O.enclosed.push(a);t.push(make_node(Le,i,{name:i,value:null}))}var s=make_node(Ot,i,i);a.references.push(s);if(r)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(wn(o,yn)||!o.name||O.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(mt,o,o);o.definition().orig.push(u);if(!s&&w)s=make_node(Ht,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=l.name)){var f=i.variables.get(l.name);var p=make_node(Ot,l,l);f.references.push(p);t.splice(n++,0,make_node(et,c,{operator:"=",logical:false,left:p,right:make_node(Ht,l)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=O.body.indexOf(t.parent(M-1))+1;O.body.splice(e,0,make_node(Ne,i,{definitions:n}))}return r.map(e=>e.clone(true))}});def_optimize(Ge,function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(Ke,e,e).transform(t);return e});def_optimize(Xe,function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Xe))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach(function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this});var Wn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof se||e instanceof it||e instanceof ct}def_optimize(Qe,function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Wn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&M[e.left.operator]>=M[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(Gt,e.left)}else if(t.option("typeofs")&&e.left instanceof Bt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Ot?i.is_declared(t):!(i instanceof He&&t.option("ie8"))){e.right=i;e.left=make_node(Ht,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Ot&&e.right instanceof Ot&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?$t:jt,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof Qe&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof Gt||r.left instanceof Gt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(Qe,e,{operator:r.operator.slice(0,-1),left:make_node(Gt,e),right:r.right});if(r!==e.left){a=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node($t,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node($t,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Bt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Bt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Bt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=wn(e.left,kn)?true:wn(e.left,Sn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof U)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(jt,e)]).optimize(t)}else{Mn(e,Sn)}}else if(!(s instanceof U)){var c=t.parent();if(c.operator=="&&"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var l=e.left.right.evaluate(t);if(!l)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=wn(e.left,kn)?true:wn(e.left,Sn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof U)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var c=t.parent();if(c.operator=="||"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof U)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node($t,e)]).optimize(t)}else{Mn(e,kn)}}if(e.left.operator=="&&"){var l=e.left.right.evaluate(t);if(l&&!(l instanceof U))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof U)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof U)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Lt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var h=p.optimize(t);if(p!==h){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:h}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof he){var d=e.left;var _=e.right.evaluate(t);if(_!=e.right){d.segments[d.segments.length-1].value+=String(_);return d}}if(e.right instanceof he){var _=e.right;var d=e.left.evaluate(t);if(d!=e.left){_.segments[0].value=String(d)+_.segments[0].value;return _}}if(e.left instanceof he&&e.right instanceof he){var d=e.left;var m=d.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return d}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof Qe&&e.left.operator!=e.operator&&M[e.left.operator]>=M[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Lt&&!(e.left instanceof Lt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Lt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof Lt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(Ln.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e});def_optimize(wt,function(e){return e});function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof se||n instanceof ct){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof z)return false;if(t instanceof nt||t instanceof at||t instanceof it){return true}}return false}def_optimize(Ot,function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ie)){switch(e.name){case"undefined":return make_node(Ht,e).optimize(t);case"NaN":return make_node(Xt,e).optimize(t);case"Infinity":return make_node(qt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof Ke&&n.is_expr_pure(t)||has_annotation(n,en))&&!(n instanceof ze&&s instanceof se&&s.name);if(u&&(s instanceof se||s instanceof ct)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||wn(s,An)||within_array_or_object_literal(t))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof Dt){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof fe||is_func_expr(i)){Mn(i,An)}}while(i=i.parent_scope)}}}if(u&&s instanceof se){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof Ke&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s instanceof ct){const e=!s.extends||!s.extends.may_throw(t)&&!s.extends.has_side_effects(t);u=e&&!s.properties.some(e=>e.may_throw(t)||e.has_side_effects(t))}if(u&&s){if(s instanceof ft){Mn(s,Rn);s=make_node(pt,s,s)}if(s instanceof fe){Mn(s,Rn);s=make_node(ce,s,s)}if(a.recursive_refs>0&&s.name instanceof bt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof St)){n=make_node(St,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,n=>{if(n instanceof Ot&&n.definition()===e){n.thedef=t;t.references.push(n)}})}if((s instanceof se||s instanceof ct)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof It){if(!(a.orig[0]instanceof Dt)&&a.references.every(e=>a.scope===e.scope)){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e});function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Ot||e.TYPE===t.TYPE}def_optimize(Ht,function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Ot,e,{name:"undefined",scope:n.scope,thedef:n});Mn(i,Tn);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Vt,e,{value:0})})});def_optimize(qt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Vt,e,{value:1}),right:make_node(Vt,e,{value:0})})});def_optimize(Xt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Vt,e,{value:0}),right:make_node(Vt,e,{value:0})})}return e});function is_reachable(e,t){const n=e=>{if(e instanceof Ot&&member(e.definition(),t)){return Zt}};return walk_parent(e,(t,i)=>{if(t instanceof re&&t!==e){var r=i.parent();if(r instanceof Ke&&r.expression===t)return;if(walk(t,n))return Zt;return true}})}const qn=makePredicate("+ - / * % >> << >>> | ^ &");const Yn=makePredicate("* | ^ &");def_optimize(et,function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Ot&&(n=e.left.definition()).scope===t.find_parent(se)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof Ee){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof Qe&&a.right===r||a instanceof Xe&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Ot&&e.right instanceof Qe){if(e.right.left instanceof Ot&&e.right.left.name==e.left.name&&qn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Ot&&e.right.right.name==e.left.name&&Yn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(Gt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Fe){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}});def_optimize(tt,function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e});function is_nullish(e){let t;return e instanceof Gt||is_undefined(e)||e instanceof Ot&&(t=e.definition().fixed)instanceof U&&is_nullish(t)||e instanceof He&&e.optional&&is_nullish(e.expression)||e instanceof Ke&&e.optional&&is_nullish(e.expression)||e instanceof Ye&&is_nullish(e.expression)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof Qe&&e.operator==="=="&&((i=is_nullish(e.left)&&e.left)||(i=is_nullish(e.right)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let n;let i;const r=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let r=0;let a;if(e.left instanceof Gt){r++;n=e;a=e.right}if(e.right instanceof Gt){r++;n=e;a=e.left}if(is_undefined(e.left)){r++;i=e;a=e.right}if(is_undefined(e.right)){r++;i=e;a=e.left}if(r!==1){return false}if(!a.equivalent_to(t)){return false}return true};if(!r(e.left))return false;if(!r(e.right))return false;if(n&&i&&n!==i){return true}}return false}def_optimize(Je,function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Xe){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(Je,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Ot&&o instanceof Ot&&a.definition()===o.definition()){return make_node(Qe,e,{operator:"||",left:a,right:s})}if(o instanceof et&&s instanceof et&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(et,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(Je,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof Ke&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var c=o.clone();c.args[u]=make_node(Je,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return c}if(s instanceof Je&&o.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof Xe&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof Je&&o.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof Qe&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var l=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof $t||l&&e instanceof Lt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Lt&&!e.expression.getValue()}function is_false(e){return e instanceof jt||l&&e instanceof Lt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Lt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof it){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof ut?o.key.name:o.key)==e){if(!r.every(e=>{return e instanceof at||n&&e instanceof ut&&!e.is_generator}))break;if(!safe_to_flatten(o.value,t))break;return make_node(qe,this,{expression:make_node(nt,i,{elements:r.map(function(e){var t=e.value;if(t instanceof ue)t=make_node(ce,t,t);var n=e.key;if(n instanceof U&&!(n instanceof yt)){return make_sequence(e,[n,t])}return t})}),property:make_node(Vt,this,{value:a})})}}}});def_optimize(qe,function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(We,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Ot&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof se&&s.uses_arguments&&!(s instanceof le)&&i instanceof Vt){var u=i.getValue();var c=new Set;var l=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(Dt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var d=make_node(Ot,e,_);d.reference({});Nn(_,yn);return d}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Vt&&n instanceof nt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var a=E[b].drop_side_effect_free(t);if(a){D.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof oe)break e;g=g instanceof Wt?make_node(Ht,g):g;if(!v)D.unshift(g);while(--b>=0){var a=E[b];if(a instanceof oe)break e;a=a.drop_side_effect_free(t);if(a)D.unshift(a);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:D}),property:make_node(Vt,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression)){return make_node(Ht,e)}return e});def_optimize(Ye,function(e,t){e.expression=e.expression.optimize(t);return e});se.DEFMETHOD("contains_this",function(){return walk(this,e=>{if(e instanceof It)return Zt;if(e!==this&&e instanceof re&&!(e instanceof le)){return true}})});def_optimize(We,function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof We&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ce,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Vt,e.expression,{value:0});break;case"Object":e.expression=make_node(it,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(zt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Bt,e.expression,{value:""});break}}if(!(n instanceof Ke)||!has_annotation(n,en)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression)){return make_node(Ht,e)}return e});function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node($t,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Wt)){e.splice(t,1,...i.elements);t--}}}}def_optimize(nt,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e});function inline_object_prop_spread(e){for(var t=0;te instanceof at)){e.splice(t,1,...i.properties);t--}else if(i instanceof Lt&&!(i instanceof Bt)){e.splice(t,1)}}}}def_optimize(it,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties);return e});def_optimize(zt,literals_in_boolean_context);def_optimize(ge,function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(le,opt_AST_Lambda);def_optimize(ce,function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,e=>{if(e instanceof It)return Zt});if(!n)return make_node(le,e,e).optimize(t)}return e});def_optimize(ct,function(e){return e});def_optimize(Se,function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e});def_optimize(he,function(e,t){if(!t.option("evaluate")||t.parent()instanceof _e){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof le&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof ce)&&!r.name){return make_node(ut,e,{async:r.async,is_generator:r.is_generator,key:i instanceof U?i:make_node(yt,e,{name:i}),value:make_node(ue,r,r),quote:e.quote})}}return e});def_optimize(pe,function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof oe)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){dn.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof ae){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Zn(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format beautify=true.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach(function(t){if(t in e){s[t]=e[t]}});if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.beautify||e.format){if(e.beautify&&e.format){fatal("Please only specify one of --beautify or --format")}if(e.beautify){s.format=typeof e.beautify=="object"?e.beautify:{};if(!("beautify"in s.format)){s.format.beautify=true}}if(e.format){s.format=typeof e.format=="object"?e.format:{}}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var c in e.define){s.compress.global_defs[c]=e.define[c]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let l=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){l=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let f;if(s.files&&s.files.length){f=s.files;delete s.files}else if(e.args.length){f=e.args}if(f){simple_glob(f).forEach(function(e){o[l(e)]=read_file(e)})}else{await new Promise(e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",function(e){t.push(e)}).on("end",function(){o=[t.join("")];e()});process.stdin.resume()})}await run_cli();function convert_ast(e){return U.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast(function(t,i){return n(89).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})})}else if(e.parse.spidermonkey){o=convert_ast(function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e})}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var c=o[e.filename].split(/\r?\n/);var l=c[e.line-1];if(!l&&!u){l=c[e.line-2];u=l.length}if(l){var f=70;if(u>f){l=l.slice(u-f);u=f}print_error(l.slice(0,80));print_error(l.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"functions":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof U){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.functions=t.block_scope.functions;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach(function(e){n[e]=t[e]});return n}return t},2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter(function(e){return s.test(e)}).map(function(e){return r.join(t,e)});if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),t=>{if(t instanceof et){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof nt){n[i]=r.elements.map(to_string)}else if(r instanceof zt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof _t||t instanceof He){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof Xe))throw t;function to_string(e){return e instanceof Lt?e.getValue():e.print_to_string({quote_keys:true})}})}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach(function(e){n.push(t(e))});return n}function format_object(e){var t=[];var n="";Object.keys(e).map(function(t){if(n.length!/^\$/.test(e));if(n.length>0){e.space();e.with_parens(function(){n.forEach(function(t,n){if(n)e.space();e.print(t)})})}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block(function(){t.SUBCLASSES.forEach(function(t){e.indent();doitem(t);e.newline()})})}}doitem(U);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach(t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n});return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify})},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __nccwpck_require__(n){if(t[n]){return t[n].exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);r=false}finally{if(r)delete t[n]}return i.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(845)})(); \ No newline at end of file +module.exports=(()=>{var e={89:function(e,t){(function(e,n){true?n(t):0})(this,function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var n="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var c=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var l=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)||isInAstralSet(e,l)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var h={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return h[e]=new f(e,t)}var d={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),questionDot:new f("?."),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var D=Object.prototype;var b=D.hasOwnProperty;var y=D.toString;function has(e,t){return b.call(e,t)}var k=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var T=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(k(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(k(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new T(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var C=1,R=2,x=C|R,O=4,F=8,w=16,M=32,N=64,I=128;function functionFlags(e,t){return R|(e?O:0)|(t?F:0)}var P=0,L=1,B=2,V=3,U=4,z=5;var K=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){for(var o=e.ecmaVersion;;o--){if(a=t[o]){break}}if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var s=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(s);this.reservedWordsStrictBind=wordsRegexp(s+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=d.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null};var G={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};K.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};G.inFunction.get=function(){return(this.currentVarScope().flags&R)>0};G.inGenerator.get=function(){return(this.currentVarScope().flags&F)>0};G.inAsync.get=function(){return(this.currentVarScope().flags&O)>0};G.allowSuper.get=function(){return(this.currentThisScope().flags&N)>0};G.allowDirectSuper.get=function(){return(this.currentThisScope().flags&I)>0};G.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};K.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&R)>0};K.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i=,?^&]/.test(r)||r==="!"&&this.input.charAt(i+1)==="=")}e+=t[0].length;v.lastIndex=e;e+=v.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};X.eat=function(e){if(this.type===e){this.next();return true}else{return false}};X.isContextual=function(e){return this.type===d.name&&this.value===e&&!this.containsEsc};X.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};X.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};X.canInsertSemicolon=function(){return this.type===d.eof||this.type===d.braceR||m.test(this.input.slice(this.lastTokEnd,this.start))};X.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};X.semicolon=function(){if(!this.eat(d.semi)&&!this.insertSemicolon()){this.unexpected()}};X.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};X.expect=function(e){this.eat(e)||this.unexpected()};X.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}X.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};X.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};X.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case d._class:if(e){this.unexpected()}return this.parseClass(r,true);case d._if:return this.parseIfStatement(r);case d._return:return this.parseReturnStatement(r);case d._switch:return this.parseSwitchStatement(r);case d._throw:return this.parseThrowStatement(r);case d._try:return this.parseTryStatement(r);case d._const:case d._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case d._while:return this.parseWhileStatement(r);case d._with:return this.parseWithStatement(r);case d.braceL:return this.parseBlock(true,r);case d.semi:return this.parseEmptyStatement(r);case d._export:case d._import:if(this.options.ecmaVersion>10&&i===d._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return i===d._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var c=this.value,l=this.parseExpression();if(i===d.name&&l.type==="Identifier"&&this.eat(d.colon)){return this.parseLabeledStatement(r,c,l,e)}else{return this.parseExpressionStatement(r,l)}}};W.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==d.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(d.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};W.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(q);this.enterScope(0);this.expect(d.parenL);if(this.type===d.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===d._var||this.type===d._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=new DestructuringErrors;var o=this.parseExpression(true,a);if(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(o,false,a);this.checkLVal(o);return this.parseForIn(e,o)}else{this.checkExpressionErrors(a,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,o)};W.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,$|(n?0:Z),false,t)};W.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(d._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};W.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};W.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(d.braceL);this.labels.push(Y);this.enterScope(0);var t;for(var n=false;this.type!==d.braceR;){if(this.type===d._case||this.type===d._default){var i=this.type===d._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(d.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};W.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var j=[];W.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===d._catch){var t=this.startNode();this.next();if(this.eat(d.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?M:0);this.checkLVal(t.param,n?U:B);this.expect(d.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(d._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};W.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};W.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(q);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};W.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};W.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};W.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var c=this.labels[u];if(c.statementStart===e.start){c.statementStart=this.start;c.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};W.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};W.parseBlock=function(e,t,n){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(d.braceL);if(e){this.enterScope(0)}while(this.type!==d.braceR){var i=this.parseStatement(null);t.body.push(i)}if(n){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};W.parseFor=function(e,t){e.init=t;this.expect(d.semi);e.test=this.type===d.semi?null:this.parseExpression();this.expect(d.semi);e.update=this.type===d.parenR?null:this.parseExpression();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};W.parseForIn=function(e,t){var n=this.type===d._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(t.type==="AssignmentPattern"){this.raise(t.start,"Invalid left-hand side in for-loop")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};W.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(d.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===d._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(d.comma)){break}}return e};W.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLVal(e.id,t==="var"?L:B,false)};var $=1,Z=2,Q=4;W.parseFunction=function(e,t,n,i){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===d.star&&t&Z){this.unexpected()}e.generator=this.eat(d.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&$){e.id=t&Q&&this.type!==d.name?null:this.parseIdent();if(e.id&&!(t&Z)){this.checkLVal(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?L:B:V)}}var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&$)){e.id=this.type===d.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,t&$?"FunctionDeclaration":"FunctionExpression")};W.parseFunctionParams=function(e){this.expect(d.parenL);e.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};W.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.startNode();var r=false;i.body=[];this.expect(d.braceL);while(this.type!==d.braceR){var a=this.parseClassElement(e.superClass!==null);if(a){i.body.push(a);if(a.type==="MethodDefinition"&&a.kind==="constructor"){if(r){this.raise(a.start,"Duplicate constructor in the same class")}r=true}}}this.strict=n;this.next();e.body=this.finishNode(i,"ClassBody");return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};W.parseClassElement=function(e){var t=this;if(this.eat(d.semi)){return null}var n=this.startNode();var i=function(e,i){if(i===void 0)i=false;var r=t.start,a=t.startLoc;if(!t.eatContextual(e)){return false}if(t.type!==d.parenL&&(!i||!t.canInsertSemicolon())){return true}if(n.key){t.unexpected()}n.computed=false;n.key=t.startNodeAt(r,a);n.key.name=e;t.finishNode(n.key,"Identifier");return false};n.kind="method";n.static=i("static");var r=this.eat(d.star);var a=false;if(!r){if(this.options.ecmaVersion>=8&&i("async",true)){a=true;r=this.options.ecmaVersion>=9&&this.eat(d.star)}else if(i("get")){n.kind="get"}else if(i("set")){n.kind="set"}}if(!n.key){this.parsePropertyName(n)}var o=n.key;var s=false;if(!n.computed&&!n.static&&(o.type==="Identifier"&&o.name==="constructor"||o.type==="Literal"&&o.value==="constructor")){if(n.kind!=="method"){this.raise(o.start,"Constructor can't have get/set modifier")}if(r){this.raise(o.start,"Constructor can't be a generator")}if(a){this.raise(o.start,"Constructor can't be an async method")}n.kind="constructor";s=e}else if(n.static&&o.type==="Identifier"&&o.name==="prototype"){this.raise(o.start,"Classes may not have a static property named prototype")}this.parseClassMethod(n,r,a,s);if(n.kind==="get"&&n.value.params.length!==0){this.raiseRecoverable(n.value.start,"getter should have no params")}if(n.kind==="set"&&n.value.params.length!==1){this.raiseRecoverable(n.value.start,"setter should have exactly one param")}if(n.kind==="set"&&n.value.params[0].type==="RestElement"){this.raiseRecoverable(n.value.params[0].start,"Setter cannot use rest params")}return n};W.parseClassMethod=function(e,t,n,i){e.value=this.parseMethod(t,n,i);return this.finishNode(e,"MethodDefinition")};W.parseClassId=function(e,t){if(this.type===d.name){e.id=this.parseIdent();if(t){this.checkLVal(e.id,B,false)}}else{if(t===true){this.unexpected()}e.id=null}};W.parseClassSuper=function(e){e.superClass=this.eat(d._extends)?this.parseExprSubscripts():null};W.parseExport=function(e,t){this.next();if(this.eat(d.star)){if(this.options.ecmaVersion>=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(d._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===d._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,$|Q,false,n)}else if(this.type===d._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!a&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(d._function)){return this.parseFunction(this.startNodeAt(i,r),0,false,true)}if(n&&!this.canInsertSemicolon()){if(this.eat(d.arrow)){return this.parseArrowExpression(this.startNodeAt(i,r),[o],false)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===d.name&&!a){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(d.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(i,r),[o],true)}}return o;case d.regexp:var s=this.value;t=this.parseLiteral(s.value);t.regex={pattern:s.pattern,flags:s.flags};return t;case d.num:case d.string:return this.parseLiteral(this.value);case d._null:case d._true:case d._false:t=this.startNode();t.value=this.type===d._null?null:this.type===d._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case d.parenL:var u=this.start,c=this.parseParenAndDistinguishExpression(n);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=u}if(e.parenthesizedBind<0){e.parenthesizedBind=u}}return c;case d.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(d.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case d.braceL:return this.parseObj(false,e);case d._function:t=this.startNode();this.next();return this.parseFunction(t,0);case d._class:return this.parseClass(this.startNode(),false);case d._new:return this.parseNew();case d.backQuote:return this.parseTemplate();case d._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ee.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case d.parenL:return this.parseDynamicImport(e);case d.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ee.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(d.parenR)){var t=this.start;if(this.eat(d.comma)&&this.eat(d.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ee.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ee.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ee.parseParenExpression=function(){this.expect(d.parenL);var e=this.parseExpression();this.expect(d.parenR);return e};ee.parseParenAndDistinguishExpression=function(e){var t=this.start,n=this.startLoc,i,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc;var s=[],u=true,c=false;var l=new DestructuringErrors,f=this.yieldPos,p=this.awaitPos,_;this.yieldPos=0;this.awaitPos=0;while(this.type!==d.parenR){u?u=false:this.expect(d.comma);if(r&&this.afterTrailingComma(d.parenR,true)){c=true;break}else if(this.type===d.ellipsis){_=this.start;s.push(this.parseParenItem(this.parseRestBinding()));if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{s.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var h=this.start,m=this.startLoc;this.expect(d.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(d.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=f;this.awaitPos=p;return this.parseParenArrowList(t,n,s)}if(!s.length||c){this.unexpected(this.lastTokStart)}if(_){this.unexpected(_)}this.checkExpressionErrors(l,true);this.yieldPos=f||this.yieldPos;this.awaitPos=p||this.awaitPos;if(s.length>1){i=this.startNodeAt(a,o);i.expressions=s;this.finishNodeAt(i,"SequenceExpression",h,m)}else{i=s[0]}}else{i=this.parseParenExpression()}if(this.options.preserveParens){var E=this.startNodeAt(t,n);E.expression=i;return this.finishNode(E,"ParenthesizedExpression")}else{return i}};ee.parseParenItem=function(e){return e};ee.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var te=[];ee.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(d.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(n){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.inNonArrowFunction()){this.raiseRecoverable(e.start,"'new.target' can only be used in functions")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===d._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(d.parenL)){e.arguments=this.parseExprList(d.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=te}return this.finishNode(e,"NewExpression")};ee.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===d.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===d.backQuote;return this.finishNode(n,"TemplateElement")};ee.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===d.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(d.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(d.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};ee.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===d.name||this.type===d.num||this.type===d.string||this.type===d.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===d.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};ee.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(d.braceR)){if(!i){this.expect(d.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(d.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};ee.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(d.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===d.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===d.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(d.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(d.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};ee.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===d.colon){this.unexpected()}if(this.eat(d.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===d.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==d.comma&&this.type!==d.braceR&&this.type!==d.eq)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var c=e.value.start;if(e.kind==="get"){this.raiseRecoverable(c,"getter should have no params")}else{this.raiseRecoverable(c,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,e.key)}else if(this.type===d.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,e.key)}else{e.value=e.key}e.shorthand=true}else{this.unexpected()}};ee.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(d.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(d.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===d.num||this.type===d.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ee.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ee.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|N|(n?I:0));this.expect(d.parenL);i.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};ee.parseArrowExpression=function(e,t,n){var i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|w);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=i;this.awaitPos=r;this.awaitIdentPos=a;return this.finishNode(e,"ArrowFunctionExpression")};ee.parseFunctionBody=function(e,t,n){var i=t&&this.type!==d.braceL;var r=this.strict,a=false;if(i){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||o){a=this.strictDirective(this.end);if(a&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var s=this.labels;this.labels=[];if(a){this.strict=true}this.checkParams(e,!r&&!a&&!t&&!n&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLVal(e.id,z)}e.body=this.parseBlock(false,undefined,a&&!r);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=s}this.exitScope()};ee.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===U){var a=this.currentScope();a.lexical.push(e)}else if(t===V){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&M&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&x){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};ie.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};ie.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ie.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x){return t}}};ie.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x&&!(t.flags&w)){return t}}};var ae=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var oe=K.prototype;oe.startNode=function(){return new ae(this,this.start,this.startLoc)};oe.startNodeAt=function(e,t){return new ae(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}oe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};oe.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};var se=function TokContext(e,t,n,i,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!n;this.override=i;this.generator=!!r};var ue={b_stat:new se("{",false),b_expr:new se("{",true),b_tmpl:new se("${",false),p_stat:new se("(",false),p_expr:new se("(",true),q_tmpl:new se("`",true,true,function(e){return e.tryReadTemplateToken()}),f_stat:new se("function",false),f_expr:new se("function",true),f_expr_gen:new se("function",true,false,null,true),f_gen:new se("function",false,false,null,true)};var ce=K.prototype;ce.initialContext=function(){return[ue.b_stat]};ce.braceIsBlock=function(e){var t=this.curContext();if(t===ue.f_expr||t===ue.f_stat){return true}if(e===d.colon&&(t===ue.b_stat||t===ue.b_expr)){return!t.isExpr}if(e===d._return||e===d.name&&this.exprAllowed){return m.test(this.input.slice(this.lastTokEnd,this.start))}if(e===d._else||e===d.semi||e===d.eof||e===d.parenR||e===d.arrow){return true}if(e===d.braceL){return t===ue.b_stat}if(e===d._var||e===d._const||e===d.name){return false}return!this.exprAllowed};ce.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};ce.updateContext=function(e){var t,n=this.type;if(n.keyword&&e===d.dot){this.exprAllowed=false}else if(t=n.updateContext){t.call(this,e)}else{this.exprAllowed=n.beforeExpr}};d.parenR.updateContext=d.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===ue.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};d.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?ue.b_stat:ue.b_expr);this.exprAllowed=true};d.dollarBraceL.updateContext=function(){this.context.push(ue.b_tmpl);this.exprAllowed=true};d.parenL.updateContext=function(e){var t=e===d._if||e===d._for||e===d._with||e===d._while;this.context.push(t?ue.p_stat:ue.p_expr);this.exprAllowed=true};d.incDec.updateContext=function(){};d._function.updateContext=d._class.updateContext=function(e){if(e.beforeExpr&&e!==d.semi&&e!==d._else&&!(e===d._return&&m.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===d.colon||e===d.braceL)&&this.curContext()===ue.b_stat)){this.context.push(ue.f_expr)}else{this.context.push(ue.f_stat)}this.exprAllowed=false};d.backQuote.updateContext=function(){if(this.curContext()===ue.q_tmpl){this.context.pop()}else{this.context.push(ue.q_tmpl)}this.exprAllowed=false};d.star.updateContext=function(e){if(e===d._function){var t=this.context.length-1;if(this.context[t]===ue.f_expr){this.context[t]=ue.f_expr_gen}else{this.context[t]=ue.f_gen}}this.exprAllowed=true};d.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==d.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var le="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var fe=le+" Extended_Pictographic";var pe=fe;var _e={9:le,10:fe,11:pe};var he="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var de="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 me=de+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var Ee=me+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ge={9:de,10:me,11:Ee};var ve={};function buildUnicodeData(e){var t=ve[e]={binary:wordsRegexp(_e[e]+" "+he),nonBinary:{General_Category:wordsRegexp(he),Script:wordsRegexp(ge[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var De=K.prototype;var be=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=ve[e.options.ecmaVersion>=11?11:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};be.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};be.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};be.prototype.at=function at(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return-1}var r=n.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i){return r}var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};be.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return i}var r=n.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i||(a=n.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};be.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};be.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};be.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};be.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}De.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};De.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};De.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};De.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};De.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};De.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};De.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};De.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};De.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}De.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};De.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};De.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};De.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};De.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};De.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierStart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}De.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierPart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}De.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};De.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};De.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};De.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};De.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};De.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};De.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};De.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}De.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var n=e.pos;var i=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(i&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343){e.lastIntValue=(r-55296)*1024+(o-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(i&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(i){e.raise("Invalid unicode escape")}e.pos=n}return false};function isValidUnicode(e){return e>=0&&e<=1114111}De.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};De.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};De.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}De.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};De.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};De.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};De.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}De.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}De.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};De.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};De.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};De.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};De.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};De.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};De.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};De.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}De.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}De.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};De.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}De.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(d.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};ke.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};ke.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344){return e}var t=this.input.charCodeAt(this.pos+1);return(e<<10)+t-56613888};ke.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};ke.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};ke.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(d.ellipsis)}else{++this.pos;return this.finishToken(d.dot)}};ke.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.slash,1)};ke.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?d.star:d.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=d.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(d.assign,n+1)}return this.finishOp(i,n)};ke.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(d.assign,3)}}return this.finishOp(e===124?d.logicalOR:d.logicalAND,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(e===124?d.bitwiseOR:d.bitwiseAND,1)};ke.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.bitwiseXOR,1)};ke.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(d.incDec,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(d.plusMin,1)};ke.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(d.assign,n+1)}return this.finishOp(d.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(d.relational,n)};ke.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(d.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(d.arrow)}return this.finishOp(e===61?d.eq:d.prefix,1)};ke.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57){return this.finishOp(d.questionDot,2)}}if(t===63){if(e>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(d.assign,3)}}return this.finishOp(d.coalesce,2)}}return this.finishOp(d.question,1)};ke.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(d.parenL);case 41:++this.pos;return this.finishToken(d.parenR);case 59:++this.pos;return this.finishToken(d.semi);case 44:++this.pos;return this.finishToken(d.comma);case 91:++this.pos;return this.finishToken(d.bracketL);case 93:++this.pos;return this.finishToken(d.bracketR);case 123:++this.pos;return this.finishToken(d.braceL);case 125:++this.pos;return this.finishToken(d.braceR);case 58:++this.pos;return this.finishToken(d.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(d.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(d.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};ke.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};ke.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new be(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(d.regexp,{pattern:r,flags:o,value:u})};ke.readInt=function(e,t,n){var i=this.options.ecmaVersion>=12&&t===undefined;var r=n&&this.input.charCodeAt(this.pos)===48;var a=this.pos,o=0,s=0;for(var u=0,c=t==null?Infinity:t;u=97){f=l-97+10}else if(l>=65){f=l-65+10}else if(l>=48&&l<=57){f=l-48}else{f=Infinity}if(f>=e){break}s=l;o=o*e+f}if(i&&s===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return o};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}ke.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,n)};ke.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,r)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),n);return this.finishToken(d.num,a)};ke.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}ke.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else{if(isNewLine(i,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(d.string,t)};var Se={};ke.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Se){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};ke.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Se}else{this.raise(e,t)}};ke.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===d.template||this.type===d.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(d.dollarBraceL)}else{++this.pos;return this.finishToken(d.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(d.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};ke.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};ke.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};ke.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var i=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e})}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var o="";var s=true;var u="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var l="enum implements import interface package private protected public static super this "+c+" "+u;var f="return new delete throw else case yield await";u=makePredicate(u);l=makePredicate(l);f=makePredicate(f);c=makePredicate(c);var p=makePredicate(characters("+-*&%=<>!?|~^"));var _=/[0-9a-f]/i;var h=/^0x[0-9a-f]+$/i;var d=/^0[0-7]+$/;var m=/^0o[0-7]+$/i;var E=/^0b[01]+$/i;var g=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var v=/^(0[xob])?[0-9a-f]+n$/i;var D=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var b=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var y=makePredicate(characters("\n\r\u2028\u2029"));var k=makePredicate(characters(";]),:"));var S=makePredicate(characters("[{(,;:"));var T=makePredicate(characters("[]{}(),;:"));var A={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return A.ID_Start.test(e)}function is_identifier_char(e){return A.ID_Continue.test(e)}const C=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return C.test(e)}function is_identifier_string(e,t){if(C.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=A.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=A.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(h.test(e)){return parseInt(e.substr(2),16)}else if(d.test(e)){return parseInt(e.substr(1),8)}else if(m.test(e)){return parseInt(e.substr(2),8)}else if(E.test(e)){return parseInt(e.substr(2),2)}else if(g.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var R={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw R;if(y.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));o=r.text.slice(e,r.pos);a.quote=t;return a});var g=with_eof_error("Unterminated template",function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);o=n;s=false;return a}n+=i;if(i=="\\"){var u=r.pos;var c=m&&(m.type==="name"||m.type==="punc"&&(m.value===")"||m.value==="]"));i=read_escaped_char(true,!c,true);n+=r.text.substr(u,r.pos-u)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);o=n;s=true;return a});function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var k=with_eof_error("Unterminated multiline comment",function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token});var A=with_eof_error("Unterminated identifier name",function(){var e=[],t,n=false;var i=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=i();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=i();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(l.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r});var C=with_eof_error("Unterminated regular expression",function(e){var t=false,n,i=false;while(n=next(true))if(y.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=A();return token("regexp","/"+e+"/"+r)});function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(D.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return k()}return r.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=A();if(a)return token("name",e);return c.has(e)?token("atom",e):!u.has(e)?token("name",e):D.has(e)?token("operator",e):token("keyword",e)}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===R)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(T.has(t))return token("punc",next());if(p.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var x=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var O=makePredicate(["--","++"]);var F=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var w=makePredicate(["??=","&&=","||="]);var M=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var N=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every(e=>!e.nlb)}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=S(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens(function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!o.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var s=i.in_directives,l=simple_statement();return s&&l.body instanceof Bt?new G(l.body):l;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return u(fe,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var _=import_();semicolon();return _}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new W({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new q;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(be);case"continue":next();return break_cont(ye);case"debugger":next();semicolon();return new K;case"do":next();var h=in_loop(statement);expect_token("keyword","while");var d=parenthesised();semicolon(true);return new Q({body:h,condition:d});case"while":next();return new J({condition:parenthesised(),body:in_loop(function(){return statement(false,true)})});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(ft);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return u(fe,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var m=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){m=S(true);semicolon()}return new ge({value:m});case"switch":next();return new Ae({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var m=S(true);semicolon();return new ve({value:m});case"try":next();return try_();case"var":next();var _=c();semicolon();return _;case"let":next();var _=f();semicolon();return _;case"const":next();var _=p();semicolon();return _;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ie({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var _=export_();if(is("punc",";"))semicolon();return _}}}unexpected()});function labeled_statement(){var e=as_symbol(Ot);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some(t=>t.name===e.name)){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof $)){e.references.forEach(function(t){if(t instanceof ye){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}})}return new j({body:t,label:e})}function simple_statement(e){return new X({body:(e=S(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Nt,true)}if(t!=null){n=i.labels.find(e=>e.name===t.name);if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!is_in_async()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),c(true)):is("keyword","let")?(next(),f(true)):is("keyword","const")?(next(),p(true)):S(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Me){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof pe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:S(true);expect(";");var n=is("punc",")")?null:S(true);expect(")");return new ee({init:e,condition:t,step:n,body:in_loop(function(){return r(false,true)})})}function for_of(e,t){var n=e instanceof Me?e.definitions[0].name:null;var i=S(true);expect(")");return new ne({await:t,init:e,name:n,object:i,body:in_loop(function(){return r(false,true)})})}function for_in(e){var t=S(true);expect(")");return new te({init:e,object:t,body:in_loop(function(){return r(false,true)})})}var a=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new le({start:e,end:a,async:n,argnames:t,body:r})};var u=function(e,t,n,i){var r=e===fe;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?bt:St):null;if(r&&!o){if(i){e=ce}else{unexpected()}}if(o&&e!==ue&&!(o instanceof dt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(l.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof oe){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new tt({start:n.start,left:n,operator:"=",right:S(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new oe({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?Dt:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Wt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:S(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new oe({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new pe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var c=as_symbol(t);if(a){n.push(new oe({start:o,expression:c,end:c.end}))}else{n.push(new at({start:u,key:c.name,value:c,end:c.end}))}}else if(is("punc","}")){continue}else{var l=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new at({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new at({start:l,quote:l.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:S(false),end:i.token})}}expect("}");e.check_strict();return new pe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new oe({start:prev(),expression:S(),end:i.token}))}else{o.push(S())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var c=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var l=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var l=[new ge({start:i.token,value:S(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=c;return l}function _await_expression(){if(!is_in_async()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new ke({start:prev(),end:i.token,expression:v(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&k.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Se({start:e,is_star:t,expression:n?S():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Te({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),a),expression:S(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new Re({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Ct);expect(")")}t=new Fe({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new we({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Oe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?mt:t==="const"?gt:t==="let"?vt:null;if(is("punc","{")||is("punc","[")){r=new Le({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),S(false,e)):null,end:prev()})}else{r=new Le({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),S(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var c=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var f=function(e){return new Ie({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var p=function(e){return new Pe({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var _=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return g(new ht({start:t,end:prev()}),e)}var n=h(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Ge({start:t,expression:n,args:r,end:prev()});annotate(a);return g(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Ft);break;case"num":t=new Vt({start:e,end:e,value:e.value,raw:o});break;case"big_int":t=new Ut({start:e,end:e,value:e.value});break;case"string":t=new Bt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new zt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new jt({start:e,end:e});break;case"true":t=new $t({start:e,end:e});break;case"null":t=new Gt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var n=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof it){return n(new pe({start:e.start,end:e.end,is_array:false,names:e.properties.map(e=>to_fun_args(e))}),t)}else if(e instanceof at){e.value=to_fun_args(e.value);return n(e,t)}else if(e instanceof Wt){return e}else if(e instanceof pe){e.names=e.names.map(e=>to_fun_args(e));return n(e,t)}else if(e instanceof Ft){return n(new Dt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof oe){e.expression=to_fun_args(e.expression);return n(e,t)}else if(e instanceof nt){return n(new pe({start:e.start,end:e.end,is_array:true,names:e.elements.map(e=>to_fun_args(e))}),t)}else if(e instanceof et){return n(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var h=function(e,t){if(is("operator","new")){return _(e)}if(is("operator","import")){return import_meta()}var r=i.token;var o;var s=is("name","async")&&(o=peek()).value!="["&&o.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(s&&!e)break;var c=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return a(r,c.map(e=>to_fun_args(e)),!!s)}var l=s?new Ke({expression:s,args:c}):c.length==1?c[0]:new Xe({expressions:c});if(l.start){const e=r.comments_before.length;n.set(r,e);l.start.comments_before.unshift(...r.comments_before);r.comments_before=l.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=l.start.comments_after}l.start=r;var p=prev();if(l.end){p.comments_before=l.end.comments_before;l.end.comments_after.push(...p.comments_after);p.comments_after=l.end.comments_after}l.end=p;if(l instanceof Ke)annotate(l);return g(l,e);case"[":return g(d(),e);case"{":return g(E(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var h=new Dt({name:i.token.value,start:r,end:r});next();return a(r,[h],!!s)}if(is("keyword","function")){next();var m=u(ce,false,!!s);m.start=r;m.end=prev();return g(m,e)}if(s)return g(s,e);if(is("keyword","class")){next();var v=class_(pt);v.start=r;v.end=prev();return g(v,e)}if(is("template_head")){return g(template_string(),e)}if(N.has(i.token.type)){return g(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new de({start:i.token,raw:o,value:i.token.value,end:i.token}));while(!s){next();handle_regexp();e.push(S(true));e.push(new de({start:i.token,raw:o,value:i.token.value,end:i.token}))}next();return new he({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Wt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new oe({start:prev(),expression:S(),end:i.token}))}else{a.push(S(false))}}next();return a}var d=embed_tokens(function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})});var m=embed_tokens((e,t)=>{return u(ue,e,t)});var E=embed_tokens(function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new oe({start:e,expression:S(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Ft({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=S(false)}if(is("operator","=")){next();o=new et({start:e,left:o,operator:"=",right:S(false),logical:false,end:prev()})}r.push(new at({start:e,quote:e.quote,key:a instanceof U?a:""+a,value:o,end:prev()}))}next();return new it({properties:r})});function class_(e){var t,n,r,a,o=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){r=as_symbol(e===ft?Tt:At)}if(e===ft&&!r){unexpected()}if(i.token.value=="extends"){next();a=S(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){t=i.token;n=concise_method_or_getset(as_property_name(),t,true);if(!n){unexpected()}o.push(n);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:t,name:r,extends:a,properties:o,end:prev()})}function concise_method_or_getset(e,t,n){var r=function(e,t){if(typeof e==="string"||typeof e==="number"){return new yt({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const a=e=>{if(typeof e==="string"||typeof e==="number"){return new kt({start:c,end:c,name:""+e})}else if(e===null){unexpected()}return e};var o=false;var s=false;var u=false;var c=t;if(n&&e==="static"&&!is("punc","(")){s=true;c=i.token;e=as_property_name()}if(e==="async"&&!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=")){o=true;c=i.token;e=as_property_name()}if(e===null){u=true;c=i.token;e=as_property_name();if(e===null){unexpected()}}if(is("punc","(")){e=r(e,t);var l=new ut({start:t,static:s,is_generator:u,async:o,key:e,quote:e instanceof yt?c.quote:undefined,value:m(u,o),end:prev()});return l}const f=i.token;if(e=="get"){if(!is("punc")||is("punc","[")){e=r(as_property_name(),t);return new st({start:t,static:s,key:e,quote:e instanceof yt?f.quote:undefined,value:m(),end:prev()})}}else if(e=="set"){if(!is("punc")||is("punc","[")){e=r(as_property_name(),t);return new ot({start:t,static:s,key:e,quote:e instanceof yt?f.quote:undefined,value:m(),end:prev()})}}if(n){const n=a(e);const i=n instanceof kt?c.quote:undefined;if(is("operator","=")){next();return new lt({start:t,static:s,quote:i,key:n,value:S(false),end:prev()})}else if(is("name")||is("punc",";")||is("punc","}")){return new lt({start:t,static:s,quote:i,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Rt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Ve({start:e,imported_name:t,imported_names:n,module_name:new Bt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return g(new Ue({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?xt:Mt;var n=e?Rt:wt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Be({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?xt:Mt;var r=e?Rt:wt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Be({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Rt:Mt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new ze({start:e,is_default:t,exported_names:n,module_name:new Bt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new ze({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=S(false);semicolon()}else if((o=r(t))instanceof Me&&t){unexpected(o.start)}else if(o instanceof Me||o instanceof se||o instanceof ft){u=o}else if(o instanceof X){s=o.body}else{unexpected(o.start)}return new ze({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=S(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?It:t=="super"?Pt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof dt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,Qt);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,Jt);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,en);break}}}}var g=function(e,t,n){var i=e.start;if(is("punc",".")){next();return g(new We({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=S(true);expect("]");return g(new qe({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new Ke({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return g(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new Ke({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=g(t,true,true)}else if(is("name")){n=g(new We({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=S(true);expect("]");n=g(new qe({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return g(new _e({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new oe({start:prev(),expression:S(false),end:prev()}))}else{e.push(S(false))}if(!is("punc",")")){expect(",")}}next();return e}var v=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"){if(is_in_async()){next();return _await_expression()}else if(i.input.has_directive("use strict")){token_error(i.token,"Unexpected await identifier inside strict mode")}}if(is("operator")&&x.has(n.value)){next();handle_regexp();var r=make_unary($e,n,v(e));r.start=n;r.end=prev();return r}var a=h(e,t);while(is("operator")&&O.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof le)unexpected();a=make_unary(Ze,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Ft&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var D=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?M[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=D(v(true),a,n);return D(new Qe({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return D(v(true,true),0,e)}var b=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=S(false);expect(":");return new Je({start:t,condition:n,consequent:r,alternative:S(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof Ft}function to_destructuring(e){if(e instanceof it){e=new pe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const I=(e,t)=>Boolean(e.flags&t);const P=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const L=1;const B=2;const V=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return I(this,L)}set nlb(e){P(this,L,e)}get quote(){return!I(this,V)?"":I(this,B)?"'":'"'}set quote(e){P(this,B,e==="'");P(this,V,!!e)}}var U=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer(function(e){if(e!==t){return e.clone(true)}}))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var z=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var K=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},z);var G=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},z);var X=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,function(){this.body._walk(e)})},_children_backwards(e){e(this.body)}},z);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",functions:"[Map/S] like `variables`, but only lists function declarations",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.functions)n.functions=new Map(this.functions);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var ae=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer(function(e){if(e instanceof G&&e.value=="$ORIG"){return i.splice(t)}}));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer(function(e){if(e instanceof G&&e.value=="$ORIG"){return i.splice(n)}}))}},re);var oe=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,function(){this.expression.walk(e)})},_children_backwards(e){e(this.expression)}});var se=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},se);var fe=DEFNODE("Defun",null,{$documentation:"A function definition"},se);var pe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,function(){this.names.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker(function(t){if(t instanceof _t){e.push(t)}}));return e}});var _e=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,function(){this.prefix._walk(e);this.template_string._walk(e)})},_children_backwards(e){e(this.template_string);e(this.prefix)}});var he=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,function(){this.segments.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var me=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},z);var Ee=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},me);var ge=DEFNODE("Return",null,{$documentation:"A `return` statement"},Ee);var ve=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},Ee);var De=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},me);var be=DEFNODE("Break",null,{$documentation:"A `break` statement"},De);var ye=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},De);var ke=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})},_children_backwards(e){e(this.expression)}});var Se=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Te=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)})},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},Y);var Ae=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var Ce=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var Re=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Ce);var xe=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Ce);var Oe=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)})},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var Fe=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,function(){if(this.argname)this.argname._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var we=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var Me=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e))})},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},re);var lt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,function(){if(this.key instanceof U)this.key._walk(e);if(this.value instanceof U)this.value._walk(e)})},_children_backwards(e){if(this.value instanceof U)e(this.value);if(this.key instanceof U)e(this.key)},computed_key(){return!(this.key instanceof kt)}},rt);var ft=DEFNODE("DefClass",null,{$documentation:"A class definition"},ct);var pt=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},ct);var _t=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var ht=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var dt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},_t);var mt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},dt);var Et=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},dt);var gt=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},Et);var vt=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},Et);var Dt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},mt);var bt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},dt);var yt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},_t);var kt=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},_t);var St=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},dt);var Tt=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},Et);var At=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},dt);var Ct=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},Et);var Rt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},Et);var xt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},_t);var Ot=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},_t);var Ft=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},_t);var wt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Ft);var Mt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},_t);var Nt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},_t);var It=DEFNODE("This",null,{$documentation:"The `this` symbol"},_t);var Pt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},It);var Lt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Bt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Lt);var Vt=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Lt);var Ut=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Lt);var zt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Lt);var Kt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Lt);var Gt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Kt);var Xt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Kt);var Ht=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Kt);var Wt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Kt);var qt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Kt);var Yt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Kt);var jt=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Yt);var $t=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Yt);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===Zt)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===Zt)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const Zt=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof se){this.directives=Object.create(this.directives)}else if(e instanceof G&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof ct){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof se||e instanceof ct){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof re&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof j&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof $||e instanceof be&&i instanceof Ae)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const Qt=1;const Jt=2;const en=4;var tn=Object.freeze({__proto__:null,AST_Accessor:ue,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:Kt,AST_Await:ke,AST_BigInt:Ut,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:W,AST_Boolean:Yt,AST_Break:be,AST_Call:Ke,AST_Case:xe,AST_Catch:Fe,AST_Chain:Ye,AST_Class:ct,AST_ClassExpression:pt,AST_ClassProperty:lt,AST_ConciseMethod:ut,AST_Conditional:Je,AST_Const:Pe,AST_Constant:Lt,AST_Continue:ye,AST_Debugger:K,AST_Default:Re,AST_DefaultAssign:tt,AST_DefClass:ft,AST_Definitions:Me,AST_Defun:fe,AST_Destructuring:pe,AST_Directive:G,AST_Do:Q,AST_Dot:We,AST_DWLoop:Z,AST_EmptyStatement:q,AST_Exit:Ee,AST_Expansion:oe,AST_Export:ze,AST_False:jt,AST_Finally:we,AST_For:ee,AST_ForIn:te,AST_ForOf:ne,AST_Function:ce,AST_Hole:Wt,AST_If:Te,AST_Import:Ve,AST_ImportMeta:Ue,AST_Infinity:qt,AST_IterationStatement:$,AST_Jump:me,AST_Label:Ot,AST_LabeledStatement:j,AST_LabelRef:Nt,AST_Lambda:se,AST_Let:Ie,AST_LoopControl:De,AST_NameMapping:Be,AST_NaN:Xt,AST_New:Ge,AST_NewTarget:ht,AST_Node:U,AST_Null:Gt,AST_Number:Vt,AST_Object:it,AST_ObjectGetter:st,AST_ObjectKeyVal:at,AST_ObjectProperty:rt,AST_ObjectSetter:ot,AST_PrefixedTemplateString:_e,AST_PropAccess:He,AST_RegExp:zt,AST_Return:ge,AST_Scope:re,AST_Sequence:Xe,AST_SimpleStatement:X,AST_Statement:z,AST_StatementWithBody:Y,AST_String:Bt,AST_Sub:qe,AST_Super:Pt,AST_Switch:Ae,AST_SwitchBranch:Ce,AST_Symbol:_t,AST_SymbolBlockDeclaration:Et,AST_SymbolCatch:Ct,AST_SymbolClass:At,AST_SymbolClassProperty:kt,AST_SymbolConst:gt,AST_SymbolDeclaration:dt,AST_SymbolDefClass:Tt,AST_SymbolDefun:bt,AST_SymbolExport:wt,AST_SymbolExportForeign:Mt,AST_SymbolFunarg:Dt,AST_SymbolImport:Rt,AST_SymbolImportForeign:xt,AST_SymbolLambda:St,AST_SymbolLet:vt,AST_SymbolMethod:yt,AST_SymbolRef:Ft,AST_SymbolVar:mt,AST_TemplateSegment:de,AST_TemplateString:he,AST_This:It,AST_Throw:ve,AST_Token:AST_Token,AST_Toplevel:ae,AST_True:$t,AST_Try:Oe,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:Ht,AST_Var:Ne,AST_VarDef:Le,AST_While:J,AST_With:ie,AST_Yield:Se,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:Zt,walk_body:walk_body,walk_parent:walk_parent,_INLINE:Jt,_NOINLINE:en,_PURE:Qt});function def_transform(e,t){e.DEFMETHOD("transform",function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i})}function do_list(e,t){return i(e,function(e){return e.transform(t,true)})}def_transform(U,noop);def_transform(j,function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)});def_transform(X,function(e,t){e.body=e.body.transform(t)});def_transform(H,function(e,t){e.body=do_list(e.body,t)});def_transform(Q,function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)});def_transform(J,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)});def_transform(ee,function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)});def_transform(te,function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)});def_transform(ie,function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)});def_transform(Ee,function(e,t){if(e.value)e.value=e.value.transform(t)});def_transform(De,function(e,t){if(e.label)e.label=e.label.transform(t)});def_transform(Te,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)});def_transform(Ae,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(xe,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Oe,function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)});def_transform(Fe,function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)});def_transform(Me,function(e,t){e.definitions=do_list(e.definitions,t)});def_transform(Le,function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)});def_transform(pe,function(e,t){e.names=do_list(e.names,t)});def_transform(se,function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof U){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}});def_transform(Ke,function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)});def_transform(Xe,function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Vt({value:0})]});def_transform(We,function(e,t){e.expression=e.expression.transform(t)});def_transform(qe,function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)});def_transform(Ye,function(e,t){e.expression=e.expression.transform(t)});def_transform(Se,function(e,t){if(e.expression)e.expression=e.expression.transform(t)});def_transform(ke,function(e,t){e.expression=e.expression.transform(t)});def_transform(je,function(e,t){e.expression=e.expression.transform(t)});def_transform(Qe,function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)});def_transform(Je,function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)});def_transform(nt,function(e,t){e.elements=do_list(e.elements,t)});def_transform(it,function(e,t){e.properties=do_list(e.properties,t)});def_transform(rt,function(e,t){if(e.key instanceof U){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)});def_transform(ct,function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)});def_transform(oe,function(e,t){e.expression=e.expression.transform(t)});def_transform(Be,function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)});def_transform(Ve,function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)});def_transform(ze,function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)});def_transform(he,function(e,t){e.segments=do_list(e.segments,t)});def_transform(_e,function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)});(function(){var e=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Oe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new we(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new yt({name:n.key})}else{n.key=from_moz(e.key)}return new ut(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new at(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new yt({name:n.key})}n.value=new ue(n.value);if(e.kind=="get")return new st(n);if(e.kind=="set")return new ot(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ut(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new yt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new st(t)}if(e.kind=="set"){return new ot(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ut(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new lt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map(function(e){return e===null?new Wt:from_moz(e)})})},ObjectExpression:function(e){return new it({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map(function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)})})},SequenceExpression:function(e){return new Xe({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:We)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?xe:Re)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Pe:e.kind==="let"?Ie:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach(function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:new xt({name:"*"}),name:from_moz(e.local)}))}});return new Ve({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_names:[new Be({name:new Mt({name:"*"}),foreign_name:new Mt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map(function(e){return new Be({foreign_name:from_moz(e.exported),name:from_moz(e.local)})}):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new ze({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new zt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new zt(n)}if(t===null)return new Gt(n);switch(typeof t){case"string":n.value=t;return new Bt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Vt(n);case"boolean":return new(t?$t:jt)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new ht({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ue({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var t=n[n.length-2];return new(t.type=="LabeledStatement"?Ot:t.type=="VariableDeclarator"&&t.id===e?t.kind=="const"?gt:t.kind=="let"?vt:mt:/Import.*Specifier/.test(t.type)?t.local===e?Rt:xt:t.type=="ExportSpecifier"?t.local===e?wt:Mt:t.type=="FunctionExpression"?t.id===e?St:Dt:t.type=="FunctionDeclaration"?t.id===e?bt:Dt:t.type=="ArrowFunctionExpression"?t.params.includes(e)?Dt:Ft:t.type=="ClassExpression"?t.id===e?At:Ft:t.type=="Property"?t.key===e&&t.computed||t.value===e?Ft:yt:t.type=="FieldDefinition"?t.key===e&&t.computed||t.value===e?Ft:kt:t.type=="ClassDeclaration"?t.id===e?Tt:Ft:t.type=="MethodDefinition"?t.computed?Ft:yt:t.type=="CatchClause"?Ct:t.type=="BreakStatement"||t.type=="ContinueStatement"?Nt:Ft)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Ut({start:my_start_token(e),end:my_end_token(e),value:e.value})}};t.UpdateExpression=t.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};t.ClassDeclaration=t.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?ft:pt)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",q);map("BlockStatement",W,"body@body");map("IfStatement",Te,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",j,"label>label, body>body");map("BreakStatement",be,"label>label");map("ContinueStatement",ye,"label>label");map("WithStatement",ie,"object>expression, body>body");map("SwitchStatement",Ae,"discriminant>expression, cases@body");map("ReturnStatement",ge,"argument>value");map("ThrowStatement",ve,"argument>value");map("WhileStatement",J,"test>condition, body>body");map("DoWhileStatement",Q,"test>condition, body>body");map("ForStatement",ee,"init>init, test>condition, update>step, body>body");map("ForInStatement",te,"left>init, right>object, body>body");map("ForOfStatement",ne,"left>init, right>object, body>body, await=await");map("AwaitExpression",ke,"argument>expression");map("YieldExpression",Se,"argument>expression, delegate=is_star");map("DebuggerStatement",K);map("VariableDeclarator",Le,"id>name, init>value");map("CatchClause",Fe,"param>argname, body%body");map("ThisExpression",It);map("Super",Pt);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ge,"callee>expression, arguments@args");map("CallExpression",Ke,"callee>expression, optional=optional, arguments@args");def_to_moz(ae,function To_Moz_Program(e){return to_moz_scope("Program",e)});def_to_moz(oe,function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}});def_to_moz(_e,function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}});def_to_moz(he,function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value}));Yt.DEFMETHOD("to_mozilla_ast",Lt.prototype.to_mozilla_ast);Gt.DEFMETHOD("to_mozilla_ast",Lt.prototype.to_mozilla_ast);Wt.DEFMETHOD("to_mozilla_ast",function To_Moz_ArrayHole(){return null});H.DEFMETHOD("to_mozilla_ast",W.prototype.to_mozilla_ast);se.DEFMETHOD("to_mozilla_ast",ce.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(e,n,i){var r="function From_Moz_"+e+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+e+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(e);if(i)i.split(/\s*,\s*/).forEach(function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}});r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(tn,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);t[e]=r;def_to_moz(n,a)}var n=null;function from_moz(e){n.push(e);var i=e!=null?t[e.type](e):null;n.pop();return i}U.from_mozilla_ast=function(e){var t=n;n=[];var i=from_moz(e);n=t;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",function(e){return set_moz_loc(this,t(this,e))})}var i=null;function to_moz(e){if(i===null){i=[]}i.push(e);var t=e!=null?e.to_mozilla_ast(i[i.length-2]):null;i.pop();if(i.length===0){i=null}return t}function to_moz_in_destructuring(){var e=i.length;while(e--){if(i[e]instanceof pe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof X&&t.body[0].body instanceof Bt){n.unshift(to_moz(new q(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof z&&i.body===t)return true;if(i instanceof Xe&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof _e&&i.prefix===t||i instanceof We&&i.expression===t||i instanceof qe&&i.expression===t||i instanceof Je&&i.condition===t||i instanceof Qe&&i.left===t||i instanceof Ze&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof it)return true;if(e instanceof Xe)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof _e)return left_is_object(e.prefix);if(e instanceof We||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const nn=/^$|[;{][\s\n]*$/;const rn=10;const an=32;const on=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let c=new Set;var l=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"})}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}})}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e})};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n});function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=l(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=l(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var h=0;var d=false;var m=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var y=b?function(){b.forEach(function(t){try{e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,!t.name&&t.token.type=="name"?t.token.value:t.name)}catch(e){}});b=[]}:noop;var k=e.max_line_len?function(){if(a>e.max_line_len){if(h){var t=u.slice(0,h);var n=u.slice(h);if(b){var i=n.length-a;b.forEach(function(e){e.line++;e.col+=i})}u=t+"\n"+n;o++;s++;a=n.length}}if(h){h=0;y()}}:noop;var S=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(d&&n){d=false;if(n!=="\n"){print("\n");C()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){A()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||S.has(n)){u+=";";a++;s++}else{k();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){b.push({token:v,name:D,line:o,col:a});v=false;if(!h)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),c=r.length-1;o+=c;a+=r[0].length;if(c>0){k();a=r[c].length}g=t}var T=function(){print("*")};var A=e.beautify?function(){print(" ")}:function(){p=true};var C=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var R=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var x=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){k();h=u.length}:noop;var O=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");x();R(next_indent(),function(){t=e()});C();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");A()}function colon(){print(":");A()}var F=b?function(e,t){v=e;D=t}:noop;function get(){if(h){k()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===rn){return true}if(t!==an){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(on," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof Ee&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var c=new TreeWalker(function(e){var t=c.parent();if(t instanceof Ee||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof We&&t.expression===e||t instanceof Xe&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}});c.push(t);t.value.walk(c)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");C()}var l=e.preamble;if(l){print(l.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter(e=>!a.has(e));if(u.length==0)return;var f=has_nlb();u.forEach(function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");C();f=true}else if(t>0){A()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");C()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}});if(!f){if(r.nlb){print("\n");C()}else{A()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof z||o.every(e=>!/comment[134]/.test(e.type))))return;a.add(o);var s=u.length;o.filter(n,e).forEach(function(e,n){if(a.has(e))return;a.add(e);m=false;if(d){print("\n");C();d=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");C()}else if(n>0||!t){A()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}d=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}});if(u.length>s)E=s}var w=[];return{get:get,toString:get,indent:C,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:x,print:print,star:T,space:A,comma:comma,colon:colon,last:function(){return g},semicolon:O,force_semicolon:force_semicolon,to_utf8:l,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!nn.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:R,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:F,option:function(t){return e[t]},printed_comments:c,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){w.push(e)},pop_node:function(){return w.pop()},parent:function(e){return w[w.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}U.DEFMETHOD("print",function(e,t){var n=this,i=n._codegen;if(n instanceof re){e.active_scope=n}else if(!e.use_asm&&n instanceof G&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}});U.DEFMETHOD("_print",U.prototype.print);U.DEFMETHOD("print_to_string",function(e){var t=OutputStream(e);this.print(t);return t.get()});function PARENS(e,t){if(Array.isArray(e)){e.forEach(function(e){PARENS(e,t)})}else{e.DEFMETHOD("needs_parens",t)}}PARENS(U,return_false);PARENS(ce,function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof Ke&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof Ke&&t.args.includes(this)){return true}}return false});PARENS(le,function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof Ke&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this});PARENS(it,function(e){return!e.has_parens()&&first_in_statement(e)});PARENS(pt,first_in_statement);PARENS(je,function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof Ke&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"});PARENS(ke,function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof Ke&&t.expression===this||e.option("safari10")&&t instanceof $e});PARENS(Xe,function(e){var t=e.parent();return t instanceof Ke||t instanceof je||t instanceof Qe||t instanceof Le||t instanceof He||t instanceof nt||t instanceof rt||t instanceof Je||t instanceof le||t instanceof tt||t instanceof oe||t instanceof ne&&this===t.object||t instanceof Se||t instanceof ze});PARENS(Qe,function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=M[e];const r=M[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}});PARENS(Se,function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof Ke&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true});PARENS(He,function(e){var t=e.parent();if(t instanceof Ge&&t.expression===this){return walk(this,e=>{if(e instanceof re)return true;if(e instanceof Ke){return Zt}})}});PARENS(Ke,function(e){var t=e.parent(),n;if(t instanceof Ge&&t.expression===this||t instanceof ze&&t.is_default&&this.expression instanceof ce)return true;return this.expression instanceof ce&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t});PARENS(Ge,function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof Ke&&t.expression===this))return true});PARENS(Vt,function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}});PARENS(Ut,function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}});PARENS([et,Je],function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof Ke&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof pe&&this.left.is_array===false)return true});DEFPRINT(G,function(e,t){t.print_string(e.value,e.quote);t.semicolon()});DEFPRINT(oe,function(e,t){t.print("...");e.expression.print(t)});DEFPRINT(pe,function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach(function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Wt)t.comma()});t.print(e.is_array?"]":"}")});DEFPRINT(K,function(e,t){t.print("debugger");t.semicolon()});function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach(function(e,i){if(n.in_directive===true&&!(e instanceof G||e instanceof q||e instanceof X&&e.body instanceof Bt)){n.in_directive=false}if(!(e instanceof q)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof X&&e.body instanceof Bt){n.in_directive=false}});n.in_directive=false}Y.DEFMETHOD("_do_print_body",function(e){force_statement(this.body,e)});DEFPRINT(z,function(e,t){e.body.print(t);t.semicolon()});DEFPRINT(ae,function(e,t){display_body(e.body,true,t,true);t.print("")});DEFPRINT(j,function(e,t){e.label.print(t);t.colon();e.body.print(t)});DEFPRINT(X,function(e,t){e.body.print(t);t.semicolon()});function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),function(){t.append_comments(e,true)});t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block(function(){display_body(e.body,false,t,n)})}else print_braced_empty(e,t)}DEFPRINT(W,function(e,t){print_braced(e,t)});DEFPRINT(q,function(e,t){t.semicolon()});DEFPRINT(Q,function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.semicolon()});DEFPRINT(J,function(e,t){t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.space();e._do_print_body(t)});DEFPRINT(ee,function(e,t){t.print("for");t.space();t.with_parens(function(){if(e.init){if(e.init instanceof Me){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}});t.space();e._do_print_body(t)});DEFPRINT(te,function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens(function(){e.init.print(t);t.space();t.print(e instanceof ne?"of":"in");t.space();e.object.print(t)});t.space();e._do_print_body(t)});DEFPRINT(ie,function(e,t){t.print("with");t.space();t.with_parens(function(){e.expression.print(t)});t.space();e._do_print_body(t)});se.DEFMETHOD("_do_print",function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof _t){n.name.print(e)}else if(t&&n.name instanceof U){e.with_square(function(){n.name.print(e)})}e.with_parens(function(){n.argnames.forEach(function(t,n){if(n)e.comma();t.print(e)})});e.space();print_braced(n,e,true)});DEFPRINT(se,function(e,t){e._do_print(t)});DEFPRINT(_e,function(e,t){var n=e.prefix;var i=n instanceof se||n instanceof Qe||n instanceof Je||n instanceof Xe||n instanceof je||n instanceof We&&n.expression instanceof it;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)});DEFPRINT(he,function(e,t){var n=t.parent()instanceof _e;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof ge){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}});Ee.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()});DEFPRINT(ge,function(e,t){e._do_print(t,"return")});DEFPRINT(ve,function(e,t){e._do_print(t,"throw")});DEFPRINT(Se,function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}});DEFPRINT(ke,function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof Ke||n instanceof Ft||n instanceof He||n instanceof je||n instanceof Lt||n instanceof ke||n instanceof it);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")});De.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()});DEFPRINT(be,function(e,t){e._do_print(t,"break")});DEFPRINT(ye,function(e,t){e._do_print(t,"continue")});function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Q)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Te){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof Y){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Te,function(e,t){t.print("if");t.space();t.with_parens(function(){e.condition.print(t)});t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Te)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}});DEFPRINT(Ae,function(e,t){t.print("switch");t.space();t.with_parens(function(){e.expression.print(t)});t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block(function(){e.body.forEach(function(e,i){t.indent(true);e.print(t);if(i0)t.newline()})})});Ce.DEFMETHOD("_do_print_body",function(e){e.newline();this.body.forEach(function(t){e.indent();t.print(e);e.newline()})});DEFPRINT(Re,function(e,t){t.print("default:");e._do_print_body(t)});DEFPRINT(xe,function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)});DEFPRINT(Oe,function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}});DEFPRINT(Fe,function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens(function(){e.argname.print(t)})}t.space();print_braced(e,t)});DEFPRINT(we,function(e,t){t.print("finally");t.space();print_braced(e,t)});Me.DEFMETHOD("_do_print",function(e,t){e.print(t);e.space();this.definitions.forEach(function(t,n){if(n)e.comma();t.print(e)});var n=e.parent();var i=n instanceof ee||n instanceof te;var r=!i||n&&n.init!==this;if(r)e.semicolon()});DEFPRINT(Ie,function(e,t){e._do_print(t,"let")});DEFPRINT(Ne,function(e,t){e._do_print(t,"var")});DEFPRINT(Pe,function(e,t){e._do_print(t,"const")});DEFPRINT(Ve,function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach(function(n,i){t.space();n.print(t);if(i{if(e instanceof re)return true;if(e instanceof Qe&&e.operator=="in"){return Zt}})}e.print(t,i)}DEFPRINT(Le,function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof ee||n instanceof te;parenthesize_for_noin(e.value,t,i)}});DEFPRINT(Ke,function(e,t){e.expression.print(t);if(e instanceof Ge&&e.args.length===0)return;if(e.expression instanceof Ke||e.expression instanceof se){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens(function(){e.args.forEach(function(e,n){if(n)t.comma();e.print(t)})})});DEFPRINT(Ge,function(e,t){t.print("new");t.space();Ke.prototype._codegen(e,t)});Xe.DEFMETHOD("_do_print",function(e){this.expressions.forEach(function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)})});DEFPRINT(Xe,function(e,t){e._do_print(t)});DEFPRINT(We,function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=l.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Vt&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}});DEFPRINT(qe,function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")});DEFPRINT(Ye,function(e,t){e.expression.print(t)});DEFPRINT($e,function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)});DEFPRINT(Ze,function(e,t){e.expression.print(t);t.print(e.operator)});DEFPRINT(Qe,function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)});DEFPRINT(Je,function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)});DEFPRINT(nt,function(e,t){t.with_square(function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach(function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Wt)t.comma()});if(i>0)t.space()})});DEFPRINT(it,function(e,t){if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)});t.newline()});else print_braced_empty(e,t)});DEFPRINT(ct,function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Ft)&&!(e.extends instanceof He)&&!(e.extends instanceof pt)&&!(e.extends instanceof ce);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.newline()}t.indent();e.print(t)});t.newline()});else t.print("{}")});DEFPRINT(ht,function(e,t){t.print("new.target")});function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=l.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(at,function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof _t&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!l.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof _t&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof U)){print_property_name(e.key,e.quote,t)}else{t.with_square(function(){e.key.print(t)})}t.colon();e.value.print(t)}});DEFPRINT(lt,(e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof kt){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()});rt.DEFMETHOD("_print_getter_setter",function(e,t){var n=this;if(n.static){t.print("static");t.space()}if(e){t.print(e);t.space()}if(n.key instanceof yt){print_property_name(n.key.name,n.quote,t)}else{t.with_square(function(){n.key.print(t)})}n.value._do_print(t,true)});DEFPRINT(ot,function(e,t){e._print_getter_setter("set",t)});DEFPRINT(st,function(e,t){e._print_getter_setter("get",t)});DEFPRINT(ut,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,t)});_t.DEFMETHOD("_do_print",function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)});DEFPRINT(_t,function(e,t){e._do_print(t)});DEFPRINT(Wt,noop);DEFPRINT(It,function(e,t){t.print("this")});DEFPRINT(Pt,function(e,t){t.print("super")});DEFPRINT(Lt,function(e,t){t.print(e.getValue())});DEFPRINT(Bt,function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)});DEFPRINT(Vt,function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}});DEFPRINT(Ut,function(e,t){t.print(e.getValue()+"n")});const e=/(<\s*\/\s*script)/i;const t=(e,t)=>t.replace("/","\\/");DEFPRINT(zt,function(n,i){let{source:r,flags:a}=n.getValue();r=regexp_source_fix(r);a=a?sort_regexp_flags(a):"";r=r.replace(e,t);i.print(i.to_utf8(`/${r}/${a}`));const o=i.parent();if(o instanceof Qe&&/^\w/.test(o.operator)&&o.left===n){i.print(" ")}});function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof q)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;i{return e===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t)};const un=(e,t)=>{if(!sn(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!sn(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const cn=e=>{const t=Object.keys(e).map(t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}}).join(" && ");return new Function("other","return "+t)};const ln=()=>true;U.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};K.prototype.shallow_cmp=ln;G.prototype.shallow_cmp=cn({value:"eq"});X.prototype.shallow_cmp=ln;H.prototype.shallow_cmp=ln;q.prototype.shallow_cmp=ln;j.prototype.shallow_cmp=cn({"label.name":"eq"});Q.prototype.shallow_cmp=ln;J.prototype.shallow_cmp=ln;ee.prototype.shallow_cmp=cn({init:"exist",condition:"exist",step:"exist"});te.prototype.shallow_cmp=ln;ne.prototype.shallow_cmp=ln;ie.prototype.shallow_cmp=ln;ae.prototype.shallow_cmp=ln;oe.prototype.shallow_cmp=ln;se.prototype.shallow_cmp=cn({is_generator:"eq",async:"eq"});pe.prototype.shallow_cmp=cn({is_array:"eq"});_e.prototype.shallow_cmp=ln;he.prototype.shallow_cmp=ln;de.prototype.shallow_cmp=cn({value:"eq"});me.prototype.shallow_cmp=ln;De.prototype.shallow_cmp=ln;ke.prototype.shallow_cmp=ln;Se.prototype.shallow_cmp=cn({is_star:"eq"});Te.prototype.shallow_cmp=cn({alternative:"exist"});Ae.prototype.shallow_cmp=ln;Ce.prototype.shallow_cmp=ln;Oe.prototype.shallow_cmp=cn({bcatch:"exist",bfinally:"exist"});Fe.prototype.shallow_cmp=cn({argname:"exist"});we.prototype.shallow_cmp=ln;Me.prototype.shallow_cmp=ln;Le.prototype.shallow_cmp=cn({value:"exist"});Be.prototype.shallow_cmp=ln;Ve.prototype.shallow_cmp=cn({imported_name:"exist",imported_names:"exist"});Ue.prototype.shallow_cmp=ln;ze.prototype.shallow_cmp=cn({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});Ke.prototype.shallow_cmp=ln;Xe.prototype.shallow_cmp=ln;He.prototype.shallow_cmp=ln;Ye.prototype.shallow_cmp=ln;We.prototype.shallow_cmp=cn({property:"eq"});je.prototype.shallow_cmp=cn({operator:"eq"});Qe.prototype.shallow_cmp=cn({operator:"eq"});Je.prototype.shallow_cmp=ln;nt.prototype.shallow_cmp=ln;it.prototype.shallow_cmp=ln;rt.prototype.shallow_cmp=ln;at.prototype.shallow_cmp=cn({key:"eq"});ot.prototype.shallow_cmp=cn({static:"eq"});st.prototype.shallow_cmp=cn({static:"eq"});ut.prototype.shallow_cmp=cn({static:"eq",is_generator:"eq",async:"eq"});ct.prototype.shallow_cmp=cn({name:"exist",extends:"exist"});lt.prototype.shallow_cmp=cn({static:"eq"});_t.prototype.shallow_cmp=cn({name:"eq"});ht.prototype.shallow_cmp=ln;It.prototype.shallow_cmp=ln;Pt.prototype.shallow_cmp=ln;Bt.prototype.shallow_cmp=cn({value:"eq"});Vt.prototype.shallow_cmp=cn({value:"eq"});Ut.prototype.shallow_cmp=cn({value:"eq"});zt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Kt.prototype.shallow_cmp=ln;const fn=1<<0;const pn=1<<1;let _n=null;let hn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof U)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(_n&&_n.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&fn||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof St||this.orig[0]instanceof bt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof yt||(this.orig[0]instanceof At||this.orig[0]instanceof Tt)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof St)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Ct&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}re.DEFMETHOD("figure_out_scope",function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof ae)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new re(t);i._block_scope=true;const a=t instanceof Fe?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof ee||t instanceof te){s.push(i)}}if(t instanceof Ae){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof Et){return e instanceof St}return!(e instanceof vt||e instanceof gt)})){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof Dt))mark_export(h,2);if(a!==i){t.mark_enclosed();var h=i.find_variable(t);if(t.thedef!==h){t.thedef=h;t.reference()}}}else if(t instanceof Nt){var d=r.get(t.name);if(!d)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=d}if(!(i instanceof ae)&&(t instanceof ze||t instanceof Ve)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}});this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof ze?fn:0){var r=i.exported_definition;if((r instanceof fe||r instanceof ft)&&i.is_default){e.export=pn}}}const c=this instanceof ae;if(c){this.globals=new Map}var u=new TreeWalker(e=>{if(e instanceof De&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Ft){var t=e.name;if(t=="eval"&&u.parent()instanceof Ke){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Be&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof wt)r.export=fn}else if(r.scope instanceof se&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof Et)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Ct&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}});this.walk(u);if(e.ie8||e.safari10){walk(this,e=>{if(e instanceof Ct){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach(function(e){e.thedef=a;e.reference()});e.thedef=a;e.reference();return true}})}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach(function(t){push_uniq(e.enclosed,t)})}}});ae.DEFMETHOD("def_global",function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}});re.DEFMETHOD("init_scope_vars",function(e){this.variables=new Map;this.functions=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1});re.DEFMETHOD("conflicting_def",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)});re.DEFMETHOD("conflicting_def_shallow",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)});re.DEFMETHOD("add_child_scope",function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach(t=>push_uniq(e.enclosed,t));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}});function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}re.DEFMETHOD("create_symbol",function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find(e=>e.conflicting_def_shallow(o))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s});U.DEFMETHOD("is_block_scope",return_false);ct.DEFMETHOD("is_block_scope",return_false);se.DEFMETHOD("is_block_scope",return_false);ae.DEFMETHOD("is_block_scope",return_false);Ce.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);re.DEFMETHOD("is_block_scope",function(){return this._block_scope||false});$.DEFMETHOD("is_block_scope",return_true);se.DEFMETHOD("init_scope_vars",function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new Dt({name:"arguments",start:this.start,end:this.end}))});le.DEFMETHOD("init_scope_vars",function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false});_t.DEFMETHOD("mark_enclosed",function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}});_t.DEFMETHOD("reference",function(){this.definition().references.push(this);this.mark_enclosed()});re.DEFMETHOD("find_variable",function(e){if(e instanceof _t)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)});re.DEFMETHOD("def_function",function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof fe)n.init=t;this.functions.set(e.name,n);return n});re.DEFMETHOD("def_variable",function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ce)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n});function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=dn(++e.cname);if(l.has(i))continue;if(t.reserved.has(i))continue;if(hn&&hn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}re.DEFMETHOD("next_mangled",function(e){return next_mangled(this,e)});ae.DEFMETHOD("next_mangled",function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t});ce.DEFMETHOD("next_mangled",function(e,t){var n=t.orig[0]instanceof Dt&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}});_t.DEFMETHOD("unmangleable",function(e){var t=this.definition();return!t||t.unmangleable(e)});Ot.DEFMETHOD("unmangleable",return_false);_t.DEFMETHOD("unreferenced",function(){return!this.definition().references.length&&!this.scope.pinned()});_t.DEFMETHOD("definition",function(){return this.thedef});_t.DEFMETHOD("global",function(){return this.thedef.global});ae.DEFMETHOD("_default_mangler_options",function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e});ae.DEFMETHOD("mangle_names",function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){_n=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach(function(e){i.add(e)})}}var r=new TreeWalker(function(i,r){if(i instanceof j){var a=t;r();t=a;return true}if(i instanceof re){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(_n&&i instanceof Le&&i.value instanceof se&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){_n.add(i.name.definition().id);return}if(i instanceof Ot){let e;do{e=dn(++t)}while(l.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Ct){n.push(i.definition());return}});this.walk(r);if(e.keep_fnames||e.keep_classnames){hn=new Set;n.forEach(t=>{if(t.name.length<6&&t.unmangleable(e)){hn.add(t.name)}})}n.forEach(t=>{t.mangle(e)});_n=null;hn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&fn);if(i){n.push(t)}}});ae.DEFMETHOD("find_colliding_names",function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker(function(e){if(e instanceof re)e.variables.forEach(add_def);if(e instanceof Ct)add_def(e.definition())}));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}});ae.DEFMETHOD("expand_names",function(e){dn.reset();dn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker(function(e){if(e instanceof re)e.variables.forEach(rename);if(e instanceof Ct)rename(e.definition())}));function next_name(){var e;do{e=dn(n++)}while(t.has(e)||l.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach(function(e){e.name=i});t.references.forEach(function(e){e.name=i})}});U.DEFMETHOD("tail_node",return_this);Xe.DEFMETHOD("tail_node",function(){return this.expressions[this.expressions.length-1]});ae.DEFMETHOD("compute_char_frequency",function(e){e=this._default_mangler_options(e);try{U.prototype.print=function(t,n){this._print(t,n);if(this instanceof _t&&!this.unmangleable(e)){dn.consider(this.name,-1)}else if(e.properties){if(this instanceof We){dn.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};dn.consider(this.print_to_string(),1)}finally{U.prototype.print=U.prototype._print}dn.sort();function skip_string(e){if(e instanceof Bt){dn.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Xe){skip_string(e.tail_node())}}});const dn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach(function(e){i.set(e,0)});t.forEach(function(e){i.set(e,0)})}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let mn=undefined;U.prototype.size=function(e,t){mn=e&&e.mangle_options;let n=0;walk_parent(this,(e,t)=>{n+=e._size(t)},t||e&&e.stack);mn=undefined;return n};U.prototype._size=(()=>0);K.prototype._size=(()=>8);G.prototype._size=function(){return 2+this.value.length};const En=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+En(this.body)};ae.prototype._size=function(){return En(this.body)};q.prototype._size=(()=>1);j.prototype._size=(()=>2);Q.prototype._size=(()=>9);J.prototype._size=(()=>7);ee.prototype._size=(()=>8);te.prototype._size=(()=>8);ie.prototype._size=(()=>6);oe.prototype._size=(()=>3);const gn=e=>(e.is_generator?1:0)+(e.async?6:0);ue.prototype._size=function(){return gn(this)+4+En(this.argnames)+En(this.body)};ce.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+gn(this)+12+En(this.argnames)+En(this.body)};fe.prototype._size=function(){return gn(this)+13+En(this.argnames)+En(this.body)};le.prototype._size=function(){let e=2+En(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof _t)){e+=2}return gn(this)+e+(Array.isArray(this.body)?En(this.body):this.body._size())};pe.prototype._size=(()=>2);he.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};ge.prototype._size=function(){return this.value?7:6};ve.prototype._size=(()=>6);be.prototype._size=function(){return this.label?6:5};ye.prototype._size=function(){return this.label?9:8};Te.prototype._size=(()=>4);Ae.prototype._size=function(){return 8+En(this.body)};xe.prototype._size=function(){return 5+En(this.body)};Re.prototype._size=function(){return 8+En(this.body)};Oe.prototype._size=function(){return 3+En(this.body)};Fe.prototype._size=function(){let e=7+En(this.body);if(this.argname){e+=2}return e};we.prototype._size=function(){return 7+En(this.body)};const vn=(e,t)=>e+En(t.definitions);Ne.prototype._size=function(){return vn(4,this)};Ie.prototype._size=function(){return vn(4,this)};Pe.prototype._size=function(){return vn(6,this)};Le.prototype._size=function(){return this.value?1:0};Be.prototype._size=function(){return this.name?4:0};Ve.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+En(this.imported_names)}return e};Ue.prototype._size=(()=>11);ze.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+En(this.exported_names)}if(this.module_name){e+=5}return e};Ke.prototype._size=function(){if(this.optional){return 4+En(this.args)}return 2+En(this.args)};Ge.prototype._size=function(){return 6+En(this.args)};Xe.prototype._size=function(){return En(this.expressions)};We.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=(()=>3);nt.prototype._size=function(){return 2+En(this.elements)};it.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+En(this.properties)};const Dn=e=>typeof e==="string"?e.length:0;at.prototype._size=function(){return Dn(this.key)+1};const bn=e=>e?7:0;st.prototype._size=function(){return 5+bn(this.static)+Dn(this.key)};ot.prototype._size=function(){return 5+bn(this.static)+Dn(this.key)};ut.prototype._size=function(){return bn(this.static)+Dn(this.key)+gn(this)};ct.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};lt.prototype._size=function(){return bn(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};_t.prototype._size=function(){return!mn||this.definition().unmangleable(mn)?this.name.length:1};kt.prototype._size=function(){return this.name.length};Ft.prototype._size=dt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return _t.prototype._size.call(this)};ht.prototype._size=(()=>10);xt.prototype._size=function(){return this.name.length};Mt.prototype._size=function(){return this.name.length};It.prototype._size=(()=>4);Pt.prototype._size=(()=>5);Bt.prototype._size=function(){return this.value.length+2};Vt.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Ut.prototype._size=function(){return this.value.length};zt.prototype._size=function(){return this.value.toString().length};Gt.prototype._size=(()=>4);Xt.prototype._size=(()=>3);Ht.prototype._size=(()=>6);Wt.prototype._size=(()=>0);qt.prototype._size=(()=>8);$t.prototype._size=(()=>4);jt.prototype._size=(()=>5);ke.prototype._size=(()=>6);Se.prototype._size=(()=>6);const yn=1;const kn=2;const Sn=4;const Tn=8;const An=16;const Cn=32;const Rn=256;const xn=512;const On=1024;const Fn=Rn|xn|On;const wn=(e,t)=>e.flags&t;const Mn=(e,t)=>{e.flags|=t};const Nn=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:null,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,()=>{e++});if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Te){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof ie){r.body=r.body.transform(i)}return r});n.transform(i)});function read_property(e,t){t=get_value(t);if(t instanceof U)return;var n;if(e instanceof nt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof it){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof at))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Ft&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof Ke&&o.expression===n&&!(i instanceof le)&&!(i instanceof ct)&&!o.is_expr_pure(e)&&(!(i instanceof ce)||!(o instanceof Ge)&&i.contains_this())){return true}if(o instanceof nt){return is_modified(e,t,o,o,r+1)}if(o instanceof at&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof He&&o.expression===n){var c=read_property(i,o.property);return!a&&is_modified(e,t,o,c,r+1)}}(function(e){e(U,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof gt||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach(function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}})}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach(t=>{reset_def(e,t)})}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof Dt||n.name=="arguments")return false;t.fixed=make_node(Ht,n)}return true}return t.fixed instanceof fe}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof fe){return i instanceof U&&t.fixed.parent_scope===n}return t.orig.every(e=>{return!(e instanceof gt||e instanceof bt||e instanceof St)})}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof se||e instanceof It}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof pt)return}if(s instanceof et&&(s.operator==="="||s.logical)&&i===s.right||s instanceof Ke&&(i!==s.expression||s instanceof Ge)||s instanceof Ee&&i===s.value&&i.scope!==t.scope||s instanceof Le&&i===s.value||s instanceof Se&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof nt||s instanceof ke||s instanceof Qe&&Ln.has(s.operator)||s instanceof Je&&i!==s.condition||s instanceof oe||s instanceof Xe&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof at&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof He&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof Xe&&i!==s.tail_node())return;if(s instanceof X)return;t.direct_access=true}const t=e=>walk(e,e=>{if(!(e instanceof _t))return;var t=e.definition();if(!t)return;if(e instanceof Ft)t.references.push(e);t.fixed=false});e(ue,function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true});e(et,function(e,n,i){var r=this;if(r.left instanceof pe){t(r.left);return}const a=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var o=r.left;if(!(o instanceof Ft))return a();var s=o.definition();var u=safe_to_assign(e,s,o.scope,r.right);s.assignments++;if(!u)return a();var c=s.fixed;if(!c&&r.operator!="="&&!r.logical)return a();var l=r.operator=="=";var f=l?r.right:r;if(is_modified(i,e,r,f,0))return a();s.references.push(o);if(!r.logical){if(!l)s.chained=true;s.fixed=l?function(){return r.right}:function(){return make_node(Qe,r,{operator:r.operator.slice(0,-1),left:c instanceof U?c:c(),right:r.right})}}if(r.logical){mark(e,s,false);push(e);r.right.walk(e);pop(e);return true}mark(e,s,false);r.right.walk(e);mark(e,s,true);mark_escaped(e,s,o.scope,r,f,0,1);return true});e(Qe,function(e){if(!Ln.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true});e(H,function(e,t,n){reset_block_variables(n,this)});e(xe,function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true});e(ct,function(e,t){Nn(this,An);push(e);t();pop(e);return true});e(Je,function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true});e(Ye,function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true});e(Ke,function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true});e(He,function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof U)this.property.walk(e);return true});e(Re,function(e,t){push(e);t();pop(e);return true});function mark_lambda(e,t,n){Nn(this,An);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof Ke&&i.expression===this&&!i.args.some(e=>e instanceof oe)&&this.argnames.every(e=>e instanceof _t)){this.argnames.forEach((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node(Ht,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}})}t();pop(e);return true}e(se,mark_lambda);e(Q,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true});e(ee,function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true});e(te,function(e,n,i){reset_block_variables(i,this);t(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true});e(Te,function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true});e(j,function(e){push(e);this.body.walk(e);pop(e);return true});e(Ct,function(){this.definition().fixed=false});e(Ft,function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof bt){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof se&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof se&&!r.pinned()||r instanceof ct||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)});e(ae,function(e,t,n){this.globals.forEach(function(e){reset_def(n,e)});reset_variables(e,n,this)});e(Oe,function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true});e(je,function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Ft))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:a instanceof U?a:a()}),right:make_node(Vt,t,{value:1})})};mark(e,i,true);return true});e(Le,function(e,n){var i=this;if(i.name instanceof pe){t(i.name);return}var r=i.name.definition();if(i.value){if(safe_to_assign(e,r,i.name.scope,i.value)){r.fixed=function(){return i.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);n();mark(e,r,true);return true}else{r.fixed=false}}});e(J,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true})})(function(e,t){e.DEFMETHOD("reduce_vars",t)});ae.DEFMETHOD("reset_opt_flags",function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker(function(r,a){Nn(r,Fn);if(n){if(e.top_retain&&r instanceof fe&&i.parent()===t){Mn(r,On)}return r.reduce_vars(i,a,e)}});i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)});_t.DEFMETHOD("fixed_value",function(){var e=this.thedef.fixed;if(!e||e instanceof U)return e;return e()});Ft.DEFMETHOD("is_immutable",function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof St});function is_func_expr(e){return e instanceof le||e instanceof ce}function is_lhs_read_only(e){if(e instanceof It)return true;if(e instanceof Ft)return e.definition().orig[0]instanceof St;if(e instanceof He){e=e.expression;if(e instanceof Ft){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof zt)return false;if(e instanceof Lt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Ft))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof ae)return n;if(n instanceof se)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof re)break;if(n instanceof Fe&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Xe,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Bt,t,{value:e});case"number":if(isNaN(e))return make_node(Xt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Vt,t,{value:-e})}):make_node(Vt,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(qt,t)}):make_node(qt,t);case"boolean":return make_node(e?$t:jt,t);case"undefined":return make_node(Ht,t);default:if(e===null){return make_node(Gt,t,{value:null})}if(e instanceof RegExp){return make_node(zt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof Ke&&e.expression===t&&(n instanceof He||n instanceof Ft&&n.name=="eval")){return make_sequence(t,[make_node(Vt,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Xe){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof W)return e.body;if(e instanceof q)return[];if(e instanceof z)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof q)return true;if(e instanceof W)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof ft||e instanceof fe||e instanceof Ie||e instanceof Pe||e instanceof ze||e instanceof Ve)}function loop_body(e){if(e instanceof $){return e.body instanceof W?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ce||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Ft&&e.definition().undeclared}var In=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Ft.DEFMETHOD("is_declared",function(e){return!this.definition().undeclared||e.option("unsafe")&&In.has(this.name)});var Pn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof qt||e instanceof Xt||e instanceof Ht}function tighten_body(e,t){var n,r;var a=t.find_parent(re).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),i=0;do{if(e instanceof Fe||e instanceof we){i++}else if(e instanceof $){n=true}else if(e instanceof re){a=e;break}else if(e instanceof Oe){r=true}}while(e=t.parent(i++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var c=e.length;var l=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_1||e instanceof $&&!(e instanceof ee)||e instanceof De||e instanceof Oe||e instanceof ie||e instanceof Se||e instanceof ze||e instanceof ct||n instanceof ee&&e!==n.init||!y&&(e instanceof Ft&&!e.is_declared(t)&&!Gn.has(e))||e instanceof Ft&&n instanceof Ke&&has_annotation(n,en)){A=true;return e}if(!E&&(!D||!y)&&(n instanceof Qe&&Ln.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof Te&&n.condition!==e)){E=n}if(R&&!(e instanceof dt)&&g.equivalent_to(e)){if(E){A=true;return e}if(is_lhs(e,n)){if(d)C++;return e}else{C++;if(d&&h instanceof Le)return e}o=A=true;if(h instanceof Ze){return make_node($e,h,h)}if(h instanceof Le){var i=h.name.definition();var a=h.value;if(i.references.length-i.replaced==1&&!t.exposed(i)){i.replaced++;if(S&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(et,h,{operator:"=",logical:false,left:make_node(Ft,h.name,h.name),right:a})}Nn(h,Cn);return h}var s;if(e instanceof Ke||e instanceof Ee&&(b||g instanceof He||may_modify(g))||e instanceof He&&(b||e.expression.may_throw_on_access(t))||e instanceof Ft&&(v.get(e.name)||b&&may_modify(e))||e instanceof Le&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||k&&(r?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof re)A=true}return handle_custom_scan_order(e)},function(e){if(A)return;if(m===e)A=true;if(E===e)E=null});var f=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_=0){if(c==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[c]);while(u.length>0){p=u.pop();var _=0;var h=p[p.length-1];var d=null;var m=null;var E=null;var g=get_lhs(h);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(h);var D=is_lhs_local(g);if(g instanceof Ft)v.set(g.name,false);var b=value_has_side_effects(h);var y=replace_all_symbols();var k=h.may_throw(t);var S=h.name instanceof Dt;var T=S;var A=false,C=0,R=!s||!T;if(!R){for(var x=t.self().argnames.lastIndexOf(h.name)+1;!A&&xC)C=false;else{A=false;_=0;T=S;for(var O=c;!A&&O!(e instanceof oe))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var c=n.argnames[o];var l=e.args[o];const r=c.definition&&c.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Le,c,{name:c,value:l}));if(a.has(c.name))continue;a.add(c.name);if(c instanceof oe){var f=e.args.slice(o);if(f.every(e=>!has_overlapping_symbol(n,e,i))){u.unshift([make_node(Le,c,{name:c.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!l){l=make_node(Ht,c).transform(t)}else if(l instanceof se&&l.pinned()||has_overlapping_symbol(n,l,i)){l=null}if(l)u.unshift([make_node(Le,c,{name:c,value:l})])}}}}function extract_candidates(e){p.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof Ke&&!has_annotation(e,en)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof xe){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Me){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof Dt)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Ft,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,gt)&&!is_ref_of(t,vt)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var i=new TreeWalker(function(e){var r=e;while(r instanceof He)r=r.expression;if(r instanceof Ft||r instanceof It){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}});get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof Dt){var r=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){r.args.length=Math.min(r.args.length,a.length-1)}else{var s=r.args;if(s[o])s[o]=make_node(Vt,s[o],{value:0})}return true}var u=false;return e[c].transform(new TreeTransformer(function(e,t,r){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Le){e.value=e.name instanceof gt?make_node(Ht,e.value):null;return e}return r?i.skip:null}},function(e){if(e instanceof Xe)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}}))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof Ft&&e.definition().scope===a&&!(n&&(v.has(e.name)||h instanceof je||h instanceof et&&!h.logical&&h.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Bn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(d)return true;if(g instanceof Ft){var e=g.definition();if(e.references.length-e.replaced==(h instanceof Le?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof bt)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every(e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a})}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Le)return e.value&&side_effects_external(e.value);if(t){if(e instanceof We)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof Ft)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var c=e[u];if(r&&!c&&s instanceof ge){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){o=true;e[a]=make_node(X,s,{body:s.value.expression});continue}}if(s instanceof Te){var l=aborts(s.body);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,l);s.body=make_node(W,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(W,s,{body:f});e[a]=s.transform(t);continue}var l=aborts(s.alternative);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.body=make_node(W,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,l);s.alternative=make_node(W,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Te&&s.body instanceof ge){var p=s.body.value;if(!p&&!s.alternative&&(r&&!c||c instanceof ge&&!c.value)){o=true;e[a]=make_node(X,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&c instanceof ge&&c.value){o=true;s=s.clone();s.alternative=c;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!c&&r&&i||c instanceof ge)){o=true;s=s.clone();s.alternative=c||make_node(ge,s,{value:null});e[a]=s.transform(t);if(c)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Te&&_.body instanceof ge&&next_index(u)==e.length&&c instanceof X){o=true;s=s.clone();s.alternative=make_node(W,c,{body:[c,make_node(ge,c,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Te&&i.body instanceof ge){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ne&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value)}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(X,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Me&&declarations_only(s)||s instanceof fe){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof W))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof re)return true;if(e instanceof Qe&&e.operator==="in"){return Zt}});if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof te){if(!(a.init instanceof Pe)&&!(a.init instanceof Ie)){a.object=cons_seq(a.object)}}else if(a instanceof Te){a.condition=cons_seq(a.condition)}else if(a instanceof Ae){a.expression=cons_seq(a.expression)}else if(a instanceof ie){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Te){var s=[];var u=to_simple_statement(a.body,s);var c=to_simple_statement(a.alternative,s);if(u!==false&&c!==false&&s.length>0){var l=s.length;s.push(make_node(Te,a,{condition:a.condition,body:u||make_node(q,a.body),alternative:c}));s.unshift(n,1);[].splice.apply(e,s);r+=l;n+=l+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof X?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Me))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof it))return;var r;if(n instanceof et&&!n.logical){r=[n]}else if(n instanceof Xe){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof Ft))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var c=s.left.property;if(c instanceof U){c=c.evaluate(t)}if(c instanceof U)break;c=""+c;var l=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=c&&(e.key&&e.key.name!=c)}:function(e){return e.key&&e.key.name!=c};if(!i.value.properties.every(l))break;var f=i.value.properties.filter(function(e){return e.key===c})[0];if(!f){i.value.properties.push(make_node(at,s,{key:c,value:s.right}))}else{f.value=new Xe({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ne){i.remove_initializers();n.push(i);return true}if(i instanceof fe&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ne,i,{definitions:[make_node(Le,i,{name:make_node(mt,i.name,i.name),value:null})]}));return true}if(i instanceof ze||i instanceof Ve){n.push(i);return true}if(i instanceof re){return true}})}function get_value(e){if(e instanceof Lt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof Lt){return}return e}function is_undefined(e,t){return wn(e,Tn)||e instanceof Ht||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){U.DEFMETHOD("may_throw_on_access",function(e){return!e.option("pure_getters")||this._dot_throw(e)});function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(U,is_strict);e(Gt,return_true);e(Ht,return_true);e(Lt,return_false);e(nt,return_false);e(it,function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false});e(ct,return_false);e(rt,return_false);e(st,return_true);e(oe,function(e){return this.expression._dot_throw(e)});e(ce,return_false);e(le,return_false);e(Ze,return_false);e($e,function(){return this.operator=="void"});e(Qe,function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))});e(et,function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)});e(Je,function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)});e(We,function(e){if(!is_strict(e))return false;if(this.expression instanceof ce&&this.property=="prototype")return false;return true});e(Ye,function(e){return this.expression._dot_throw(e)});e(Xe,function(e){return this.tail_node()._dot_throw(e)});e(Ft,function(e){if(this.name==="arguments")return false;if(wn(this,Tn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)})})(function(e,t){e.DEFMETHOD("_dot_throw",t)});(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(U,return_false);e($e,function(){return t.has(this.operator)});e(Qe,function(){return n.has(this.operator)||Ln.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()});e(Je,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()});e(et,function(){return this.operator=="="&&this.right.is_boolean()});e(Xe,function(){return this.tail_node().is_boolean()});e($t,return_true);e(jt,return_true)})(function(e,t){e.DEFMETHOD("is_boolean",t)});(function(e){e(U,return_false);e(Vt,return_true);var t=makePredicate("+ - ~ ++ --");e(je,function(){return t.has(this.operator)});var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)});e(et,function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)});e(Xe,function(e){return this.tail_node().is_number(e)});e(Je,function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)})})(function(e,t){e.DEFMETHOD("is_number",t)});(function(e){e(U,return_false);e(Bt,return_true);e(he,return_true);e($e,function(){return this.operator=="typeof"});e(Qe,function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))});e(et,function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)});e(Xe,function(e){return this.tail_node().is_string(e)});e(Je,function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)})})(function(e,t){e.DEFMETHOD("is_string",t)});var Ln=makePredicate("&& || ??");var Bn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Bn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof U)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map(function(e){return to_node(e,t)})});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(at,t,{key:i,value:to_node(e[i],t)}))}return make_node(it,t,{properties:n})}return make_node_from_constant(e,t)}ae.DEFMETHOD("resolve_defines",function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer(function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof He))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n}))});e(U,noop);e(Ye,function(e,t){return this.expression._find_defs(e,t)});e(We,function(e,t){return this.expression._find_defs(e,"."+this.property+t)});e(dt,function(){if(!this.global())return});e(Ft,function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)})})(function(e,t){e.DEFMETHOD("_find_defs",t)});function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(X,e,{body:e}),make_node(X,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Vn=["constructor","toString","valueOf"];var Un=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Vn),Boolean:Vn,Function:Vn,Number:["toExponential","toFixed","toPrecision"].concat(Vn),Object:Vn,RegExp:["test"].concat(Vn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Vn)});var zn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){U.DEFMETHOD("evaluate",function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t});var t=makePredicate("! ~ - + void");U.DEFMETHOD("is_constant",function(){if(this instanceof Lt){return!(this instanceof zt)}else{return this instanceof $e&&this.expression instanceof Lt&&t.has(this.operator)}});e(z,function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))});e(se,return_this);e(ct,return_this);e(U,return_this);e(Lt,function(){return this.getValue()});e(Ut,return_this);e(zt,function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this});e(he,function(){if(this.segments.length!==1)return this;return this.segments[0].value});e(ce,function(e){if(e.option("unsafe")){var t=function(){};t.node=this;t.toString=function(){return this.node.print_to_string()};return t}return this});e(nt,function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var s;if(n!=null&&o!=null&&r.has(this.operator)&&a(n)&&a(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":s=n&&o;break;case"||":s=n||o;break;case"??":s=n!=null?n:o;break;case"|":s=n|o;break;case"&":s=n&o;break;case"^":s=n^o;break;case"+":s=n+o;break;case"*":s=n*o;break;case"**":s=Math.pow(n,o);break;case"/":s=n/o;break;case"%":s=n%o;break;case"-":s=n-o;break;case"<<":s=n<>":s=n>>o;break;case">>>":s=n>>>o;break;case"==":s=n==o;break;case"===":s=n===o;break;case"!=":s=n!=o;break;case"!==":s=n!==o;break;case"<":s=n":s=n>o;break;case">=":s=n>=o;break;default:return this}if(isNaN(s)&&e.find_parent(ie)){return this}return s});e(Je,function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r});const o=new Set;e(Ft,function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const i=n._eval(e,t);o.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i});var s={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var u=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});e(He,function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof U){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var o=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));o=o instanceof We?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var c=u.get(i.name);if(!c||!c.has(n))return this;r=s[i.name]}else{r=i._eval(e,t+1);if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.argnames.length;default:return this}}return r[n]}return this});e(Ye,function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n});e(Ke,function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var i=n.property;if(i instanceof U){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var o=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));o=o instanceof We?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var u=zn.get(a.name);if(!u||!u.has(i))return this;r=s[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var c=Un.get(r.constructor.name);if(!c||!c.has(i))return this}var l=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)})})(function(e,t){e.DEFMETHOD("negate",function(e,n){return t.call(this,e,n)})});var Kn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");Ke.DEFMETHOD("is_expr_pure",function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Kn.has(t.name))return true;let i;if(t instanceof We&&is_undeclared_ref(t.expression)&&(i=zn.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,Qt)||!e.pure_funcs(this)});U.DEFMETHOD("is_call_pure",return_false);We.DEFMETHOD("is_call_pure",function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Un.get("Array")}else if(t.is_boolean()){n=Un.get("Boolean")}else if(t.is_number(e)){n=Un.get("Number")}else if(t instanceof zt){n=Un.get("RegExp")}else if(t.is_string(e)){n=Un.get("String")}else if(!this.may_throw_on_access(e)){n=Un.get("Object")}return n&&n.has(this.property)});const Gn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(U,return_true);e(q,return_false);e(Lt,return_false);e(It,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,function(e){return any(this.body,e)});e(Ke,function(e){if(!this.is_expr_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)});e(Ae,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(xe,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Oe,function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)});e(Te,function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)});e(j,function(e){return this.body.has_side_effects(e)});e(X,function(e){return this.body.has_side_effects(e)});e(se,return_false);e(ct,function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)});e(Qe,function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)});e(et,return_true);e(Je,function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)});e(je,function(e){return Bn.has(this.operator)||this.expression.has_side_effects(e)});e(Ft,function(e){return!this.is_declared(e)&&!Gn.has(this.name)});e(kt,return_false);e(dt,return_false);e(it,function(e){return any(this.properties,e)});e(rt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value.has_side_effects(e)});e(lt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)});e(ut,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(st,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(ot,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(nt,function(e){return any(this.elements,e)});e(We,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)});e(qe,function(e){if(this.optional&&is_nullish(this.expression)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)});e(Ye,function(e){return this.expression.has_side_effects(e)});e(Xe,function(e){return any(this.expressions,e)});e(Me,function(e){return any(this.definitions,e)});e(Le,function(){return this.value});e(de,return_false);e(he,function(e){return any(this.segments,e)})})(function(e,t){e.DEFMETHOD("has_side_effects",t)});(function(e){e(U,return_true);e(Lt,return_false);e(q,return_false);e(se,return_false);e(dt,return_false);e(It,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(ct,function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)});e(nt,function(e){return any(this.elements,e)});e(et,function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Ft){return false}return this.left.may_throw(e)});e(Qe,function(e){return this.left.may_throw(e)||this.right.may_throw(e)});e(H,function(e){return any(this.body,e)});e(Ke,function(e){if(this.optional&&is_nullish(this.expression))return false;if(any(this.args,e))return true;if(this.is_expr_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof se)||any(this.expression.body,e)});e(xe,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Je,function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)});e(Me,function(e){return any(this.definitions,e)});e(Te,function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)});e(j,function(e){return this.body.may_throw(e)});e(it,function(e){return any(this.properties,e)});e(rt,function(e){return this.value.may_throw(e)});e(lt,function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)});e(ut,function(e){return this.computed_key()&&this.key.may_throw(e)});e(st,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ot,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ge,function(e){return this.value&&this.value.may_throw(e)});e(Xe,function(e){return any(this.expressions,e)});e(X,function(e){return this.body.may_throw(e)});e(We,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)});e(qe,function(e){if(this.optional&&is_nullish(this.expression))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)});e(Ye,function(e){return this.expression.may_throw(e)});e(Ae,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Ft,function(e){return!this.is_declared(e)&&!Gn.has(this.name)});e(kt,return_false);e(Oe,function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)});e(je,function(e){if(this.operator=="typeof"&&this.expression instanceof Ft)return false;return this.expression.may_throw(e)});e(Le,function(e){if(!this.value)return false;return this.value.may_throw(e)})})(function(e,t){e.DEFMETHOD("may_throw",t)});(function(e){function all_refs_local(e){let t=true;walk(this,n=>{if(n instanceof Ft){if(wn(this,An)){t=false;return Zt}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return Zt}return true}if(n instanceof It&&this instanceof le){t=false;return Zt}});return t}e(U,return_false);e(Lt,return_true);e(ct,function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)});e(se,all_refs_local);e(je,function(){return this.expression.is_constant_expression()});e(Qe,function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()});e(nt,function(){return this.elements.every(e=>e.is_constant_expression())});e(it,function(){return this.properties.every(e=>e.is_constant_expression())});e(rt,function(){return!(this.key instanceof U)&&this.value.is_constant_expression()})})(function(e,t){e.DEFMETHOD("is_constant_expression",t)});function aborts(e){return e&&e.aborts()}(function(e){e(z,return_null);e(me,return_this);function block_aborts(){for(var e=0;e{if(e instanceof dt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}})}if(n.value){if(n.name instanceof pe){n.walk(f)}else{var i=n.name.definition();map_add(c,i.id,n.value);if(!i.chained&&n.name.fixed_value()===n.value){s.set(i.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}});return true}return scan_ref_scoped(i,a)});t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach(function(e){var t=c.get(e.id);if(t)t.forEach(function(e){e.walk(f)})});var p=new TreeTransformer(function before(c,f,_){var h=p.parent();if(r){const e=a(c);if(e instanceof Ft){var d=e.definition();var m=o.has(d.id);if(c instanceof et){if(!m||s.has(d.id)&&s.get(d.id)!==c){return maintain_this_binding(h,c,c.right.transform(p))}}else if(!m)return _?i.skip:make_node(Vt,c,{value:0})}}if(l!==t)return;var d;if(c.name&&(c instanceof pt&&!keep_name(e.option("keep_classnames"),(d=c.name.definition()).name)||c instanceof ce&&!keep_name(e.option("keep_fnames"),(d=c.name.definition()).name))){if(!o.has(d.id)||d.orig.length>1)c.name=null}if(c instanceof se&&!(c instanceof ue)){var E=!e.option("keep_fargs");for(var g=c.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof oe){D=D.expression}if(D instanceof tt){D=D.left}if(!(D instanceof pe)&&!o.has(D.definition().id)){Mn(D,yn);if(E){g.pop()}}else{E=false}}}if((c instanceof fe||c instanceof ft)&&c!==t){const t=c.name.definition();let r=t.global&&!n||o.has(t.id);if(!r){t.eliminated++;if(c instanceof ft){const t=c.drop_side_effect_free(e);if(t){return make_node(X,c,{body:t})}}return _?i.skip:make_node(q,c)}}if(c instanceof Me&&!(h instanceof te&&h.init===c)){var b=!(h instanceof ae)&&!(c instanceof Ne);var y=[],k=[],S=[];var T=[];c.definitions.forEach(function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof pe;var i=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&i.global)return S.push(t);if(!(r||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(i.id)){if(t.value&&s.has(i.id)&&s.get(i.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof mt){var a=u.get(i.id);if(a.length>1&&(!t.value||i.orig.indexOf(t.name)>i.eliminated)){if(t.value){var l=make_node(Ft,t.name,t.name);i.references.push(l);var f=make_node(et,t,{operator:"=",logical:false,left:l,right:t.value});if(s.get(i.id)===t){s.set(i.id,f)}T.push(f.transform(p))}remove(a,t);i.eliminated++;return}}if(t.value){if(T.length>0){if(S.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{y.push(make_node(X,c,{body:make_sequence(c,T)}))}T=[]}S.push(t)}else{k.push(t)}}else if(i.orig[0]instanceof Ct){var _=t.value&&t.value.drop_side_effect_free(e);if(_)T.push(_);t.value=null;k.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){T.push(_)}i.eliminated++}});if(k.length>0||S.length>0){c.definitions=k.concat(S);y.push(c)}if(T.length>0){y.push(make_node(X,c,{body:make_sequence(c,T)}))}switch(y.length){case 0:return _?i.skip:make_node(q,c);case 1:return y[0];default:return _?i.splice(y):make_node(W,c,{body:y})}}if(c instanceof ee){f(c,this);var A;if(c.init instanceof W){A=c.init;c.init=A.body.pop();A.body.push(c)}if(c.init instanceof X){c.init=c.init.body}else if(is_empty(c.init)){c.init=null}return!A?c:_?i.splice(A.body):A}if(c instanceof j&&c.body instanceof ee){f(c,this);if(c.body instanceof W){var A=c.body;c.body=A.body.pop();A.body.push(c);return _?i.splice(A.body):A}return c}if(c instanceof W){f(c,this);if(_&&c.body.every(can_be_evicted_from_block)){return i.splice(c.body)}return c}if(c instanceof re){const e=l;l=c;f(c,this);l=e;return c}});t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Ft&&!is_ref_of(e.left,Et)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof et){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Ft){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Ct){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof re){var u=l;l=e;n();l=u;return true}}});re.DEFMETHOD("hoist_declarations",function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,e=>{if(e instanceof re&&e!==t)return true;if(e instanceof Ne){++u;return true}});i=i&&u>1;var c=new TreeTransformer(function before(u){if(u!==t){if(u instanceof G){r.push(u);return make_node(q,u)}if(n&&u instanceof fe&&!(c.parent()instanceof ze)&&c.parent()===t){a.push(u);return make_node(q,u)}if(i&&u instanceof Ne&&!u.definitions.some(e=>e.name instanceof pe)){u.definitions.forEach(function(e){o.set(e.name.name,e);++s});var l=u.to_assignments(e);var f=c.parent();if(f instanceof te&&f.init===u){if(l==null){var p=u.definitions[0].name;return make_node(Ft,p,p)}return l}if(f instanceof ee&&f.init===u){return l}if(!l)return make_node(q,u);return make_node(X,u,{body:l})}if(u instanceof re)return u}});t=t.transform(c);if(s>0){var l=[];const e=t instanceof se;const n=e?t.args_as_names():null;o.forEach((t,i)=>{if(e&&n.some(e=>e.name===t.name.name)){o.delete(i)}else{t=t.clone();t.value=null;l.push(t);o.set(i,t)}});if(l.length>0){for(var f=0;fe instanceof oe||e.computed_key())){s(o,this);const e=new Map;const n=[];l.properties.forEach(({key:i,value:r})=>{const s=find_scope(a);const c=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map(e=>e.scope)]),tentative_name:u.name+"_"+i});e.set(String(i),c.definition());n.push(make_node(Le,o,{name:c,value:r}))});r.set(c.id,e);return i.splice(n)}}else if(o instanceof He&&o.expression instanceof Ft){const e=r.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Ft,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}});return t.transform(a)});(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var h=n.body[n.body.length-1];if(h instanceof be&&t.loopcontrol_target(h)===e)n.body.pop();if(n.body.length||n instanceof xe&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(W,e,{body:a.concat(make_node(X,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var d=false;var m=new TreeWalker(function(t){if(d||t instanceof se||t instanceof X)return true;if(t instanceof be&&m.loopcontrol_target(t)===e)d=true});e.walk(m);if(!d){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(X,f,{body:f}));E.unshift(make_node(X,e.expression,{body:e.expression}));return make_node(W,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}});def_optimize(Oe,function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(W,e,{body:n}).optimize(t)}return e});Me.DEFMETHOD("remove_initializers",function(){var e=[];this.definitions.forEach(function(t){if(t.name instanceof dt){t.value=null;e.push(t)}else{walk(t.name,n=>{if(n instanceof dt){e.push(make_node(Le,t,{name:n,value:null}))}})}});this.definitions=e});Me.DEFMETHOD("to_assignments",function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Ft,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Le,e,{name:e.name,value:e.value});var a=make_node(Ne,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)});def_optimize(Me,function(e){if(e.definitions.length==0)return make_node(q,e);return e});def_optimize(Le,function(e){if(e.name instanceof vt&&e.value!=null&&is_undefined(e.value)){e.value=null}return e});def_optimize(Ve,function(e){return e});function retain_top_func(e,t){return t.top_retain&&e instanceof fe&&wn(e,On)&&e.name&&t.top_retain(e.name)}def_optimize(Ke,function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every(e=>!(e instanceof oe));if(t.option("reduce_vars")&&i instanceof Ft&&!has_annotation(e,en)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i)){return make_node(Ht,e)}var a=i instanceof se;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,c=e.args.length;u=i.argnames.length;if(f||wn(i.argnames[u],yn)){var l=e.args[u].drop_side_effect_free(t);if(l){e.args[o++]=l}else if(!f){e.args[o++]=make_node(Vt,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Vt&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every(e=>{var n=e.evaluate(t);p.push(n);return e!==n})){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(zt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof We)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Bt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var h=[];var d=[];for(var u=0,c=n.expression.elements.length;u0){h.push(make_node(Bt,e,{value:d.join(_)}));d.length=0}h.push(m)}}if(d.length>0){h.push(make_node(Bt,e,{value:d.join(_)}))}if(h.length==0)return make_node(Bt,e,{value:""});if(h.length==1){if(h[0].is_string(t)){return h[0]}return make_node(Qe,h[0],{operator:"+",left:make_node(Bt,e,{value:""}),right:h[0]})}if(_==""){var g;if(h[0].is_string(t)||h[1].is_string(t)){g=h.shift()}else{g=make_node(Bt,e,{value:""})}return h.reduce(function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})},g).optimize(t)}var l=e.clone();l.expression=l.expression.clone();l.expression.expression=l.expression.expression.clone();l.expression.expression.elements=h;return best_of(t,e,l)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(Ke,e,{expression:make_node(We,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Ft){y=y.fixed_value()}if(y instanceof se&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(Ke,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(Ke,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ce,e,{argnames:[],body:[]}).optimize(t);if(e.args.every(e=>e instanceof Bt)){try{var k="n(function("+e.args.slice(0,-1).map(function(e){return e.value}).join(",")+"){"+e.args[e.args.length-1].value+"})";var S=parse(k);var T={ie8:t.option("ie8")};S.figure_out_scope(T);var A=new Compressor(t.options,{mangle_options:t.mangle_options});S=S.transform(A);S.figure_out_scope(T);dn.reset();S.compute_char_frequency(T);S.mangle_names(T);var C;walk(S,e=>{if(is_func_expr(e)){C=e;return Zt}});var k=OutputStream();W.prototype._codegen.call(C,C,k);e.args=[make_node(Bt,e,{value:C.argnames.map(function(e){return e.print_to_string()}).join(",")}),make_node(Bt,e.args[e.args.length-1],{value:k.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=a&&i.body[0];var x=a&&!i.is_generator&&!i.async;var O=x&&t.option("inline")&&!e.is_expr_pure(t);if(O&&R instanceof ge){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(Ht,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof Dt&&e.args.length<2&&n instanceof Ft&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node(Ht)).optimize(t);let i;if(n instanceof He&&(i=t.parent())instanceof Ke&&i.expression===e){return make_sequence(e,[make_node(Vt,e,{value:0}),n])}return n}}if(O){var F,w,M=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof ct)&&!(i.name&&i instanceof ce)&&(o=can_flatten_body(R))&&(n===i||has_annotation(e,Jt)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,Qt|en)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(F instanceof ct)){Mn(i,Rn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(O&&has_annotation(e,Jt)){Mn(i,Rn);i=make_node(i.CTOR===fe?ce:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(Ke,e,{expression:i,args:e.args}).optimize(t)}const N=x&&t.option("side_effects")&&i.body.every(is_empty);if(N){var b=e.args.concat(make_node(Ht,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof X&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(Ht,e);if(t instanceof ge){if(!t.value)return make_node(Ht,e);return t.value.clone(true)}if(t instanceof X){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value)){return false}}else if(e){return false}else if(!(o instanceof q)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof pe||e.has(s.name)||Pn.has(s.name)||F.conflicting_def(s.name)){return false}if(w)w.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{F=t.parent(++M);if(F.is_block_scope()&&F.block_scope){F.block_scope.variables.forEach(function(t){e.add(t.name)})}if(F instanceof Fe){if(F.argname){e.add(F.argname.name)}}else if(F instanceof $){w=[]}else if(F instanceof Ft){if(F.fixed_value()instanceof re)return false}}while(!(F instanceof re));var n=!(F instanceof ae)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!w||w.length==0||!is_reachable(i,w)}function append_var(t,n,i,r){var a=i.definition();const o=F.variables.has(i.name);if(!o){F.variables.set(i.name,a);F.enclosed.push(a);t.push(make_node(Le,i,{name:i,value:null}))}var s=make_node(Ft,i,i);a.references.push(s);if(r)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(wn(o,yn)||!o.name||F.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(mt,o,o);o.definition().orig.push(u);if(!s&&w)s=make_node(Ht,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=l.name)){var f=i.variables.get(l.name);var p=make_node(Ft,l,l);f.references.push(p);t.splice(n++,0,make_node(et,c,{operator:"=",logical:false,left:p,right:make_node(Ht,l)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=F.body.indexOf(t.parent(M-1))+1;F.body.splice(e,0,make_node(Ne,i,{definitions:n}))}return r.map(e=>e.clone(true))}});def_optimize(Ge,function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(Ke,e,e).transform(t);return e});def_optimize(Xe,function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Xe))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach(function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this});var Wn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof se||e instanceof it||e instanceof ct}def_optimize(Qe,function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Wn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&M[e.left.operator]>=M[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(Gt,e.left)}else if(t.option("typeofs")&&e.left instanceof Bt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Ft?i.is_declared(t):!(i instanceof He&&t.option("ie8"))){e.right=i;e.left=make_node(Ht,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Ft&&e.right instanceof Ft&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?$t:jt,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof Qe&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof Gt||r.left instanceof Gt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(Qe,e,{operator:r.operator.slice(0,-1),left:make_node(Gt,e),right:r.right});if(r!==e.left){a=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node($t,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node($t,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Bt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Bt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Bt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=wn(e.left,kn)?true:wn(e.left,Sn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof U)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(jt,e)]).optimize(t)}else{Mn(e,Sn)}}else if(!(s instanceof U)){var c=t.parent();if(c.operator=="&&"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var l=e.left.right.evaluate(t);if(!l)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=wn(e.left,kn)?true:wn(e.left,Sn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof U)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var c=t.parent();if(c.operator=="||"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof U)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node($t,e)]).optimize(t)}else{Mn(e,kn)}}if(e.left.operator=="&&"){var l=e.left.right.evaluate(t);if(l&&!(l instanceof U))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof U)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof U)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Lt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var h=p.optimize(t);if(p!==h){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:h}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof he){var d=e.left;var _=e.right.evaluate(t);if(_!=e.right){d.segments[d.segments.length-1].value+=String(_);return d}}if(e.right instanceof he){var _=e.right;var d=e.left.evaluate(t);if(d!=e.left){_.segments[0].value=String(d)+_.segments[0].value;return _}}if(e.left instanceof he&&e.right instanceof he){var d=e.left;var m=d.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return d}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof Qe&&e.left.operator!=e.operator&&M[e.left.operator]>=M[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Lt&&!(e.left instanceof Lt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Lt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof Lt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof Lt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(Ln.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e});def_optimize(wt,function(e){return e});function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof se||n instanceof ct){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof z)return false;if(t instanceof nt||t instanceof at||t instanceof it){return true}}return false}def_optimize(Ft,function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ie)){switch(e.name){case"undefined":return make_node(Ht,e).optimize(t);case"NaN":return make_node(Xt,e).optimize(t);case"Infinity":return make_node(qt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof Ke&&n.is_expr_pure(t)||has_annotation(n,en))&&!(n instanceof ze&&s instanceof se&&s.name);if(u&&(s instanceof se||s instanceof ct)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||wn(s,An)||within_array_or_object_literal(t))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof Dt){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof fe||is_func_expr(i)){Mn(i,An)}}while(i=i.parent_scope)}}}if(u&&s instanceof se){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof Ke&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s instanceof ct){const e=!s.extends||!s.extends.may_throw(t)&&!s.extends.has_side_effects(t);u=e&&!s.properties.some(e=>e.may_throw(t)||e.has_side_effects(t))}if(u&&s){if(s instanceof ft){Mn(s,Rn);s=make_node(pt,s,s)}if(s instanceof fe){Mn(s,Rn);s=make_node(ce,s,s)}if(a.recursive_refs>0&&s.name instanceof bt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof St)){n=make_node(St,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,n=>{if(n instanceof Ft&&n.definition()===e){n.thedef=t;t.references.push(n)}})}if((s instanceof se||s instanceof ct)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof It){if(!(a.orig[0]instanceof Dt)&&a.references.every(e=>a.scope===e.scope)){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e});function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Ft||e.TYPE===t.TYPE}def_optimize(Ht,function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Ft,e,{name:"undefined",scope:n.scope,thedef:n});Mn(i,Tn);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Vt,e,{value:0})})});def_optimize(qt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Vt,e,{value:1}),right:make_node(Vt,e,{value:0})})});def_optimize(Xt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Vt,e,{value:0}),right:make_node(Vt,e,{value:0})})}return e});function is_reachable(e,t){const n=e=>{if(e instanceof Ft&&member(e.definition(),t)){return Zt}};return walk_parent(e,(t,i)=>{if(t instanceof re&&t!==e){var r=i.parent();if(r instanceof Ke&&r.expression===t)return;if(walk(t,n))return Zt;return true}})}const qn=makePredicate("+ - / * % >> << >>> | ^ &");const Yn=makePredicate("* | ^ &");def_optimize(et,function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Ft&&(n=e.left.definition()).scope===t.find_parent(se)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof Ee){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof Qe&&a.right===r||a instanceof Xe&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Ft&&e.right instanceof Qe){if(e.right.left instanceof Ft&&e.right.left.name==e.left.name&&qn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Ft&&e.right.right.name==e.left.name&&Yn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(Gt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Oe){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}});def_optimize(tt,function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e});function is_nullish(e){let t;return e instanceof Gt||is_undefined(e)||e instanceof Ft&&(t=e.definition().fixed)instanceof U&&is_nullish(t)||e instanceof He&&e.optional&&is_nullish(e.expression)||e instanceof Ke&&e.optional&&is_nullish(e.expression)||e instanceof Ye&&is_nullish(e.expression)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof Qe&&e.operator==="=="&&((i=is_nullish(e.left)&&e.left)||(i=is_nullish(e.right)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let n;let i;const r=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let r=0;let a;if(e.left instanceof Gt){r++;n=e;a=e.right}if(e.right instanceof Gt){r++;n=e;a=e.left}if(is_undefined(e.left)){r++;i=e;a=e.right}if(is_undefined(e.right)){r++;i=e;a=e.left}if(r!==1){return false}if(!a.equivalent_to(t)){return false}return true};if(!r(e.left))return false;if(!r(e.right))return false;if(n&&i&&n!==i){return true}}return false}def_optimize(Je,function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Xe){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(Je,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Ft&&o instanceof Ft&&a.definition()===o.definition()){return make_node(Qe,e,{operator:"||",left:a,right:s})}if(o instanceof et&&s instanceof et&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(et,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(Je,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof Ke&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var c=o.clone();c.args[u]=make_node(Je,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return c}if(s instanceof Je&&o.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof Xe&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof Je&&o.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof Qe&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var l=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof $t||l&&e instanceof Lt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Lt&&!e.expression.getValue()}function is_false(e){return e instanceof jt||l&&e instanceof Lt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Lt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof it){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof ut?o.key.name:o.key)==e){if(!r.every(e=>{return e instanceof at||n&&e instanceof ut&&!e.is_generator}))break;if(!safe_to_flatten(o.value,t))break;return make_node(qe,this,{expression:make_node(nt,i,{elements:r.map(function(e){var t=e.value;if(t instanceof ue)t=make_node(ce,t,t);var n=e.key;if(n instanceof U&&!(n instanceof yt)){return make_sequence(e,[n,t])}return t})}),property:make_node(Vt,this,{value:a})})}}}});def_optimize(qe,function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(We,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Ft&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof se&&s.uses_arguments&&!(s instanceof le)&&i instanceof Vt){var u=i.getValue();var c=new Set;var l=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(Dt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var d=make_node(Ft,e,_);d.reference({});Nn(_,yn);return d}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Vt&&n instanceof nt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var a=E[b].drop_side_effect_free(t);if(a){D.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof oe)break e;g=g instanceof Wt?make_node(Ht,g):g;if(!v)D.unshift(g);while(--b>=0){var a=E[b];if(a instanceof oe)break e;a=a.drop_side_effect_free(t);if(a)D.unshift(a);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:D}),property:make_node(Vt,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression)){return make_node(Ht,e)}return e});def_optimize(Ye,function(e,t){e.expression=e.expression.optimize(t);return e});se.DEFMETHOD("contains_this",function(){return walk(this,e=>{if(e instanceof It)return Zt;if(e!==this&&e instanceof re&&!(e instanceof le)){return true}})});def_optimize(We,function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof We&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ce,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Vt,e.expression,{value:0});break;case"Object":e.expression=make_node(it,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(zt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Bt,e.expression,{value:""});break}}if(!(n instanceof Ke)||!has_annotation(n,en)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression)){return make_node(Ht,e)}return e});function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node($t,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Wt)){e.splice(t,1,...i.elements);t--}}}}def_optimize(nt,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e});function inline_object_prop_spread(e){for(var t=0;te instanceof at)){e.splice(t,1,...i.properties);t--}else if(i instanceof Lt&&!(i instanceof Bt)){e.splice(t,1)}}}}def_optimize(it,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties);return e});def_optimize(zt,literals_in_boolean_context);def_optimize(ge,function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(le,opt_AST_Lambda);def_optimize(ce,function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,e=>{if(e instanceof It)return Zt});if(!n)return make_node(le,e,e).optimize(t)}return e});def_optimize(ct,function(e){return e});def_optimize(Se,function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e});def_optimize(he,function(e,t){if(!t.option("evaluate")||t.parent()instanceof _e){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof le&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof ce)&&!r.name){return make_node(ut,e,{async:r.async,is_generator:r.is_generator,key:i instanceof U?i:make_node(yt,e,{name:i}),value:make_node(ue,r,r),quote:e.quote})}}return e});def_optimize(pe,function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof oe)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){dn.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof ae){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Zn(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format beautify=true.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach(function(t){if(t in e){s[t]=e[t]}});if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.beautify||e.format){if(e.beautify&&e.format){fatal("Please only specify one of --beautify or --format")}if(e.beautify){s.format=typeof e.beautify=="object"?e.beautify:{};if(!("beautify"in s.format)){s.format.beautify=true}}if(e.format){s.format=typeof e.format=="object"?e.format:{}}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var c in e.define){s.compress.global_defs[c]=e.define[c]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let l=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){l=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let f;if(s.files&&s.files.length){f=s.files;delete s.files}else if(e.args.length){f=e.args}if(f){simple_glob(f).forEach(function(e){o[l(e)]=read_file(e)})}else{await new Promise(e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",function(e){t.push(e)}).on("end",function(){o=[t.join("")];e()});process.stdin.resume()})}await run_cli();function convert_ast(e){return U.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast(function(t,i){return n(89).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})})}else if(e.parse.spidermonkey){o=convert_ast(function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e})}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var c=o[e.filename].split(/\r?\n/);var l=c[e.line-1];if(!l&&!u){l=c[e.line-2];u=l.length}if(l){var f=70;if(u>f){l=l.slice(u-f);u=f}print_error(l.slice(0,80));print_error(l.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"functions":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof U){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.functions=t.block_scope.functions;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach(function(e){n[e]=t[e]});return n}return t},2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter(function(e){return s.test(e)}).map(function(e){return r.join(t,e)});if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),t=>{if(t instanceof et){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof nt){n[i]=r.elements.map(to_string)}else if(r instanceof zt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof _t||t instanceof He){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof Xe))throw t;function to_string(e){return e instanceof Lt?e.getValue():e.print_to_string({quote_keys:true})}})}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach(function(e){n.push(t(e))});return n}function format_object(e){var t=[];var n="";Object.keys(e).map(function(t){if(n.length!/^\$/.test(e));if(n.length>0){e.space();e.with_parens(function(){n.forEach(function(t,n){if(n)e.space();e.print(t)})})}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block(function(){t.SUBCLASSES.forEach(function(t){e.indent();doitem(t);e.newline()})})}}doitem(U);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach(t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n});return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify})},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __nccwpck_require__(n){if(t[n]){return t[n].exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);r=false}finally{if(r)delete t[n]}return i.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(845)})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack/bundle4.js b/packages/next/compiled/webpack/bundle4.js index d43f5915fdd08..abb768670e01f 100644 --- a/packages/next/compiled/webpack/bundle4.js +++ b/packages/next/compiled/webpack/bundle4.js @@ -51765,207 +51765,7 @@ module.exports = function normalize(path) { /***/ }), -/***/ 4870: -/***/ (function(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: -/***/ (function(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); -}; - - -/***/ }), - -/***/ 50998: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -var path = __webpack_require__(85622); -var fs = __webpack_require__(35747); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; - - -/***/ }), - -/***/ 57925: +/***/ 53024: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51976,17 +51776,18 @@ mkdirP.sync = function sync (p, opts, made) { */ var util = __webpack_require__(31669); +var braces = __webpack_require__(50559); var toRegex = __webpack_require__(51279); -var extend = __webpack_require__(69148); +var extend = __webpack_require__(3767); /** * Local dependencies */ -var compilers = __webpack_require__(4756); -var parsers = __webpack_require__(5333); -var cache = __webpack_require__(58250); -var utils = __webpack_require__(41340); +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; /** @@ -51994,10 +51795,10 @@ var MAX_LENGTH = 1024 * 64; * glob patterns to use for matching. * * ```js - * var nm = require('nanomatch'); - * nm(list, patterns[, options]); + * var mm = require('micromatch'); + * mm(list, patterns[, options]); * - * console.log(nm(['a.js', 'a.txt'], ['*.js'])); + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {Array} `list` A list of strings to match @@ -52008,7 +51809,7 @@ var MAX_LENGTH = 1024 * 64; * @api public */ -function nanomatch(list, patterns, options) { +function micromatch(list, patterns, options) { patterns = utils.arrayify(patterns); list = utils.arrayify(list); @@ -52018,10 +51819,9 @@ function nanomatch(list, patterns, options) { } if (len === 1) { - return nanomatch.match(list, patterns[0], options); + return micromatch.match(list, patterns[0], options); } - var negated = false; var omit = []; var keep = []; var idx = -1; @@ -52030,22 +51830,9 @@ function nanomatch(list, patterns, options) { 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(); + omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); } else { - var unixify = utils.unixify(options); - for (var i = 0; i < list.length; i++) { - keep.push(unixify(list[i])); - } + keep.push.apply(keep, micromatch.match(list, pattern, options)); } } @@ -52061,10 +51848,10 @@ function nanomatch(list, patterns, options) { * Similar to the main function, but `pattern` must be a string. * * ```js - * var nm = require('nanomatch'); - * nm.match(list, pattern[, options]); + * var mm = require('micromatch'); + * mm.match(list, pattern[, options]); * - * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * 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 @@ -52074,13 +51861,13 @@ function nanomatch(list, patterns, options) { * @api public */ -nanomatch.match = function(list, pattern, options) { +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, nanomatch.matcher); + var isMatch = memoize('match', pattern, options, micromatch.matcher); var matches = []; list = utils.arrayify(list); @@ -52110,7 +51897,7 @@ nanomatch.match = function(list, pattern, options) { // if `opts.ignore` was defined, diff ignored list if (options.ignore) { - matches = nanomatch.not(matches, options.ignore, options); + matches = micromatch.not(matches, options.ignore, options); } return options.nodupes !== false ? utils.unique(matches) : matches; @@ -52120,12 +51907,12 @@ nanomatch.match = function(list, pattern, options) { * Returns true if the specified `string` matches the given glob `pattern`. * * ```js - * var nm = require('nanomatch'); - * nm.isMatch(string, pattern[, options]); + * var mm = require('micromatch'); + * mm.isMatch(string, pattern[, options]); * - * console.log(nm.isMatch('a.a', '*.a')); + * console.log(mm.isMatch('a.a', '*.a')); * //=> true - * console.log(nm.isMatch('a.b', '*.a')); + * console.log(mm.isMatch('a.b', '*.a')); * //=> false * ``` * @param {String} `string` String to match @@ -52135,12 +51922,12 @@ nanomatch.match = function(list, pattern, options) { * @api public */ -nanomatch.isMatch = function(str, pattern, options) { +micromatch.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)) { + if (isEmptyString(str) || isEmptyString(pattern)) { return false; } @@ -52149,21 +51936,21 @@ nanomatch.isMatch = function(str, pattern, options) { return true; } - var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); + var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); return isMatch(str); }; /** - * Returns true if some of the elements in the given `list` match any of the + * Returns true if some of the strings in the given `list` match any of the * given glob `patterns`. * * ```js - * var nm = require('nanomatch'); - * nm.some(list, patterns[, options]); + * var mm = require('micromatch'); + * mm.some(list, patterns[, options]); * - * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true - * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); + * 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. @@ -52173,35 +51960,33 @@ nanomatch.isMatch = function(str, pattern, options) { * @api public */ -nanomatch.some = function(list, patterns, options) { +micromatch.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) { + if (micromatch(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`. + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. * * ```js - * var nm = require('nanomatch'); - * nm.every(list, patterns[, options]); + * var mm = require('micromatch'); + * mm.every(list, patterns[, options]); * - * console.log(nm.every('foo.js', ['foo.js'])); + * console.log(mm.every('foo.js', ['foo.js'])); * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false - * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. @@ -52211,17 +51996,15 @@ nanomatch.some = function(list, patterns, options) { * @api public */ -nanomatch.every = function(list, patterns, options) { +micromatch.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) { + if (micromatch(list[i], patterns, options).length !== 1) { return false; } } - return true; }; @@ -52230,12 +52013,12 @@ nanomatch.every = function(list, patterns, options) { * match the specified `string`. * * ```js - * var nm = require('nanomatch'); - * nm.any(string, patterns[, options]); + * var mm = require('micromatch'); + * mm.any(string, patterns[, options]); * - * console.log(nm.any('a.a', ['b.*', '*.a'])); + * console.log(mm.any('a.a', ['b.*', '*.a'])); * //=> true - * console.log(nm.any('a.a', 'b.*')); + * console.log(mm.any('a.a', 'b.*')); * //=> false * ``` * @param {String|Array} `str` The string to test. @@ -52245,12 +52028,12 @@ nanomatch.every = function(list, patterns, options) { * @api public */ -nanomatch.any = function(str, patterns, options) { +micromatch.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)) { + if (isEmptyString(str) || isEmptyString(patterns)) { return false; } @@ -52259,7 +52042,7 @@ nanomatch.any = function(str, patterns, options) { } for (var i = 0; i < patterns.length; i++) { - if (nanomatch.isMatch(str, patterns[i], options)) { + if (micromatch.isMatch(str, patterns[i], options)) { return true; } } @@ -52267,23 +52050,23 @@ nanomatch.any = function(str, patterns, options) { }; /** - * Returns true if **all** of the given `patterns` - * match the specified string. + * Returns true if **all** of the given `patterns` match + * the specified string. * * ```js - * var nm = require('nanomatch'); - * nm.all(string, patterns[, options]); + * var mm = require('micromatch'); + * mm.all(string, patterns[, options]); * - * console.log(nm.all('foo.js', ['foo.js'])); + * console.log(mm.all('foo.js', ['foo.js'])); * // true * - * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * - * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * - * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. @@ -52293,17 +52076,15 @@ nanomatch.any = function(str, patterns, options) { * @api public */ -nanomatch.all = function(str, patterns, options) { +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 (!nanomatch.isMatch(str, patterns[i], options)) { + if (!micromatch.isMatch(str, patterns[i], options)) { return false; } } @@ -52314,10 +52095,10 @@ nanomatch.all = function(str, patterns, options) { * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js - * var nm = require('nanomatch'); - * nm.not(list, patterns[, options]); + * var mm = require('micromatch'); + * mm.not(list, patterns[, options]); * - * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. @@ -52327,16 +52108,17 @@ nanomatch.all = function(str, patterns, options) { * @api public */ -nanomatch.not = function(list, patterns, options) { +micromatch.not = function(list, patterns, options) { var opts = extend({}, options); var ignore = opts.ignore; delete opts.ignore; - list = utils.arrayify(list); + var unixify = utils.unixify(opts); + list = utils.arrayify(list).map(unixify); - var matches = utils.diff(list, nanomatch(list, patterns, opts)); + var matches = utils.diff(list, micromatch(list, patterns, opts)); if (ignore) { - matches = utils.diff(matches, nanomatch(list, ignore)); + matches = utils.diff(matches, micromatch(list, ignore)); } return opts.nodupes !== false ? utils.unique(matches) : matches; @@ -52347,12 +52129,12 @@ nanomatch.not = function(list, patterns, options) { * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js - * var nm = require('nanomatch'); - * nm.contains(string, pattern[, options]); + * var mm = require('micromatch'); + * mm.contains(string, pattern[, options]); * - * console.log(nm.contains('aa/bb/cc', '*b')); + * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true - * console.log(nm.contains('aa/bb/cc', '*d')); + * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. @@ -52362,13 +52144,13 @@ nanomatch.not = function(list, patterns, options) { * @api public */ -nanomatch.contains = function(str, patterns, options) { +micromatch.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)) { + if (isEmptyString(str) || isEmptyString(patterns)) { return false; } @@ -52383,7 +52165,7 @@ nanomatch.contains = function(str, patterns, options) { } var opts = extend({}, options, {contains: true}); - return nanomatch.any(str, patterns, opts); + return micromatch.any(str, patterns, opts); }; /** @@ -52393,7 +52175,7 @@ nanomatch.contains = function(str, patterns, options) { * @api private */ -nanomatch.matchBase = function(pattern, options) { +micromatch.matchBase = function(pattern, options) { if (pattern && pattern.indexOf('/') !== -1 || !options) return false; return options.basename === true || options.matchBase === true; }; @@ -52404,11 +52186,11 @@ nanomatch.matchBase = function(pattern, options) { * use [glob-object][] instead. * * ```js - * var nm = require('nanomatch'); - * nm.matchKeys(object, patterns[, options]); + * var mm = require('micromatch'); + * mm.matchKeys(object, patterns[, options]); * * var obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(nm.matchKeys(obj, '*b')); + * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. @@ -52418,11 +52200,11 @@ nanomatch.matchBase = function(pattern, options) { * @api public */ -nanomatch.matchKeys = function(obj, patterns, options) { +micromatch.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); + var keys = micromatch(Object.keys(obj), patterns, options); return utils.pick(obj, keys); }; @@ -52432,10 +52214,10 @@ nanomatch.matchKeys = function(obj, patterns, options) { * true if the string is a match. * * ```js - * var nm = require('nanomatch'); - * nm.matcher(pattern[, options]); + * var mm = require('micromatch'); + * mm.matcher(pattern[, options]); * - * var isMatch = nm.matcher('*.!(*a)'); + * var isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); * //=> false * console.log(isMatch('a.b')); @@ -52447,13 +52229,7 @@ nanomatch.matchKeys = function(obj, patterns, options) { * @api public */ -nanomatch.matcher = function matcher(pattern, options) { - if (utils.isEmptyString(pattern)) { - return function() { - return false; - }; - } - +micromatch.matcher = function matcher(pattern, options) { if (Array.isArray(pattern)) { return compose(pattern, options, matcher); } @@ -52477,10 +52253,10 @@ nanomatch.matcher = function matcher(pattern, options) { } // if pattern is a glob string - var re = nanomatch.makeRe(pattern, options); + var re = micromatch.makeRe(pattern, options); // if `options.matchBase` or `options.basename` is defined - if (nanomatch.matchBase(pattern, options)) { + if (micromatch.matchBase(pattern, options)) { return utils.matchBasename(re, options); } @@ -52500,25 +52276,25 @@ nanomatch.matcher = function matcher(pattern, options) { }; } - // 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; + 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. + * 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]); + * var mm = require('micromatch'); + * mm.capture(pattern, string[, options]); * - * console.log(nm.capture('test/*.js', 'test/foo.js')); + * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] - * console.log(nm.capture('test/*.js', 'foo/bar.css')); + * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `pattern` Glob pattern to use for matching. @@ -52528,8 +52304,8 @@ nanomatch.matcher = function matcher(pattern, options) { * @api public */ -nanomatch.capture = function(pattern, str, options) { - var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); +micromatch.capture = function(pattern, str, options) { + var re = micromatch.makeRe(pattern, extend({capture: true}, options)); var unixify = utils.unixify(options); function match() { @@ -52551,10 +52327,10 @@ nanomatch.capture = function(pattern, str, options) { * Create a regular expression from the given glob `pattern`. * * ```js - * var nm = require('nanomatch'); - * nm.makeRe(pattern[, options]); + * var mm = require('micromatch'); + * mm.makeRe(pattern[, options]); * - * console.log(nm.makeRe('*.js')); + * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. @@ -52563,11 +52339,7 @@ nanomatch.capture = function(pattern, str, options) { * @api public */ -nanomatch.makeRe = function(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } - +micromatch.makeRe = function(pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('expected pattern to be a string'); } @@ -52577,10 +52349,20 @@ nanomatch.makeRe = function(pattern, options) { } 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); + 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; } @@ -52588,15 +52370,58 @@ nanomatch.makeRe = function(pattern, options) { }; /** - * Parses the given glob `pattern` and returns an object with the compiled `output` - * and optional source `map`. + * Expand the given brace `pattern`. * * ```js - * var nm = require('nanomatch'); - * nm.create(pattern[, options]); + * var mm = require('micromatch'); + * console.log(mm.braces('foo/{a,b}/bar')); + * //=> ['foo/(a|b)/bar'] * - * console.log(nm.create('abc/*.js')); - * // { options: { source: 'string', sourcemap: true }, + * 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: * // { ... }, @@ -52618,7 +52443,7 @@ nanomatch.makeRe = function(pattern, options) { * // position: { line: 1, column: 28 }, * // content: {}, * // files: {}, - * // idx: 6 } + * // 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. @@ -52626,24 +52451,32 @@ nanomatch.makeRe = function(pattern, options) { * @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); +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 nm = require('nanomatch'); - * nm.parse(pattern[, options]); + * var mm = require('micromatch'); + * mm.parse(pattern[, options]); * - * var ast = nm.parse('a/{b,c}/d'); + * var ast = mm.parse('a/{b,c}/d'); * console.log(ast); * // { type: 'root', * // errors: [], @@ -52665,7 +52498,7 @@ nanomatch.create = function(pattern, options) { * @api public */ -nanomatch.parse = function(pattern, options) { +micromatch.parse = function(pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('expected a string'); } @@ -52687,11 +52520,11 @@ nanomatch.parse = function(pattern, options) { * Compile the given `ast` or string with the given `options`. * * ```js - * var nm = require('nanomatch'); - * nm.compile(ast[, options]); + * var mm = require('micromatch'); + * mm.compile(ast[, options]); * - * var ast = nm.parse('a/{b,c}/d'); - * console.log(nm.compile(ast)); + * var ast = mm.parse('a/{b,c}/d'); + * console.log(mm.compile(ast)); * // { options: { source: 'string' }, * // state: {}, * // compilers: @@ -52713,33 +52546,39 @@ nanomatch.parse = function(pattern, options) { * @api public */ -nanomatch.compile = function(ast, options) { +micromatch.compile = function(ast, options) { if (typeof ast === 'string') { - ast = nanomatch.parse(ast, options); + ast = micromatch.parse(ast, options); } - function compile() { + return memoize('compile', ast.input, options, function() { 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(); + * mm.clearCache(); * ``` * @api public */ -nanomatch.clearCache = function() { - nanomatch.cache.__data__ = {}; +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 @@ -52794,24 +52633,24 @@ function memoize(type, pattern, options, fn) { } /** - * Expose compiler, parser and cache on `nanomatch` + * Expose compiler, parser and cache on `micromatch` */ -nanomatch.compilers = compilers; -nanomatch.parsers = parsers; -nanomatch.cache = cache; +micromatch.compilers = compilers; +micromatch.parsers = parsers; +micromatch.caches = cache.caches; /** - * Expose `nanomatch` + * Expose `micromatch` * @type {Function} */ -module.exports = nanomatch; +module.exports = micromatch; /***/ }), -/***/ 58250: +/***/ 34743: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { module.exports = new (__webpack_require__(49908))(); @@ -52819,19584 +52658,16291 @@ module.exports = new (__webpack_require__(49908))(); /***/ }), -/***/ 4756: -/***/ (function(module) { +/***/ 26113: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/** -* Nanomatch compilers -*/ +var nanomatch = __webpack_require__(57925); +var extglob = __webpack_require__(66675); -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 '\\\\/'; - } +module.exports = function(snapdragon) { + var compilers = snapdragon.compiler.compilers; + var opts = snapdragon.options; - function star() { - if (options && typeof options.star === 'string') { - return options.star; - } - if (options && typeof options.star === 'function') { - return options.star.call(nanomatch); - } - return '[^' + slash() + ']*?'; + // 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); } - var ast = nanomatch.ast = nanomatch.parser.ast; - ast.state = nanomatch.parser.state; - nanomatch.compiler.state = ast.state; - nanomatch.compiler + snapdragon.use(function() { + this.options.star = this.options.star || function(/*node*/) { + return '[^\\\\/]*?'; + }; + }); - /** - * Negation / escaping - */ + // custom micromatch compilers + snapdragon.compiler - .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); - }) + // reset referenced compiler + .set('dot', dot) + .set('escape', escape) + .set('plus', plus) + .set('slash', slash) + .set('qmark', qmark) + .set('star', star) + .set('text', text); +}; - /** - * Regex - */ +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); + }); - .set('dollar', function(node) { - if (node.parent.type === 'bracket') { - return this.emit(node.val, node); - } - return this.emit('\\' + node.val, node); - }) + /** + * Visit `node` with the given `fn` + */ - /** - * Dot: "." - */ + function visit(node, fn) { + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } - .set('dot', function(node) { - if (node.dotfiles === true) this.dotfiles = true; - return this.emit('\\' + node.val, node); - }) + /** + * Map visit over array of `nodes`. + */ - /** - * Slashes: "/" and "\" - */ + function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } + } +} - .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 += '?'; - } +/***/ 14086: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // word boundary - if (node.rest.slice(0, 2) === '\\b') { - return this.emit(val, node); - } +"use strict"; - // 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); - }) +var extglob = __webpack_require__(66675); +var nanomatch = __webpack_require__(57925); +var regexNot = __webpack_require__(30931); +var toRegex = __webpack_require__(51279); +var not; - /** - * Square brackets - */ +/** + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) + */ - .set('bracket', function(node) { - var close = node.close; - var open = !node.escaped ? '[' : '\\['; - var negated = node.negated; - var inner = node.inner; - var val = node.val; +var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; +var createNotRegex = function(opts) { + return not || (not = textRegex(TEXT)); +}; - if (node.escaped === true) { - inner = inner.replace(/\\?(\W)/g, '\\$1'); - negated = ''; - } +/** + * Parsers + */ - if (inner === ']-') { - inner = '\\]\\-'; - } +module.exports = function(snapdragon) { + var parsers = snapdragon.parser.parsers; - if (negated && inner.indexOf('.') === -1) { - inner += '.'; - } - if (negated && inner.indexOf('/') === -1) { - inner += '/'; - } + // register nanomatch parsers + snapdragon.use(nanomatch.parsers); - val = open + negated + inner + close; - return this.emit(val, node); - }) + // 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; - /** - * Square: "[.]" (only matches a single character in brackets) - */ + // register extglob parsers + snapdragon.use(extglob.parsers); - .set('square', function(node) { - var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; - return this.emit(val, node); + // 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) /** - * Question mark: "?" + * Override `text` parser */ - .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); - }) + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(createNotRegex(this.options)); + if (!m || !m[0]) return; - /** - * Plus - */ + // escape regex boundary characters and simple brackets + var val = m[0].replace(/([[\]^$])/g, '\\$1'); - .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); - }) + return pos({ + type: 'text', + val: val + }); + }); +}; - /** - * globstar: '**' - */ +/** + * Create text regex + */ - .set('globstar', function(node, nodes, i) { - if (!this.output) { - this.state.leadingGlobstar = true; - } +function textRegex(pattern) { + var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); + var prefix = '(?:[\\^]|\\\\|'; + return toRegex(prefix + notStr + ')', {strictClose: false}); +} - 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'; - } - } - } +/***/ 63976: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var parsed = node.parsed; - if (parsed.charAt(0) === '!') { - parsed = parsed.slice(1); - } +"use strict"; - 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; - } +var utils = module.exports; +var path = __webpack_require__(85622); - if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { - if (after.type === 'text' || after.type === 'star') { - node.addQmark = true; - } - } +/** + * Module dependencies + */ - if (this.options.capture) { - val = '(' + val + ')'; - } +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); - return this.emit(val, node); - }) +/** + * 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} + */ - /** - * Star: "*" - */ +utils.isWindows = function() { + return path.sep === '\\' || process.platform === 'win32'; +}; - .set('star', function(node, nodes, i) { - var prior = nodes[i - 2] || {}; - var prev = this.prev(); - var next = this.next(); - var type = prev.type; +/** + * Get the `Snapdragon` instance to use + */ - function isStart(n) { - return n.type === 'bos' || n.type === 'slash'; - } +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); + } - if (this.output === '' && this.options.contains !== true) { - this.output = '(?![' + slash() + '])'; - } + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; - 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); + // 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; } - } - - 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 { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; } - } else if (prefix === '(?!\\.)') { - prefix = ''; } + } - if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { - this.output = '(?!\\.)' + this.output; - } + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); - var output = prefix + star(); - if (this.options.capture) { - output = '(' + output + ')'; - } + return snapdragon; +}; - return this.emit(output, node); - }) - - /** - * Text - */ +/** + * 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. + */ - .set('text', function(node) { - return this.emit(node.val, node); - }) +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; +}; - /** - * End-of-string - */ +/** + * Cast `val` to an array + * @return {Array} + */ - .set('eos', function(node) { - var prev = this.prev(); - var val = node.val; +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; - this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; - if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { - val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); - } +/** + * Return true if `val` is a non-empty string + */ - return this.emit(val, node); - }); +utils.isString = function(val) { + return typeof val === 'string'; +}; - /** - * Allow custom compilers to be passed on options - */ +/** + * Return true if `val` is a non-empty string + */ - if (options && typeof options.compilers === 'function') { - options.compilers(nanomatch.compiler); - } +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); +}; -/***/ }), - -/***/ 5333: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Escape regex characters in the given string + */ -"use strict"; +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); +}; +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ -var regexNot = __webpack_require__(30931); -var toRegex = __webpack_require__(51279); +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; /** - * Characters to use in negation regex (we want to "not" match - * characters that are matched by other parsers) + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} */ -var cached; -var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; -var not = createTextRegex(NOT_REGEX); +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; /** - * Nanomatch parsers + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} */ -module.exports = function(nanomatch, options) { - var parser = nanomatch.parser; - var opts = parser.options; +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; +}; - parser.state = { - slashes: 0, - paths: [] - }; +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ - parser.ast.state = parser.state; - parser +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; - /** - * Beginning-of-string - */ +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - .capture('prefix', function() { - if (this.parsed) return; - var m = this.match(/^\.[\\/]/); - if (!m) return; - this.state.strictOpen = !!this.options.strictOpen; - this.state.addPrefix = true; - }) +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; - /** - * Escape: "\\." - */ +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ - .capture('escape', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^(?:\\(.)|([$^]))/); - if (!m) return; +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; - return pos({ - type: 'escape', - val: m[2] || m[1] - }); - }) +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ - /** - * Quoted strings - */ +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; - .capture('quoted', function() { - var pos = this.position(); - var m = this.match(/^["']/); - if (!m) return; +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - var quote = m[0]; - if (this.input.indexOf(quote) === -1) { - return pos({ - type: 'escape', - val: quote - }); - } +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - var tok = advanceTo(this.input, quote); - this.consume(tok.len); + 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); + }; +}; - return pos({ - type: 'quoted', - val: tok.esc - }); - }) +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - /** - * Negations: "!" - */ +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - .capture('not', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(this.notRegex || /^!+/); - if (!m) return; - var val = m[0]; + 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); + }; +}; - var isNegated = (val.length % 2) === 1; - if (parsed === '' && !isNegated) { - val = ''; - } +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ - // 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 - }); - }) +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(path.basename(filepath)); + }; +}; - /** - * Dot: "." - */ +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ - .capture('dot', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\.+/); - if (!m) return; +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + return unixify(str); +}; - var val = m[0]; - this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ - return pos({ - type: 'dot', - dotfiles: this.state.dot, - val: val - }); - }) +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; + }; +}; - /** - * Plus: "+" - */ - .capture('plus', /^\+(?!\()/) +/***/ }), - /** - * Question mark: "?" - */ +/***/ 50559: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - .capture('qmark', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\?+(?!\()/); - if (!m) return; +"use strict"; - this.state.metachar = true; - this.state.qmark = true; - return pos({ - type: 'qmark', - parsed: parsed, - val: m[0] - }); - }) +/** + * Module dependencies + */ - /** - * Globstar: "**" - */ +var toRegex = __webpack_require__(51279); +var unique = __webpack_require__(19009); +var extend = __webpack_require__(92845); - .capture('globstar', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); - if (!m) return; +/** + * Local dependencies + */ - var type = opts.noglobstar !== true ? 'globstar' : 'star'; - var node = pos({type: type, parsed: parsed}); - this.state.metachar = true; +var compilers = __webpack_require__(90808); +var parsers = __webpack_require__(46362); +var Braces = __webpack_require__(12638); +var utils = __webpack_require__(38640); +var MAX_LENGTH = 1024 * 64; +var cache = {}; - while (this.input.slice(0, 4) === '/**/') { - this.input = this.input.slice(3); - } +/** + * 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 + */ - node.isInside = { - brace: this.isInside('brace'), - paren: this.isInside('paren') - }; +function braces(pattern, options) { + var key = utils.createKey(String(pattern), options); + var arr = []; - if (type === 'globstar') { - this.state.globstar = true; - node.val = '**'; + var disabled = options && options.cache === false; + if (!disabled && cache.hasOwnProperty(key)) { + return cache[key]; + } - } else { - this.state.star = true; - node.val = '*'; - } + 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); + } - return node; - }) + if (options && options.nodupes === true) { + arr = unique(arr); + } - /** - * Star: "*" - */ + if (!disabled) { + cache[key] = arr; + } + return arr; +} - .capture('star', function() { - var pos = this.position(); - var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; - var m = this.match(starRe); - if (!m) return; +/** + * 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 + */ - this.state.metachar = true; - this.state.star = true; - return pos({ - type: 'star', - val: m[0] - }); - }) +braces.expand = function(pattern, options) { + return braces.create(pattern, extend({}, options, {expand: true})); +}; - /** - * Slash: "/" - */ +/** + * 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 + */ - .capture('slash', function() { - var pos = this.position(); - var m = this.match(/^\//); - if (!m) return; +braces.optimize = function(pattern, options) { + return braces.create(pattern, options); +}; - this.state.slashes++; - return pos({ - type: 'slash', - val: m[0] - }); - }) +/** + * 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 + */ - /** - * Backslash: "\\" - */ +braces.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } - .capture('backslash', function() { - var pos = this.position(); - var m = this.match(/^\\(?![*+?(){}[\]'"])/); - if (!m) return; + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); + } - var val = m[0]; + function create() { + if (pattern === '' || pattern.length < 3) { + return [pattern]; + } - if (this.isInside('bracket')) { - val = '\\'; - } else if (val.length > 1) { - val = '\\\\'; - } + if (utils.isEmptySets(pattern)) { + return []; + } - return pos({ - type: 'backslash', - val: val - }); - }) + if (utils.isQuotedString(pattern)) { + return [pattern.slice(1, -1)]; + } - /** - * Square: "[.]" - */ + var proto = new Braces(options); + var result = !options || options.expand !== true + ? proto.optimize(pattern, options) + : proto.expand(pattern, options); - .capture('square', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^\[([^!^\\])\]/); - if (!m) return; + // get the generated pattern(s) + var arr = result.output; - return pos({ - type: 'square', - val: m[1] - }); - }) + // filter out empty strings if specified + if (options && options.noempty === true) { + arr = arr.filter(Boolean); + } - /** - * Brackets: "[...]" (basic, this can be overridden by other parsers) - */ + // filter out duplicates if specified + if (options && options.nodupes === true) { + arr = unique(arr); + } - .capture('bracket', function() { - var pos = this.position(); - var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); - if (!m) return; + Object.defineProperty(arr, 'result', { + enumerable: false, + value: result + }); - var val = m[0]; - var negated = m[1] ? '^' : ''; - var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); - var close = m[3] || ''; + return arr; + } - if (m[2] && inner.length < m[2].length) { - val = val.replace(/\\\\+/, '\\\\'); - } + return memoize('create', pattern, options, create); +}; - var esc = this.input.slice(0, 2); - if (inner === '' && esc === '\\]') { - inner += esc; - this.consume(2); +/** + * 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 + */ - var str = this.input; - var idx = -1; - var ch; +braces.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } - while ((ch = str[++idx])) { - this.consume(1); - if (ch === ']') { - close = ch; - break; - } - inner += ch; - } - } + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); + } - return pos({ - type: 'bracket', - val: val, - escaped: close !== ']', - negated: negated, - inner: inner, - close: close - }); - }) + function makeRe() { + var arr = braces(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(arr, opts); + } - /** - * Text - */ + return memoize('makeRe', pattern, options, makeRe); +}; - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(not); - if (!m || !m[0]) return; +/** + * 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 + */ - return pos({ - type: 'text', - val: m[0] - }); - }); +braces.parse = function(pattern, options) { + var proto = new Braces(options); + return proto.parse(pattern, options); +}; - /** - * Allow custom parsers to be passed on 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 + */ - if (options && typeof options.parsers === 'function') { - options.parsers(nanomatch.parser); - } +braces.compile = function(ast, options) { + var proto = new Braces(options); + return proto.compile(ast, options); }; /** - * Advance to the next non-escaped character + * Clear the regex cache. + * + * ```js + * braces.clearCache(); + * ``` + * @api public */ -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; - } +braces.clearCache = function() { + cache = braces.cache = {}; +}; - ch = input.charAt(++idx); - tok.len++; +/** + * 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. + */ - if (ch === '\\') { - advance(); - advance(); - } +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); } - while (ch && ch !== endChar) { - advance(); + if (cache.hasOwnProperty(key)) { + return cache[key]; } - return tok; + + var res = fn(pattern, options); + cache[key] = res; + return res; } /** - * Create text regex + * Expose `Braces` constructor and methods + * @type {Function} */ -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); -} +braces.Braces = Braces; +braces.compilers = compilers; +braces.parsers = parsers; +braces.cache = cache; /** - * Expose negation string + * Expose `braces` + * @type {Function} */ -module.exports.not = NOT_REGEX; +module.exports = braces; /***/ }), -/***/ 41340: +/***/ 12638: /***/ (function(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 extend = __webpack_require__(92845); 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) === './'; -}; +var compilers = __webpack_require__(90808); +var parsers = __webpack_require__(46362); +var utils = __webpack_require__(38640); /** - * 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} + * Customize Snapdragon parser and renderer */ -utils.isWindows = function() { - return path.sep === '\\' || isWindows === true; -}; +function Braces(options) { + this.options = extend({}, options); +} /** - * Return the last element from an array + * Initialize braces */ -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; +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; -/** - * Get the `Snapdragon` instance to use - */ + compilers(this.snapdragon, opts); + parsers(this.snapdragon, opts); -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); - } + /** + * 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(snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.call(this, str, options); - parsed.input = str; + utils.define(this.snapdragon, 'parse', function(pattern, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + this.parser.ast.input = pattern; - // 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; - } + var stack = this.parser.stack; + while (stack.length) { + addParent({type: 'brace.close', val: ''}, stack.pop()); + } - } else { - open.val = '\\' + open.val; - var sibling = open.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; - } - } + 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; }); - - 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. + * Decorate `.parse` method */ -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; +Braces.prototype.parse = function(ast, options) { + if (ast && typeof ast === 'object' && ast.nodes) return ast; + this.init(options); + return this.snapdragon.parse(ast, options); }; /** - * Cast `val` to an array - * @return {Array} + * Decorate `.compile` method */ -utils.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; +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); }; /** - * Return true if `val` is a non-empty string + * Expand */ -utils.isString = function(val) { - return typeof val === 'string'; +Braces.prototype.expand = function(pattern) { + var ast = this.parse(pattern, {expand: true}); + return this.compile(ast, {expand: true}); }; /** - * Return true if `val` is a non-empty string + * Optimize */ -utils.isRegex = function(val) { - return utils.typeOf(val) === 'regexp'; +Braces.prototype.optimize = function(pattern) { + var ast = this.parse(pattern, {optimize: true}); + return this.compile(ast, {optimize: true}); }; /** - * Return true if `val` is a non-empty string + * Expose `Braces` */ -utils.isObject = function(val) { - return utils.typeOf(val) === 'object'; -}; +module.exports = Braces; -/** - * 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} - */ +/***/ 90808: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -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, ''); -}; +"use strict"; -/** - * Returns true if the given `str` has special characters - */ -utils.hasSpecialChars = function(str) { - return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); -}; +var utils = __webpack_require__(38640); -/** - * Normalize slashes in the given filepath. - * - * @param {String} `filepath` - * @return {String} - */ +module.exports = function(braces, options) { + braces.compiler -utils.toPosixPath = function(str) { - return str.replace(/\\+/g, '/'); -}; + /** + * bos + */ -/** - * Strip backslashes before special characters in a string. - * - * @param {String} `str` - * @return {String} - */ + .set('bos', function() { + if (this.output) return; + this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; + this.ast.count = 1; + }) -utils.unescape = function(str) { - return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); -}; + /** + * Square brackets + */ -/** - * Strip the drive letter from a windows filepath - * @param {String} `fp` - * @return {String} - */ + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; -utils.stripDrive = function(fp) { - return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; -}; + inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); + if (inner === ']-') { + inner = '\\]\\-'; + } -/** - * Strip the prefix from a filepath - * @param {String} `fp` - * @return {String} - */ + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } -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 === '\\\\'; -}; + var val = open + negated + inner + close; + var queue = node.parent.queue; + var last = utils.arrayify(queue.pop()); -/** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + queue.push(utils.join(last, val)); + queue.push.apply(queue, []); + }) -utils.matchPath = function(pattern, options) { - return (options && options.contains) - ? utils.containsPattern(pattern, options) - : utils.equalsPattern(pattern, options); -}; + /** + * Brace + */ -/** - * Returns true if the given (original) filepath or unixified path are equal - * to the given pattern. - */ + .set('brace', function(node) { + node.queue = isEscaped(node) ? [node.val] : []; + node.count = 1; + return this.mapVisit(node.nodes); + }) -utils._equals = function(filepath, unixPath, pattern) { - return pattern === filepath || pattern === unixPath; -}; + /** + * Open + */ -/** - * Returns true if the given (original) filepath or unixified path contain - * the given pattern. - */ + .set('brace.open', function(node) { + node.parent.open = node.val; + }) -utils._contains = function(filepath, unixPath, pattern) { - return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; -}; + /** + * Inner + */ -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + .set('text', function(node) { + var queue = node.parent.queue; + var escaped = node.escaped; + var segs = [node.val]; -utils.equalsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + if (node.optimize === false) { + options = utils.extend({}, options, {optimize: false}); + } - 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); - }; -}; + if (node.multiplier > 1) { + node.parent.count *= node.multiplier; + } -/** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + if (options.quantifiers === true && utils.isQuantifier(node.val)) { + escaped = true; -utils.containsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + } else if (node.val.length > 1) { + if (isType(node.parent, 'brace') && !isEscaped(node)) { + var expanded = utils.expand(node.val, options); + segs = expanded.segs; - 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); - }; -}; + if (expanded.isOptimized) { + node.parent.isOptimized = true; + } -/** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` Matching regex - * @return {Function} - */ + // 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, ''); + } -utils.matchBasename = function(re) { - return function(filepath) { - return re.test(filepath) || re.test(path.basename(filepath)); - }; -}; + segs = [val]; + escaped = true; + } + } -/** - * Returns the given value unchanced. - * @return {any} - */ + } else if (node.val === ',') { + if (options.expand) { + node.parent.queue.push(['']); + segs = ['']; + } else { + segs = ['|']; + } + } else { + escaped = true; + } -utils.identity = function(val) { - return val; -}; + 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; + } + } -/** - * Determines the filepath to return based on the provided options. - * @return {any} - */ + if (!hasQueue(node.parent)) { + node.parent.queue = segs; + return; + } -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); -}; + var last = utils.arrayify(queue.pop()); + if (node.parent.count > 1 && options.expand) { + last = multiply(last, node.parent.count); + node.parent.count = 1; + } -/** - * Returns a function that normalizes slashes in a string to forward - * slashes, strips `./` from beginning of paths, and optionally unescapes - * special characters. - * @return {Function} - */ + queue.push(utils.join(utils.flatten(last), segs.shift())); + queue.push.apply(queue, segs); + }) -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; - }; -}; + /** + * 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 = ')'; + } -/***/ 18918: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // 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); + } -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + 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))); + } + }) -var isobject = __webpack_require__(96667); -var isDescriptor = __webpack_require__(44133); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + /** + * eos + */ -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'); - } + .set('eos', function(node) { + if (this.input) return; - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } + 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 (isDescriptor(val)) { - define(obj, key, val); - return obj; - } + if (node.parent.count > 1 && options.expand) { + this.output = multiply(this.output, node.parent.count); + } - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + this.output = utils.arrayify(this.output); + this.ast.queue = []; + }); - return obj; }; +/** + * Multiply the segments in the current brace level + */ -/***/ }), +function multiply(queue, n, options) { + return utils.flatten(utils.repeat(utils.arrayify(queue), n)); +} -/***/ 69148: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Return true if `node` is escaped + */ -"use strict"; +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) + */ -var isExtendable = __webpack_require__(61781); -var assignSymbols = __webpack_require__(64353); +function isOptimized(node, options) { + if (node.parent.isOptimized) return true; + return isType(node.parent, 'brace') + && !isEscaped(node.parent) + && options.expand !== true; +} -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; -}; +/** + * Returns true if the value in `node` should be wrapped in a literal brace. + * @return {Boolean} + */ -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } +function isLiteralBrace(node, options) { + return isEscaped(node.parent) || options.optimize !== false; } -function isString(val) { - return (val && typeof val === 'string'); -} +/** + * Returns true if the given `node` does not have an inner value. + * @return {Boolean} + */ -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; +function noInner(node, type) { + if (node.parent.queue.length === 1) { + return true; } - return obj; -} - -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); + 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 `key` is an own property of `obj`. + * Returns true if the given `node` is the given `type` + * @return {Boolean} */ -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +function isType(node, type) { + return typeof node !== 'undefined' && node.type === type; } -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +/** + * Returns true if the given `node` has a non-empty queue. + * @return {Boolean} + */ + +function hasQueue(node) { + return Array.isArray(node.queue) && node.queue.length; } /***/ }), -/***/ 61781: +/***/ 46362: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +var Node = __webpack_require__(12579); +var utils = __webpack_require__(38640); -var isPlainObject = __webpack_require__(81064); +/** + * Braces parsers + */ -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; +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; -/***/ 8025: -/***/ (function(module, exports) { + var prev = this.prev(); + var last = utils.last(prev.nodes); -/*! - * is-windows - * - * Copyright © 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: m[0] + })); -(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)); - }; -}); + 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; + } + } + } -/***/ 42556: -/***/ (function(module) { + if (this.options.unescape !== false) { + node.val = node.val.replace(/\\([{}])/g, '$1'); + } -var toString = Object.prototype.toString; + if (last.val === '"' && this.input.charAt(0) === '"') { + last.val = node.val; + this.consume(1); + return; + } -module.exports = function kindOf(val) { - if (val === void 0) return 'undefined'; - if (val === null) return 'null'; + return concatNodes.call(this, pos, node, prev, options); + }) - 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'; - } + /** + * Brackets: "[...]" (basic, this is overridden by + * other parsers in more advanced implementations) + */ - 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'; + .set('bracket', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; - switch (ctorName(val)) { - case 'Symbol': return 'symbol'; - case 'Promise': return 'promise'; + var prev = this.prev(); + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = m[2] || ''; + var close = m[3] || ''; - // Set, Map, WeakSet, WeakMap - case 'WeakMap': return 'weakmap'; - case 'WeakSet': return 'weakset'; - case 'Map': return 'map'; - case 'Set': return 'set'; + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - // 8-bit typed arrays - case 'Int8Array': return 'int8array'; - case 'Uint8Array': return 'uint8array'; - case 'Uint8ClampedArray': return 'uint8clampedarray'; + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); - // 16-bit typed arrays - case 'Int16Array': return 'int16array'; - case 'Uint16Array': return 'uint16array'; + var str = this.input; + var idx = -1; + var ch; - // 32-bit typed arrays - case 'Int32Array': return 'int32array'; - case 'Uint32Array': return 'uint32array'; - case 'Float32Array': return 'float32array'; - case 'Float64Array': return 'float64array'; - } + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } - if (isGeneratorObj(val)) { - return 'generator'; - } + return pos(new Node({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + })); + }) - // 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'; - } + /** + * Empty braces (we capture these early to + * speed up processing in the compiler) + */ - // other - return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); -}; + .set('multiplier', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{((?:,|\{,+\})+)\}/); + if (!m) return; -function ctorName(val) { - return typeof val.constructor === 'function' ? val.constructor.name : null; -} + this.multiplier = true; + var prev = this.prev(); + var val = m[0]; -function isArray(val) { - if (Array.isArray) return Array.isArray(val); - return val instanceof Array; -} + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } -function isError(val) { - return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); -} + var node = pos(new Node({ + type: 'text', + multiplier: 1, + match: m, + val: val + })); -function isDate(val) { - if (val instanceof Date) return true; - return typeof val.toDateString === 'function' - && typeof val.getDate === 'function' - && typeof val.setDate === 'function'; -} + return concatNodes.call(this, pos, node, prev, options); + }) -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'; -} + /** + * Open + */ -function isGeneratorFn(name, val) { - return ctorName(name) === 'GeneratorFunction'; -} + .set('brace.open', function() { + var pos = this.position(); + var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); + if (!m) return; -function isGeneratorObj(val) { - return typeof val.throw === 'function' - && typeof val.return === 'function' - && typeof val.next === 'function'; -} + var prev = this.prev(); + var last = utils.last(prev.nodes); -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 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; + } -/** - * If you need to support Safari 5-7 (8-10 yr-old browser), - * take a look at https://github.com/feross/is-buffer - */ + var open = pos(new Node({ + type: 'brace.open', + val: m[0] + })); -function isBuffer(val) { - if (val.constructor && typeof val.constructor.isBuffer === 'function') { - return val.constructor.isBuffer(val); - } - return false; -} + var node = pos(new Node({ + type: 'brace', + nodes: [] + })); + node.push(open); + prev.push(node); + this.push('brace', node); + }) -/***/ }), + /** + * Close + */ -/***/ 31368: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + .set('brace.close', function() { + var pos = this.position(); + var m = this.match(/^\}/); + if (!m || !m[0]) return; -"use strict"; + 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 typeOf = __webpack_require__(48865); -var copyDescriptor = __webpack_require__(3605); -var define = __webpack_require__(5477); + 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; + } + } + } -/** - * 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 - */ + 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); + } + } -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.'); - } + brace.push(node); + }) - var props = nativeKeys(provider); - var keys = Object.keys(provider); - var len = props.length; - omit = arrayify(omit); + /** + * Capture boundary characters + */ - while (len--) { - var key = props[len]; + .set('boundary', function() { + var pos = this.position(); + var m = this.match(/^[$^](?!\{)/); + if (!m) return; + return pos(new Node({ + type: 'text', + val: m[0] + })); + }) - if (has(keys, key)) { - define(receiver, key, provider[key]); - } else if (!(key in receiver) && !has(omit, key)) { - copyDescriptor(receiver, provider, key); - } - } -}; + /** + * One or zero, non-comma characters wrapped in braces + */ -/** - * Return true if the given value is an object or function - */ + .set('nobrace', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{[^,]?\}/); + if (!m) return; -function isObject(val) { - return typeOf(val) === 'object' || typeof val === 'function'; -} + var prev = this.prev(); + var val = m[0]; -/** - * 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} - */ + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } -function has(obj, val) { - val = arrayify(val); - var len = val.length; + return pos(new Node({ + type: 'text', + multiplier: 0, + val: val + })); + }) - if (isObject(obj)) { - for (var key in obj) { - if (val.indexOf(key) > -1) { - return true; - } - } + /** + * Text + */ - var keys = nativeKeys(obj); - return has(keys, val); - } + .set('text', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^((?!\\)[^${}[\]])+/); + if (!m) return; - if (Array.isArray(obj)) { - var arr = obj; - while (len--) { - if (arr.indexOf(val[len]) > -1) { - return true; + var prev = this.prev(); + var val = m[0]; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; } - } - return false; - } - throw new TypeError('expected an array or object.'); -} + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: val + })); + + return concatNodes.call(this, pos, node, prev, options); + }); +}; /** - * Cast the given value to an array. - * - * ```js - * arrayify('foo'); - * //=> ['foo'] - * - * arrayify(['foo']); - * //=> ['foo'] - * ``` - * - * @param {String|Array} `val` - * @return {Array} + * Returns true if the character is an extglob character. */ -function arrayify(val) { - return val ? (Array.isArray(val) ? val : [val]) : []; +function isExtglobChar(ch) { + return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; } /** - * Returns true if a value has a `contructor` - * - * ```js - * hasConstructor({}); - * //=> true - * - * hasConstructor(Object.create(null)); - * //=> false - * ``` - * @param {Object} `value` - * @return {Boolean} + * Combine text nodes, and calculate empty sets (`{,,}`) + * @param {Function} `pos` Function to calculate node position + * @param {Object} `node` AST node + * @return {Object} */ -function hasConstructor(val) { - return isObject(val) && typeof val.constructor !== 'undefined'; -} +function concatNodes(pos, node, parent, options) { + node.orig = node.val; + var prev = this.prev(); + var last = utils.last(prev.nodes); + var isEscaped = false; -/** - * 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. - */ + if (node.val.length > 1) { + var a = node.val.charAt(0); + var b = node.val.slice(-1); -function nativeKeys(val) { - if (!hasConstructor(val)) return []; - return Object.getOwnPropertyNames(val); -} + isEscaped = (a === '"' && b === '"') + || (a === "'" && b === "'") + || (a === '`' && b === '`'); + } -/** - * Expose `copy` - */ + if (isEscaped && options.unescape !== false) { + node.val = node.val.slice(1, node.val.length - 1); + node.escaped = true; + } -module.exports = copy; + if (node.match) { + var match = node.match[1]; + if (!match || match.indexOf('}') === -1) { + match = node.match[0]; + } -/** - * Expose `copy.has` for tests - */ + // replace each set with a single "," + var val = match.replace(/\{/g, ',').replace(/\}/g, ''); + node.multiplier *= val.length; + node.val = ''; + } -module.exports.has = has; + var simpleText = last.type === 'text' + && last.multiplier === 1 + && node.multiplier === 1 + && node.val; + + if (simpleText) { + last.val += node.val; + return; + } + + prev.push(node); +} /***/ }), -/***/ 59248: +/***/ 38640: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * object-visit - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ +var splitString = __webpack_require__(33218); +var utils = module.exports; -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.'); - } +/** + * Module dependencies + */ - if (typeof method !== 'string') { - throw new Error('object-visit expects `method` name to be a string'); - } +utils.extend = __webpack_require__(92845); +utils.flatten = __webpack_require__(27299); +utils.isObject = __webpack_require__(96667); +utils.fillRange = __webpack_require__(82593); +utils.repeat = __webpack_require__(69523); +utils.unique = __webpack_require__(19009); - if (typeof thisArg[method] !== 'function') { - return thisArg; - } +utils.define = function(obj, key, val) { + Object.defineProperty(obj, key, { + writable: true, + configurable: true, + enumerable: false, + value: val + }); +}; - var args = [].slice.call(arguments, 3); - target = target || {}; +/** + * Returns true if the given string contains only empty brace sets. + */ - for (var key in target) { - var arr = [key, target[key]].concat(args); - thisArg[method].apply(thisArg, arr); - } - return thisArg; +utils.isEmptySets = function(str) { + return /^(?:\{,\})+$/.test(str); }; +/** + * Returns true if the given string contains only empty brace sets. + */ -/***/ }), - -/***/ 38509: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +utils.isQuotedString = function(str) { + var open = str.charAt(0); + if (open === '\'' || open === '"' || open === '`') { + return str.slice(-1) === open; + } + return false; +}; -"use strict"; -/*! - * object.pick - * - * Copyright (c) 2014-2015 Jon Schlinkert, contributors. - * Licensed under the MIT License +/** + * 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 + */ -var isObject = __webpack_require__(96667); - -module.exports = function pick(obj, keys) { - if (!isObject(obj) && typeof obj !== 'function') { - return {}; +utils.createOptions = function(options) { + var opts = utils.extend.apply(null, arguments); + if (typeof opts.expand === 'boolean') { + opts.optimize = !opts.expand; } - - var res = {}; - if (typeof keys === 'string') { - if (keys in obj) { - res[keys] = obj[keys]; - } - return res; + if (typeof opts.optimize === 'boolean') { + opts.expand = !opts.optimize; + } + if (opts.optimize === true) { + opts.makeRe = true; } + return opts; +}; - var len = keys.length; +/** + * 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 key = keys[idx]; - if (key in obj) { - res[key] = obj[key]; + 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; } - } - return res; -}; - -/***/ }), + for (var j = 0; j < b.length; j++) { + var bval = b[j]; -/***/ 27255: -/***/ (function(module) { + if (Array.isArray(bval)) { + arr.push(utils.join(val, bval, options)); + } else { + arr.push(val + bval); + } + } + } + return arr; +}; -/*! - * pascalcase - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. +/** + * Split the given string on `,` if not escaped. */ -function pascalcase(str) { - if (typeof str !== 'string') { - throw new TypeError('expected a string.'); +utils.split = function(str, options) { + var opts = utils.extend({sep: ','}, options); + if (typeof opts.keepQuotes !== 'boolean') { + opts.keepQuotes = true; } - 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(); - }); -} + if (opts.unescape === false) { + opts.keepEscaping = true; + } + return splitString(str, opts, utils.escapeBrackets(opts)); +}; -module.exports = pascalcase; +/** + * 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; + } -/***/ 88412: -/***/ (function(module) { + if (opts.rangeLimit === true) { + opts.rangeLimit = 10000; + } -"use strict"; + 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('..'); -/** - * POSIX character classes - */ + if (arr.length === 1) { + tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; + tok.segs = []; + return tok; + } -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' -}; + 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; -/***/ 58404: -/***/ (function(module) { + 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.'); + } + } -"use strict"; + arr.push(opts); + tok.segs = utils.fillRange.apply(null, arr); + if (!tok.segs.length) { + tok.escaped = true; + tok.val = str; + return tok; + } -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 -} + if (opts.optimize === true) { + tok.segs = utils.stringifyArray(tok.segs); + } -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]; + if (tok.segs === '') { + tok.val = str; + } else { + tok.val = tok.segs[0]; + } + return tok; } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); + } 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; -/***/ 59570: -/***/ (function(module) { + while (++i < str.length) { + var ch = str[i]; -/*! - * prr - * (c) 2013 Rod Vagg - * https://github.com/rvagg/prr - * License: MIT - */ + if (ch === '\\') { + val += (opts.keepEscaping === false ? '' : ch) + str[++i]; + continue; + } -(function (name, context, definition) { - if ( true && module.exports) - module.exports = definition() - else - context[name] = definition() -})('prr', this, function() { + if (ch === '(') { + parens.push(ch); + stack.push(ch); + } - 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 - } + if (ch === '[') { + brackets.push(ch); + stack.push(ch); + } - , 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 - } + if (ch === ')') { + parens.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } - return { - enumerable : op('enumerable') - , configurable : op('configurable') - , writable : op('writable') - , value : value + if (ch === ']') { + brackets.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; } } + val += ch; + } - , prr = function (obj, key, value, options) { - var k + tok.split = false; + tok.val = val.slice(1); + tok.idx = i; + }; +}; - options = makeOptions(value, options) +/** + * Returns true if the given string looks like a regex quantifier + * @return {Boolean} + */ - if (typeof key == 'object') { - for (k in key) { - if (Object.hasOwnProperty.call(key, k)) { - options.value = key[k] - setProperty(obj, k, options) - } - } - return obj - } +utils.isQuantifier = function(str) { + return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); +}; - return setProperty(obj, key, options) - } +/** + * Cast `val` to an array. + * @param {*} `val` + */ - return prr -}) +utils.stringifyArray = function(arr) { + return [utils.arrayify(arr).join('|')]; +}; -/***/ }), +/** + * Cast `val` to an array. + * @param {*} `val` + */ -/***/ 79822: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +utils.arrayify = function(arr) { + if (typeof arr === 'undefined') { + return []; + } + if (typeof arr === 'string') { + return [arr]; + } + return arr; +}; -module.exports = __webpack_require__(76417).randomBytes +/** + * 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'); +}; /***/ }), -/***/ 42770: +/***/ 92845: /***/ (function(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 isObject = __webpack_require__(4585); +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } -/**/ - -var pna = __webpack_require__(58404); -/**/ + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; + if (isObject(obj)) { + assign(o, obj); + } + } + return o; }; -/**/ -module.exports = Duplex; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ +/** + * Returns true if the given `key` is an own property of `obj`. + */ -var Readable = __webpack_require__(79341); -var Writable = __webpack_require__(78063); +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -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); +/***/ 4585: +/***/ (function(module) { - Readable.call(this, options); - Writable.call(this, options); +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - 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; +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; - 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; +/***/ 35851: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ -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; +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'); } -}); -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } - pna.nextTick(cb, err); + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; }; + /***/ }), -/***/ 60143: +/***/ 3767: /***/ (function(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. +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; +}; -module.exports = PassThrough; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -var Transform = __webpack_require__(62826); +function isString(val) { + return (val && typeof val === 'string'); +} -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} -util.inherits(PassThrough, Transform); +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +/** + * Returns true if the given `key` is an own property of `obj`. + */ - Transform.call(this, options); +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; /***/ }), -/***/ 79341: +/***/ 82593: /***/ (function(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. +/*! + * 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__(13342); +var repeat = __webpack_require__(6332); +var toRegex = __webpack_require__(11846); -var pna = __webpack_require__(58404); -/**/ +/** + * 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} + */ -module.exports = Readable; +function fillRange(start, stop, step, options) { + if (typeof start === 'undefined') { + return []; + } -/**/ -var isArray = __webpack_require__(21352); -/**/ + 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]; + } -/**/ -var Duplex; -/**/ + if (typeof step !== 'number' && typeof step !== 'string') { + options = step; + step = undefined; + } -Readable.ReadableState = ReadableState; + if (typeof options === 'function') { + options = { transform: options }; + } -/**/ -var EE = __webpack_require__(28614).EventEmitter; + 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 []; + } -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + 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 []; + } -/**/ -var Stream = __webpack_require__(20681); -/**/ + 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); + } -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; + // 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 util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ + var step = Math.abs(toNumber(options.step)) || 1; + if (options.toRegex && step === 1) { + return toRange(a, b, start, stop, options); + } -/**/ -var debugUtil = __webpack_require__(31669); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ + var zero = {greater: [], lesser: []}; + var asc = a < b; + var arr = new Array(Math.round((asc ? b - a : a - b) / step)); + var idx = 0; -var BufferList = __webpack_require__(28878); -var destroyImpl = __webpack_require__(87915); -var StringDecoder; + 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)); + } -util.inherits(Readable, Stream); + if (options.isPadded) { + val = zeros(val, options); + } -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (options.toString) { + val = String(val); + } -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); + if (typeof options.transform === 'function') { + arr[idx++] = options.transform(val, a, b, step, idx, arr, options); + } else { + arr[idx++] = val; + } - // 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]]; + if (asc) { + a += step; + } else { + a -= step; + } + } + + if (options.toRegex === true) { + return toSequence(arr, zero, options); + } + return arr; } -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(42770); +function toRange(a, b, start, stop, options) { + if (options.isPadded) { + return toRegex(start, stop, options); + } - options = options || {}; + if (options.isNumber) { + return toRegex(Math.min(a, b), Math.max(a, b), 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; + var start = String.fromCharCode(Math.min(a, b)); + var stop = String.fromCharCode(Math.max(a, b)); + return '[' + start + '-' + stop + ']'; +} - // 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; +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 (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + if (options.capture) { + return '(' + res + ')'; + } + return res; +} - // 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; +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; +} - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; +function toNumber(val) { + return Number(val) || 0; +} - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +function isPadded(str) { + return /^-?0\d/.test(str); +} - // 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; +function isValid(min, max) { + return (isValidNumber(min) || isValidLetter(min)) + && (isValidNumber(max) || isValidLetter(max)); +} - // 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; +function isValidLetter(ch) { + return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); +} - // 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; +function isValidNumber(n) { + return isNumber(n) && !/\./.test(n); +} - // has it been destroyed - this.destroyed = false; +/** + * Expose `fillRange` + * @type {Function} + */ - // 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'; +module.exports = fillRange; - // 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; - } -} +/***/ 13342: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function Readable(options) { - Duplex = Duplex || __webpack_require__(42770); +"use strict"; - if (!(this instanceof Readable)) return new Readable(options); - this._readableState = new ReadableState(options, this); +var isObject = __webpack_require__(27244); - // legacy - this.readable = true; +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } - if (options) { - if (typeof options.read === 'function') this._read = options.read; + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (isObject(obj)) { + assign(o, obj); + } } + return o; +}; - Stream.call(this); +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } } -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; - } +/** + * Returns true if the given `key` is an own property of `obj`. + */ - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -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; - } +/***/ 27244: +/***/ (function(module) { - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); + + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); }; -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); -} +/***/ 98775: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -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); +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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); -} +var isPlainObject = __webpack_require__(81064); -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; -// 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; -} +/***/ 19613: +/***/ (function(module) { -// 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; +var toString = Object.prototype.toString; - if (n !== 0) state.emittedReadable = false; +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; - // 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; + 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'; } - n = howMuchToRead(n, state); + 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'; - // 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; - } + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; - // 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. + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; - // 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); - } + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; - // 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); + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + if (isGeneratorObj(val)) { + return 'generator'; + } - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; + // 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'; } - 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; + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} - if (ret !== null) this.emit('data', ret); +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} - return ret; -}; +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} -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; +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); +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'; } -// 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 isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; } -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; } -// 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 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; } -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; +/** + * 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); } - state.readingMore = false; + return 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); +/***/ 11846: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +"use strict"; +/*! + * to-regex-range + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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(); - } - } + +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.'); } - function onend() { - debug('onend'); - dest.end(); + if (typeof max === 'undefined' || min === max) { + return String(min); } - // 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); + if (isNumber(max) === false) { + throw new RangeError('toRegexRange: second argument is invalid.'); + } - 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(); + 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; } - // 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(); - } - } + var a = Math.min(min, max); + var b = Math.max(min, max); - // 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); + if (Math.abs(a - b) === 1) { + var result = min + '|' + max; + if (options.capture) { + return '(' + result + ')'; + } + return result; } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + var isPadded = padding(min) || padding(max); + var positives = []; + var negatives = []; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); + var tok = {min: min, max: max, a: a, b: b}; + if (isPadded) { + tok.isPadded = isPadded; + tok.maxLen = String(tok.max).length; } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + + 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; } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); + if (b >= 0) { + positives = splitToPatterns(a, b, tok, options); } - // tell the dest that it's being piped to - dest.emit('pipe', src); + tok.negatives = negatives; + tok.positives = positives; + tok.result = siftPatterns(negatives, positives, options); - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); + if (options.capture && (positives.length + negatives.length) > 1) { + tok.result = '(' + tok.result + ')'; } - return dest; -}; + cache[key] = tok; + return tok.result; +} -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); - } - }; +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('|'); } -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; +function splitToRanges(min, max) { + min = Number(min); + max = Number(max); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + var nines = 1; + var stops = [max]; + var stop = +countNines(min, nines); - // 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; + while (min <= stop && stop <= max) { + stops = push(stops, stop); + nines += 1; + stop = +countNines(min, nines); + } - if (!dest) dest = state.pipes; + var zeros = 1; + stop = countZeros(max + 1, zeros) - 1; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; + while (min < stop && stop <= max) { + stops = push(stops, stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; } - // slow case. multiple pipe destinations. + stops.sort(compare); + return stops; +} - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; +function rangeToPattern(start, stop, options) { + if (start === stop) { + return {pattern: String(start), digits: []}; } - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + var zipped = zip(String(start), String(stop)); + var len = zipped.length, i = -1; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + var pattern = ''; + var digits = 0; - dest.emit('unpipe', this, unpipeInfo); + while (++i < len) { + var numbers = zipped[i]; + var startDigit = numbers[0]; + var stopDigit = numbers[1]; - return this; -}; + if (startDigit === stopDigit) { + pattern += startDigit; -// 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); + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); - 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); - } + } else { + digits += 1; } } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; + if (digits) { + pattern += options.shorthand ? '\\d' : '[0-9]'; + } -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + return { pattern: pattern, digits: [digits] }; } -// 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 splitToPatterns(min, max, tok, options) { + var ranges = splitToRanges(min, max); + var len = ranges.length; + var idx = -1; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} + var tokens = []; + var start = min; + var prev; -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } + while (++idx < len) { + var range = ranges[idx]; + var obj = rangeToPattern(start, range, options); + var zeros = ''; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + 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; + } -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'); + if (tok.isPadded) { + zeros = padZeros(range, tok); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.digits); + tokens.push(obj); + start = range + 1; + prev = obj; } - return this; -}; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + return tokens; } -// 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; +function filterPatterns(arr, comparison, prefix, intersection, options) { + var res = []; - var state = this._readableState; - var paused = false; + for (var i = 0; i < arr.length; i++) { + var tok = arr[i]; + var ele = tok.string; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + 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); + } + } } - _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(); + if (!intersection && !contains(comparison, 'string', ele)) { + res.push(prefix + ele); } - }); - // 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); + if (intersection && contains(comparison, 'string', ele)) { + res.push(prefix + ele); } } + return res; +} - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } +/** + * Zip strings (`for in` can be used on string characters) + */ - // 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(); - } - }; +function zip(a, b) { + var arr = []; + for (var ch in a) arr.push([a[ch], b[ch]]); + return arr; +} - return this; -}; +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} -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; +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; +} -// exposed for testing purposes only. -Readable._fromList = fromList; +function countNines(min, len) { + return String(min).slice(0, -len) + repeat('9', len); +} -// 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; +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} - 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); +function toQuantifier(digits) { + var start = digits[0]; + var stop = digits[1] ? (',' + digits[1]) : ''; + if (!stop && (!start || start === 1)) { + return ''; } + return '{' + start + stop + '}'; +} - return ret; +function toCharacterClass(a, b) { + return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; } -// 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; +function padding(str) { + return /^-?(0+)\d/.exec(str); } -// 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); +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 + '}'; } - break; } - ++c; } - list.length -= c; - return ret; + return val; } -// 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); - } -} +/** + * Expose `toRegexRange` + */ -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'); - } -} +module.exports = toRegexRange; -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} /***/ }), -/***/ 62826: +/***/ 4870: /***/ (function(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 isExtendable = __webpack_require__(29502); +var forIn = __webpack_require__(43086); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); +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; } -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; +/** + * Copy properties from the source object to the + * target object. + * + * @param {*} `val` + * @param {String} `key` + */ - if (typeof options.flush === 'function') this._flush = options.flush; +function copy(val, key) { + if (!isValidKey(key)) { + return; } - // 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); - }); + var obj = this[key]; + if (isObject(val) && isObject(obj)) { + mixinDeep(obj, val); } else { - done(this, null, null); + this[key] = val; } } -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; +/** + * Returns true if `val` is an object or function. + * + * @param {any} val + * @return {Boolean} + */ - 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; - } -}; +function isObject(val) { + return isExtendable(val) && !Array.isArray(val); +} -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; +/** + * Returns true if `key` is a valid key to use when extending objects. + * + * @param {String} `key` + * @return {Boolean} + */ - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; }; -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'); +/** + * Expose `mixinDeep` + */ - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +module.exports = mixinDeep; - return stream.push(null); -} /***/ }), -/***/ 78063: +/***/ 29502: /***/ (function(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. +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -// 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 isPlainObject = __webpack_require__(81064); -/**/ +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; -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; -} +/***/ 50998: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -// 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; +var path = __webpack_require__(85622); +var fs = __webpack_require__(35747); +var _0777 = parseInt('0777', 8); - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); } -/* */ -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; -/**/ -var Duplex; -/**/ + p = path.resolve(p); -Writable.WritableState = WritableState; + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } -/**/ -var internalUtil = { - deprecate: __webpack_require__(92262) + return made; }; -/**/ - -/**/ -var Stream = __webpack_require__(20681); -/**/ -/**/ -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; -} +/***/ }), -/**/ +/***/ 57925: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var destroyImpl = __webpack_require__(87915); +"use strict"; -util.inherits(Writable, Stream); -function nop() {} +/** + * Module dependencies + */ -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(42770); +var util = __webpack_require__(31669); +var toRegex = __webpack_require__(51279); +var extend = __webpack_require__(69148); - options = options || {}; +/** + * Local dependencies + */ - // 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; +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; - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; +/** + * 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 + */ - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; +function nanomatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); - // 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); + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; + } - // if _final has been called - this.finalCalled = false; + if (len === 1) { + return nanomatch.match(list, patterns[0], options); + } - // 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; + var negated = false; + var omit = []; + var keep = []; + var idx = -1; - // has it been destroyed - this.destroyed = false; + while (++idx < len) { + var pattern = patterns[idx]; - // 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; + 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)); + } + } - // 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'; + // 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])); + } + } + } - // 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; + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } - // a flag to see when we're in the middle of a write. - this.writing = false; + return matches; +} - // when true all writes will be buffered until .uncork() call - this.corked = 0; +/** + * 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 + */ - // 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; +nanomatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } - // 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; + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, nanomatch.matcher); + var matches = []; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + list = utils.arrayify(list); + var len = list.length; + var idx = -1; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); + } + } - // the amount that is being written when _write is called. - this.writelen = 0; + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + 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]; + } + } - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = nanomatch.not(matches, options.ignore, options); + } - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + return options.nodupes !== false ? utils.unique(matches) : matches; +}; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; +/** + * 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 + */ - // count buffered requests - this.bufferedRequestCount = 0; +nanomatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { + return false; + } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; } - return out; + + var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); + return isMatch(str); }; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); +/** + * 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 + */ -// 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; +nanomatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } - return object && object._writableState instanceof WritableState; + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length === 1) { + return true; } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + } -function Writable(options) { - Duplex = Duplex || __webpack_require__(42770); + return false; +}; - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. +/** + * 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 + */ - // 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); +nanomatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; } - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length !== 1) { + return false; + } + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; + return true; +}; - if (typeof options.writev === 'function') this._writev = options.writev; +/** + * 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 + */ - if (typeof options.destroy === 'function') this._destroy = options.destroy; +nanomatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } - if (typeof options.final === 'function') this._final = options.final; + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; } - Stream.call(this); -} + if (typeof patterns === 'string') { + patterns = [patterns]; + } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); + for (var i = 0; i < patterns.length; i++) { + if (nanomatch.isMatch(str, patterns[i], options)) { + return true; + } + } + return false; }; -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; +/** + * 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 + */ - 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; +nanomatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } - 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 patterns === 'string') { + patterns = [patterns]; } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + for (var i = 0; i < patterns.length; i++) { + if (!nanomatch.isMatch(str, patterns[i], options)) { + return false; + } } + return true; +}; - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; +/** + * 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 + */ - if (typeof cb !== 'function') cb = nop; +nanomatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + list = utils.arrayify(list); + + var matches = utils.diff(list, nanomatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, nanomatch(list, ignore)); } - return ret; + return opts.nodupes !== false ? utils.unique(matches) : matches; }; -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; +/** + * 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 + */ -Writable.prototype.uncork = function () { - var state = this._writableState; +nanomatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } - if (state.corked) { - state.corked--; + if (typeof patterns === 'string') { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } } -}; -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; + var opts = extend({}, options, {contains: true}); + return nanomatch.any(str, patterns, opts); }; -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} +/** + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private + */ -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; - } -}); +nanomatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; -// 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; +/** + * 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 + */ - state.length += len; +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); +}; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; +/** + * 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 + */ - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null +nanomatch.matcher = function matcher(pattern, options) { + if (utils.isEmptyString(pattern)) { + return function() { + return false; }; - 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); + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); } -} - -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 pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); } + return utils.matchPath(pattern, options); } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + // if pattern is a glob string + var re = nanomatch.makeRe(pattern, options); -// 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 `options.matchBase` or `options.basename` is defined + if (nanomatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); } -} -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); - 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; + return function(str) { + if (equals(str)) { + return true; + } - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; + if (regex.test(unixify(str))) { + return true; + } + return false; + }; + } - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + // 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; +}; - // 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; +/** + * 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 + */ - 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; +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; } - } - if (entry === null) state.lastBufferedRequest = null; + return match.slice(1); + }; } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); + var capture = memoize('capture', pattern, options, match); + return capture(str); }; -Writable.prototype._writev = null; +/** + * 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 + */ -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +nanomatch.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); + 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; } - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); + return memoize('makeRe', pattern, options, makeRe); }; -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'); - } - } -} +/** + * 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 + */ -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } +nanomatch.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); } - 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); + function create() { + return nanomatch.compile(nanomatch.parse(pattern, options), options); } - state.ended = true; - stream.writable = false; -} + return memoize('create', pattern, options, create); +}; -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; +/** + * 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'); } -} -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; - } + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); + 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 + */ -/***/ 28878: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +nanomatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = nanomatch.parse(ast, options); + } -"use strict"; + function compile() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); + } + return memoize('compile', ast.input, options, compile); +}; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * Clear the regex cache. + * + * ```js + * nm.clearCache(); + * ``` + * @api public + */ -var Buffer = __webpack_require__(96788).Buffer; -var util = __webpack_require__(31669); +nanomatch.clearCache = function() { + nanomatch.cache.__data__ = {}; +}; -function copyBuffer(src, target, offset) { - src.copy(target, offset); +/** + * 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; + }; + }); } -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); +/** + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. + */ - this.head = null; - this.tail = null; - this.length = 0; - } +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); - 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; - }; + if (options && options.cache === false) { + return fn(pattern, options); + } - 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; - }; + if (cache.has(type, key)) { + return cache.get(type, key); + } - 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; - }; + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; +/** + * Expose compiler, parser and cache on `nanomatch` + */ - 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; - }; +nanomatch.compilers = compilers; +nanomatch.parsers = parsers; +nanomatch.cache = cache; - 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; - }; +/** + * Expose `nanomatch` + * @type {Function} + */ - return BufferList; -}(); +module.exports = nanomatch; -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: +/***/ 58250: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; +module.exports = new (__webpack_require__(49908))(); -/**/ +/***/ }), -var pna = __webpack_require__(58404); -/**/ +/***/ 4756: +/***/ (function(module) { -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +"use strict"; - 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); +/** +* Nanomatch compilers +*/ + +module.exports = function(nanomatch, options) { + function slash() { + if (options && typeof options.slash === 'string') { + return options.slash; } - return this; + if (options && typeof options.slash === 'function') { + return options.slash.call(nanomatch); + } + return '\\\\/'; } - // 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; + function star() { + if (options && typeof options.star === 'string') { + return options.star; + } + if (options && typeof options.star === 'function') { + return options.star.call(nanomatch); + } + return '[^' + slash() + ']*?'; } - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } + var ast = nanomatch.ast = nanomatch.parser.ast; + ast.state = nanomatch.parser.state; + nanomatch.compiler.state = ast.state; + nanomatch.compiler - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; + /** + * Negation / escaping + */ + + .set('not', function(node) { + var prev = this.prev(); + if (this.options.nonegate === true || prev.type !== 'bos') { + return this.emit('\\' + node.val, node); } - } else if (cb) { - cb(err); - } - }); + 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); + }) - return this; -} + /** + * Regex + */ -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + .set('dollar', function(node) { + if (node.parent.type === 'bracket') { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} + /** + * Dot: "." + */ -function emitErrorNT(self, err) { - self.emit('error', err); -} + .set('dot', function(node) { + if (node.dotfiles === true) this.dotfiles = true; + return this.emit('\\' + node.val, node); + }) -module.exports = { - destroy: destroy, - undestroy: undestroy -}; + /** + * 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(); -/***/ 20681: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // set "node.hasSlash" to true on all ancestor parens nodes + while (parent.type === 'paren' && !parent.hasSlash) { + parent.hasSlash = true; + parent = parent.parent; + } -module.exports = __webpack_require__(92413); + 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); + } -/***/ 96788: -/***/ (function(module, exports, __webpack_require__) { + // negation + if (node.parsed === '!**' && this.options.nonegate !== true) { + return this.emit(val + '?\\b', node); + } + return this.emit(val, node); + }) -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(64293) -var Buffer = buffer.Buffer + /** + * Square brackets + */ -// 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 -} + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + var val = node.val; -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} + if (node.escaped === true) { + inner = inner.replace(/\\?(\W)/g, '\\$1'); + negated = ''; + } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + if (inner === ']-') { + inner = '\\]\\-'; + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } -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 -} + val = open + negated + inner + close; + return this.emit(val, node); + }) -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} + /** + * Square: "[.]" (only matches a single character in brackets) + */ -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} + .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 = '[^\\\\/]'; + } -/***/ 7395: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch === '!' || ch === '=' || ch === ':') { + return this.emit(node.val, node); + } + } -"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. + 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: '**' + */ -var Buffer = __webpack_require__(96788).Buffer; -/**/ + .set('globstar', function(node, nodes, i) { + if (!this.output) { + this.state.leadingGlobstar = true; + } -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; - } -}; + 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; -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; - } - } -}; + if (prev.type === 'slash' && next.type === 'slash') { + if (before.type === 'text') { + this.output += '?'; -// 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; -} + if (after.type !== 'text') { + this.output += '\\b'; + } + } + } -// 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); -} + var parsed = node.parsed; + if (parsed.charAt(0) === '!') { + parsed = parsed.slice(1); + } -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 || ''; -}; + 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}).)*?'; + } -StringDecoder.prototype.end = utf8End; + if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { + val = '(?!\\.)' + val; + } -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { + if (after.type === 'text' || after.type === 'star') { + node.addQmark = true; + } + } -// 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; -}; + if (this.options.capture) { + val = '(' + val + ')'; + } -// 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; -} + return this.emit(val, node); + }) -// 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; -} + /** + * Star: "*" + */ -// 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'; + .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'; } - } - } -} -// 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; -} + if (this.output === '' && this.options.contains !== true) { + this.output = '(?![' + slash() + '])'; + } -// 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); -} + 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); + } + } -// 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; -} + var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' + ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') + : ''; -// 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); + if (isStart(prev) || (isStart(prior) && type === 'not')) { + if (prefix !== '(?!\\.)') { + prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; + } else { + prefix += '(?=.)'; + } + } else if (prefix === '(?!\\.)') { + prefix = ''; } - } - 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; -} + if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { + this.output = '(?!\\.)' + this.output; + } -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); -} + var output = prefix + star(); + if (this.options.capture) { + output = '(' + output + ')'; + } -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; -} + return this.emit(output, node); + }) -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} + /** + * Text + */ -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} + .set('text', function(node) { + return this.emit(node.val, node); + }) -/***/ }), + /** + * End-of-string + */ -/***/ 68193: -/***/ (function(module, exports, __webpack_require__) { + .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); + } +}; -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: +/***/ 5333: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(39700); -var safe = __webpack_require__(71217); +var regexNot = __webpack_require__(30931); +var toRegex = __webpack_require__(51279); /** - * 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 + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) */ -function toRegex(pattern, options) { - return new RegExp(toRegex.create(pattern, options)); -} +var cached; +var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; +var not = createTextRegex(NOT_REGEX); /** - * 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 + * Nanomatch parsers */ -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; - } +module.exports = function(nanomatch, options) { + var parser = nanomatch.parser; + var opts = parser.options; - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var endChar = opts.endChar ? opts.endChar : '+'; - var str = pattern; + parser.state = { + slashes: 0, + paths: [] + }; - if (opts.strictNegate === false) { - str = '(?:(?!(?:' + pattern + ')).)' + endChar; - } else { - str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; - } + parser.ast.state = parser.state; + parser - var res = open + str + close; - if (opts.safe === true && safe(res) === false) { - throw new Error('potentially unsafe regular expression: ' + res); - } + /** + * Beginning-of-string + */ - return res; -}; + .capture('prefix', function() { + if (this.parsed) return; + var m = this.match(/^\.[\\/]/); + if (!m) return; + this.state.strictOpen = !!this.options.strictOpen; + this.state.addPrefix = true; + }) -/** - * Expose `toRegex` - */ + /** + * Escape: "\\." + */ -module.exports = toRegex; + .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 + */ -/***/ 39700: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + .capture('quoted', function() { + var pos = this.position(); + var m = this.match(/^["']/); + if (!m) return; -"use strict"; + 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); -var isExtendable = __webpack_require__(93295); -var assignSymbols = __webpack_require__(64353); + return pos({ + type: 'quoted', + val: tok.esc + }); + }) -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; -}; + /** + * Negations: "!" + */ -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} + .capture('not', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(this.notRegex || /^!+/); + if (!m) return; + var val = m[0]; -function isString(val) { - return (val && typeof val === 'string'); -} + var isNegated = (val.length % 2) === 1; + if (parsed === '' && !isNegated) { + val = ''; + } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + // 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 + }); + }) -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + /** + * Dot: "." + */ -/** - * Returns true if the given `key` is an own property of `obj`. - */ + .capture('dot', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\.+/); + if (!m) return; -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + var val = m[0]; + this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} + return pos({ + type: 'dot', + dotfiles: this.state.dot, + val: val + }); + }) + /** + * Plus: "+" + */ -/***/ }), + .capture('plus', /^\+(?!\()/) -/***/ 93295: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Question mark: "?" + */ -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + .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] + }); + }) -var isPlainObject = __webpack_require__(81064); + /** + * Globstar: "**" + */ -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + .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); + } -/***/ 69523: -/***/ (function(module) { + node.isInside = { + brace: this.isInside('brace'), + paren: this.isInside('paren') + }; -"use strict"; -/*! - * repeat-element - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Licensed under the MIT license. - */ + if (type === 'globstar') { + this.state.globstar = true; + node.val = '**'; + } else { + this.state.star = true; + node.val = '*'; + } + return node; + }) -module.exports = function repeat(ele, num) { - var arr = new Array(num); + /** + * Star: "*" + */ - for (var i = 0; i < num; i++) { - arr[i] = ele; - } + .capture('star', function() { + var pos = this.position(); + var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; + var m = this.match(starRe); + if (!m) return; - return arr; -}; + 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; -/***/ 6332: -/***/ (function(module) { + this.state.slashes++; + return pos({ + type: 'slash', + val: m[0] + }); + }) -"use strict"; -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + /** + * Backslash: "\\" + */ + .capture('backslash', function() { + var pos = this.position(); + var m = this.match(/^\\(?![*+?(){}[\]'"])/); + if (!m) return; + var val = m[0]; -/** - * Results cache - */ + if (this.isInside('bracket')) { + val = '\\'; + } else if (val.length > 1) { + val = '\\\\'; + } -var res = ''; -var cache; + return pos({ + type: 'backslash', + val: val + }); + }) -/** - * Expose `repeat` - */ + /** + * Square: "[.]" + */ -module.exports = repeat; + .capture('square', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\[([^!^\\])\]/); + if (!m) return; -/** - * 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 - */ + return pos({ + type: 'square', + val: m[1] + }); + }) -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } + /** + * Brackets: "[...]" (basic, this can be overridden by other parsers) + */ - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; + .capture('bracket', function() { + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } else if (res.length >= max) { - return res.substr(0, max); - } + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); + var close = m[3] || ''; - while (max > res.length && num > 1) { - if (num & 1) { - res += str; - } + if (m[2] && inner.length < m[2].length) { + val = val.replace(/\\\\+/, '\\\\'); + } - num >>= 1; - str += str; - } + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); - res += str; - res = res.substr(0, max); - return res; -} + 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 + }); + }) -/***/ 25622: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Text + */ -var util = __webpack_require__(10265); -var types = __webpack_require__(40432); -var sets = __webpack_require__(28135); -var positions = __webpack_require__(54771); + .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] + }); + }); -module.exports = function(regexpStr) { - var i = 0, l, c, - start = { type: types.ROOT, stack: []}, + /** + * Allow custom parsers to be passed on options + */ - // Keep track of last clause/group and stack. - lastGroup = start, - last = start.stack, - groupStack = []; + if (options && typeof options.parsers === 'function') { + options.parsers(nanomatch.parser); + } +}; +/** + * Advance to the next non-escaped character + */ - var repeatErr = function(i) { - util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); - }; +function advanceTo(input, endChar) { + var ch = input.charAt(0); + var tok = { len: 1, val: '', esc: '' }; + var idx = 0; - // Decode a few escaped characters. - var str = util.strToChars(regexpStr); - l = str.length; + function advance() { + if (ch !== '\\') { + tok.esc += '\\' + ch; + tok.val += ch; + } - // Iterate through each character in string. - while (i < l) { - c = str[i++]; + ch = input.charAt(++idx); + tok.len++; - switch (c) { - // Handle escaped characters, inclues a few sets. - case '\\': - c = str[i++]; + if (ch === '\\') { + advance(); + advance(); + } + } - switch (c) { - case 'b': - last.push(positions.wordBoundary()); - break; + while (ch && ch !== endChar) { + advance(); + } + return tok; +} - case 'B': - last.push(positions.nonWordBoundary()); - break; +/** + * Create text regex + */ - case 'w': - last.push(sets.words()); - break; +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); +} - case 'W': - last.push(sets.notWords()); - break; +/** + * Expose negation string + */ - case 'd': - last.push(sets.ints()); - break; +module.exports.not = NOT_REGEX; - case 'D': - last.push(sets.notInts()); - break; - case 's': - last.push(sets.whitespace()); - break; +/***/ }), - case 'S': - last.push(sets.notWhitespace()); - break; +/***/ 41340: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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) }); +"use strict"; - // Escaped character. - } else { - last.push({ type: types.CHAR, value: c.charCodeAt(0) }); - } - } - break; +var utils = module.exports; +var path = __webpack_require__(85622); +/** + * Module dependencies + */ - // Positionals. - case '^': - last.push(positions.begin()); - break; +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); - case '$': - last.push(positions.end()); - break; +/** + * Returns true if the given value is effectively an empty string + */ +utils.isEmptyString = function(val) { + return String(val) === '' || String(val) === './'; +}; - // Handle custom sets. - case '[': - // Check if this class is 'anti' i.e. [^abc]. - var not; - if (str[i] === '^') { - not = true; - i++; - } else { - not = false; - } +/** + * 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} + */ - // Get all the characters in class. - var classTokens = util.tokenizeClass(str.slice(i), regexpStr); +utils.isWindows = function() { + return path.sep === '\\' || isWindows === true; +}; - // Increase index by length of class. - i += classTokens[1]; - last.push({ - type: types.SET, - set: classTokens[0], - not: not, - }); +/** + * Return the last element from an array + */ - break; +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; +/** + * Get the `Snapdragon` instance to use + */ - // Class of any character except \n. - case '.': - last.push(sets.anyChar()); - break; +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; - // 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); + // 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; } - last.push({ - type: types.REPETITION, - min: 0, - max: 1, - value: last.pop(), - }); - break; - case '+': - if (last.length === 0) { - repeatErr(i); + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; } - 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; + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); + return snapdragon; +}; - // Default is a character that is not `\[](){}?+*^$`. - default: - last.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); - } +/** + * 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; } - - // Check if any groups have not been closed. - if (groupStack.length !== 0) { - util.error(regexpStr, 'Unterminated group'); + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } } - - return start; + return key; }; -module.exports.types = types; +/** + * 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 + */ -/***/ 54771: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +utils.isString = function(val) { + return typeof val === 'string'; +}; -var types = __webpack_require__(40432); +/** + * Return true if `val` is a non-empty string + */ -exports.wordBoundary = function() { - return { type: types.POSITION, value: 'b' }; +utils.isRegex = function(val) { + return utils.typeOf(val) === 'regexp'; }; -exports.nonWordBoundary = function() { - return { type: types.POSITION, value: 'B' }; -}; +/** + * Return true if `val` is a non-empty string + */ -exports.begin = function() { - return { type: types.POSITION, value: '^' }; +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; }; -exports.end = function() { - return { type: types.POSITION, value: '$' }; -}; +/** + * 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} + */ -/***/ 28135: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +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, ''); +}; -var types = __webpack_require__(40432); +/** + * Returns true if the given `str` has special characters + */ -var INTS = function() { - return [{ type: types.RANGE , from: 48, to: 57 }]; +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); }; -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()); -}; +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ -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 } - ]; +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); }; -var NOTANYCHAR = function() { - return [ - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - ]; -}; +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ -// Predefined class objects. -exports.words = function() { - return { type: types.SET, set: WORDS(), not: false }; +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); }; -exports.notWords = function() { - return { type: types.SET, set: WORDS(), not: true }; -}; +/** + * Strip the drive letter from a windows filepath + * @param {String} `fp` + * @return {String} + */ -exports.ints = function() { - return { type: types.SET, set: INTS(), not: false }; +utils.stripDrive = function(fp) { + return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; }; -exports.notInts = function() { - return { type: types.SET, set: INTS(), not: true }; -}; +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ -exports.whitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: false }; +utils.stripPrefix = function(str) { + if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { + return str.slice(2); + } + return str; }; -exports.notWhitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: true }; -}; +/** + * 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} + */ -exports.anyChar = function() { - return { type: types.SET, set: NOTANYCHAR(), not: true }; +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 === '\\\\'; +}; -/***/ 40432: -/***/ (function(module) { +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -module.exports = { - ROOT : 0, - GROUP : 1, - POSITION : 2, - SET : 3, - RANGE : 4, - REPETITION : 5, - REFERENCE : 6, - CHAR : 7, +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; +}; -/***/ 10265: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ -var types = __webpack_require__(40432); -var sets = __webpack_require__(28135); +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} + */ -// All of these are private and only used by randexp. -// It's assumed that they will always be called with the correct input. +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; -var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; -var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; + 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); + }; +}; /** - * Finds character representations in str and convert all to - * their respective characters + * Returns a function that returns true if the given + * pattern contains a `filepath` * - * @param {String} str - * @return {String} + * @param {String} `pattern` + * @return {Function} */ -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); +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - // Escape special regex characters. - if (/[\[\]{}\^$.|?*+()]/.test(c)) { - c = '\\' + c; + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; } - - return c; - }); - - return str; + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; }; - /** - * turns class into tokens - * reads str until it encounters a ] not preceeded by a \ + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. * - * @param {String} str - * @param {String} regexpStr - * @return {Array., Number>} + * @param {RegExp} `re` Matching regex + * @return {Function} */ -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()); +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; - } else if (rs[3]) { - tokens.push(sets.whitespace()); +/** + * Returns the given value unchanced. + * @return {any} + */ - } else if (rs[4]) { - tokens.push(sets.notWords()); +utils.identity = function(val) { + return val; +}; - } else if (rs[5]) { - tokens.push(sets.notInts()); +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ - } 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]; - } +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; } - - exports.error(regexpStr, 'Unterminated character class'); + if (options && typeof options.unixify === 'function') { + return options.unixify(str); + } + return unixify(str); }; - /** - * Shortcut to throw errors. - * - * @param {String} regexp - * @param {String} msg + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} */ -exports.error = function(regexp, msg) { - throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); + +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; + }; }; /***/ }), -/***/ 71217: +/***/ 18918: /***/ (function(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); -}; +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ -function isRegExp (x) { - return {}.toString.call(x) === '[object RegExp]'; -} -/***/ }), +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; -/***/ 85841: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +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'); + } -"use strict"; -/* -Copyright (c) 2014, Yahoo! Inc. All rights reserved. -Copyrights licensed under the New BSD License. -See the accompanying LICENSE file for terms. -*/ + 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 + }); -var randomBytes = __webpack_require__(79822); + return obj; +}; -// 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']; +/***/ 69148: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -// 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' -}; +"use strict"; -function escapeUnsafeChars(unsafeChar) { - return ESCAPED_CHARS[unsafeChar]; -} -function generateUID() { - var bytes = randomBytes(UID_LENGTH); - var result = ''; - for(var i=0; i + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - if (type === 'undefined') { - return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@'; - } - if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) { - return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@'; - } - return value; - } +var isPlainObject = __webpack_require__(81064); - function serializeFunc(fn) { - var serializedFn = fn.toString(); - if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) { - throw new TypeError('Serializing native function: ' + fn.name); - } +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; - // pure functions, example: {key: function() {}} - if(IS_PURE_FUNCTION.test(serializedFn)) { - return serializedFn; - } - // arrow functions, example: arg1 => 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 }); +/***/ 8025: +/***/ (function(module, exports) { - var nonReservedSymbols = def.filter(function(val) { - return RESERVED_SYMBOLS.indexOf(val) === -1 - }); +/*! + * is-windows + * + * Copyright © 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ - // enhanced literal objects, example: {key() {}} - if(nonReservedSymbols.length > 0) { - return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' - + (def.join('').indexOf('*') > -1 ? '*' : '') - + serializedFn.substr(argsStartsAt); - } +(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)); + }; +}); - // 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; +/***/ 42556: +/***/ (function(module) { - // 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); - } +var toString = Object.prototype.toString; - // Protects against `JSON.stringify()` returning `undefined`, by serializing - // to the literal string: "undefined". - if (typeof str !== 'string') { - return String(str); - } +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; - // 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); - } + 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 (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0) { - return str; - } + 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'; - // 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; - } + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; - if (type === 'D') { - return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; - } + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; - if (type === 'R') { - return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; - } + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; - if (type === 'M') { - return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; - } + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; - if (type === 'S') { - return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; - } + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } - if (type === 'U') { - return 'undefined' - } + if (isGeneratorObj(val)) { + return 'generator'; + } - if (type === 'I') { - return infinities[valueIndex]; - } + // 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'; + } - var fn = functions[valueIndex]; + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; - return serializeFunc(fn); - }); +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'); +} -/***/ 34857: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} -"use strict"; -/*! - * set-value - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ +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'; +} -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; +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; } - - if (isPlainObject(current[key]) && isPlainObject(val)) { - current[key] = extend({}, current[key], val); - } else { - current[key] = val; + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; } } + return false; +} - return obj; -}; +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; } /***/ }), -/***/ 12579: -/***/ (function(module, exports, __webpack_require__) { +/***/ 31368: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(96667); -var define = __webpack_require__(88599); -var utils = __webpack_require__(82071); -var ownNames; +var typeOf = __webpack_require__(48865); +var copyDescriptor = __webpack_require__(3605); +var define = __webpack_require__(5477); /** - * Create a new AST `Node` with the given `val` and `type`. + * Copy static properties, prototype properties, and descriptors from one object to another. * * ```js - * var node = new Node('*', 'Star'); - * var node = new Node({type: 'star', val: '*'}); + * function App() {} + * var proto = App.prototype; + * App.prototype.set = function() {}; + * App.prototype.get = function() {}; + * + * var obj = {}; + * copy(obj, proto); * ``` - * @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 + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} * @api public */ -function Node(val, type, parent) { - if (typeof type !== 'string') { - parent = type; - type = null; +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.'); } - define(this, 'parent', parent); - define(this, 'isNode', true); - define(this, 'expect', null); + var props = nativeKeys(provider); + var keys = Object.keys(provider); + var len = props.length; + omit = arrayify(omit); - 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]; - } + 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); } - } 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 + * Return true if the given value is an object or function */ -Node.prototype.define = function(name, val) { - define(this, name, val); - return this; -}; +function isObject(val) { + return typeOf(val) === 'object' || typeof val === 'function'; +} /** - * Returns true if `node.val` is an empty string, or `node.nodes` does - * not contain any non-empty text nodes. + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. * * ```js - * var node = new Node({type: 'text'}); - * node.isEmpty(); //=> true - * node.val = 'foo'; - * node.isEmpty(); //=> false + * has(['a', 'b', 'c'], 'c'); + * //=> true + * + * has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true * ``` - * @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. + * @param {Object} `obj` + * @param {String|Array} `val` * @return {Boolean} - * @api public */ -Node.prototype.isEmpty = function(fn) { - return utils.isEmpty(this, fn); -}; +function has(obj, val) { + val = arrayify(val); + var len = val.length; -/** - * 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 - */ + if (isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; + } + } -Node.prototype.push = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - define(node, 'parent', this); + var keys = nativeKeys(obj); + return has(keys, val); + } - this.nodes = this.nodes || []; - return this.nodes.push(node); -}; + 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.'); +} /** - * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and - * set `foo` as `bar.parent`. + * Cast the given value to an array. * * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.unshift(bar); + * arrayify('foo'); + * //=> ['foo'] + * + * arrayify(['foo']); + * //=> ['foo'] * ``` - * @param {Object} `node` - * @return {Number} Returns the length of `node.nodes` - * @api public + * + * @param {String|Array} `val` + * @return {Array} */ -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); -}; +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} /** - * Pop a node from `node.nodes`. + * Returns true if a value has a `contructor` * * ```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 + * hasConstructor({}); + * //=> true + * + * hasConstructor(Object.create(null)); + * //=> false * ``` - * @return {Number} Returns the popped `node` - * @api public + * @param {Object} `value` + * @return {Boolean} */ -Node.prototype.pop = function() { - return this.nodes && this.nodes.pop(); -}; +function hasConstructor(val) { + return isObject(val) && typeof val.constructor !== 'undefined'; +} /** - * Shift a node from `node.nodes`. + * 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 - * 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 + * nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * nativeKeys(function(){}) + * //=> ['length', 'caller'] * ``` - * @return {Object} Returns the shifted `node` - * @api public + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. */ -Node.prototype.shift = function() { - return this.nodes && this.nodes.shift(); -}; +function nativeKeys(val) { + if (!hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +} /** - * Remove `node` from `node.nodes`. - * - * ```js - * node.remove(childNode); - * ``` - * @param {Object} `node` - * @return {Object} Returns the removed node. - * @api public + * Expose `copy` */ -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; -}; +module.exports = copy; /** - * 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 + * Expose `copy.has` for tests */ -Node.prototype.find = function(type) { - return utils.findNode(this.nodes, type); -}; +module.exports.has = has; -/** - * 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); +/***/ 59248: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * object-visit * - * 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 + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -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; +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.'); } -}); -/** - * 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 - */ + if (typeof method !== 'string') { + throw new Error('object-visit expects `method` name to be a string'); + } -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; + if (typeof thisArg[method] !== 'function') { + return thisArg; } -}); -/** - * 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); + 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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * object.pick * - * console.log(baz.prev.type) // 'bar' - * ``` - * @return {Object} - * @api public + * Copyright (c) 2014-2015 Jon Schlinkert, contributors. + * Licensed under the MIT License */ -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; + + +var isObject = __webpack_require__(96667); + +module.exports = function pick(obj, keys) { + if (!isObject(obj) && typeof obj !== 'function') { + return {}; } -}); -/** - * 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; + var res = {}; + if (typeof keys === 'string') { + if (keys in obj) { + res[keys] = obj[keys]; } - return null; + return res; } -}); -/** - * 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 - */ + var len = keys.length; + var idx = -1; -Object.defineProperty(Node.prototype, 'first', { - get: function() { - return this.nodes ? this.nodes[0] : null; + while (++idx < len) { + var key = keys[idx]; + if (key in obj) { + res[key] = obj[key]; + } } -}); + return res; +}; -/** - * 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); +/***/ 27255: +/***/ (function(module) { + +/*! + * pascalcase * - * console.log(foo.last.type) // 'qux' - * ``` - * @return {Object} The last node, or undefiend - * @api public + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -Object.defineProperty(Node.prototype, 'scope', { - get: function() { - if (this.isScope !== true) { - return this.parent ? this.parent.scope : this; - } - return this; +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(); + }); +} -/** - * Get own property names from Node prototype, but only the - * first time `Node` is instantiated - */ +module.exports = pascalcase; -function lazyKeys() { - if (!ownNames) { - ownNames = Object.getOwnPropertyNames(Node.prototype); - } -} -/** - * Simplified assertion. Throws an error is `val` is falsey. - */ +/***/ }), + +/***/ 88412: +/***/ (function(module) { + +"use strict"; -function assert(val, message) { - if (!val) throw new Error(message); -} /** - * Expose `Node` + * POSIX character classes */ -exports = module.exports = Node; +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' +}; /***/ }), -/***/ 88599: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 58404: +/***/ (function(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) { + /*! - * define-property - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + * 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 + } -var isDescriptor = __webpack_require__(44133); + , 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 + } -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); - } + return { + enumerable : op('enumerable') + , configurable : op('configurable') + , writable : op('writable') + , value : value + } + } - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); - } + , prr = function (obj, key, value, options) { + var k - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); - } + options = makeOptions(value, options) - return Object.defineProperty(obj, prop, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); -}; + 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 +}) /***/ }), -/***/ 82071: +/***/ 79822: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; +module.exports = __webpack_require__(76417).randomBytes -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 - */ +/***/ 42770: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -utils.isNode = function(node) { - return typeOf(node) === 'object' && node.isNode === true; -}; +"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. -/** - * 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 - */ +// 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. -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 - */ +var pna = __webpack_require__(58404); +/**/ -utils.append = function(val) { - return function(node) { - append(this, val, node); - }; +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; }; +/**/ -/** - * 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 - */ +module.exports = Duplex; -utils.toNoop = function(node, nodes) { - if (nodes) { - node.nodes = nodes; - } else { - delete node.nodes; - node.type = 'text'; - node.val = ''; +/**/ +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]; } -}; +} -/** - * 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 - */ +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); -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; -}; + Readable.call(this, options); + Writable.call(this, options); -/** - * 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 - */ + if (options && options.readable === false) this.readable = false; -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'); + if (options && options.writable === false) this.writable = false; - for (var i = 0; i < node.nodes.length; i++) { - utils.visit(node.nodes[i], fn); - } - return node; -}; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; -/** - * 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'); + this.once('end', onend); +} - if (typeof val === 'function') { - filter = val; - val = ''; +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; } +}); - 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; -}; +// 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; -/** - * 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 - */ + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} -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'); +function onEndNT(self) { + self.end(); +} - if (typeof val === 'function') { - filter = val; - val = ''; - } +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; + } - 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); + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; } - return close; +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); }; -/** - * 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'); +/***/ 60143: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - utils.addOpen(node, Node, filter); - utils.addClose(node, Node, filter); - return node; -}; +"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. -/** - * 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 - */ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -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 - */ +module.exports = PassThrough; -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'); +var Transform = __webpack_require__(62826); - node.define('parent', parent); - parent.nodes = parent.nodes || []; - parent.nodes.unshift(node); -}; +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ -/** - * 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 - */ +util.inherits(PassThrough, Transform); -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(); -}; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); -/** - * 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 - */ + Transform.call(this, options); +} -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(); +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; -/** - * 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'); +/***/ 79341: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!parent.nodes) { - return null; - } +"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. - 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'); - } - } -}; +var pna = __webpack_require__(58404); +/**/ -/** - * 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 - */ +module.exports = Readable; -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; -}; +/**/ +var isArray = __webpack_require__(21352); +/**/ -/** - * 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 - */ +/**/ +var Duplex; +/**/ -utils.firstOfType = function(nodes, type) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (utils.isType(node, type)) { - return node; - } - } -}; +Readable.ReadableState = ReadableState; -/** - * 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 - */ +/**/ +var EE = __webpack_require__(28614).EventEmitter; -utils.findNode = function(nodes, type) { - if (!Array.isArray(nodes)) { - return null; - } - if (typeof type === 'number') { - return nodes[type]; - } - return utils.firstOfType(nodes, type); +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; }; +/**/ -/** - * 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 - */ +/**/ +var Stream = __webpack_require__(1065); +/**/ -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 - */ +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; +} -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 - */ +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ -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; -}; +/**/ +var debugUtil = __webpack_require__(31669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ -/** - * 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 - */ +var BufferList = __webpack_require__(28878); +var destroyImpl = __webpack_require__(87915); +var StringDecoder; -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; -}; +util.inherits(Readable, Stream); -/** - * 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 - */ +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -utils.hasOpenAndClose = function(node) { - return utils.hasOpen(node) && utils.hasClose(node); -}; +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); -/** - * 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 - */ + // 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]]; +} -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'); +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); - var type = node.parent - ? node.parent.type - : node.type.replace(/\.open$/, ''); + options = options || {}; - if (!state.hasOwnProperty('inside')) { - state.inside = {}; - } - if (!state.inside.hasOwnProperty(type)) { - state.inside[type] = []; - } + // 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; - var arr = state.inside[type]; - arr.push(node); - return arr; -}; + // 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; -/** - * 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 - */ + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; -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'); + // 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; - var type = node.parent - ? node.parent.type - : node.type.replace(/\.close$/, ''); + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - if (state.inside.hasOwnProperty(type)) { - return state.inside[type].pop(); - } -}; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); -/** - * 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 - */ + // 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; -utils.isEmpty = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); + // 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; - 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); - } + // 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; - 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; - } - } + // has it been destroyed + this.destroyed = false; - return true; -}; + // 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'; -/** - * 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 - */ + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -utils.isInsideType = function(state, type) { - assert(isObject(state), 'expected state to be an object'); - assert(isString(type), 'expected type to be a string'); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (!state.hasOwnProperty('inside')) { - return 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; } +} - if (!state.inside.hasOwnProperty(type)) { - return false; - } +function Readable(options) { + Duplex = Duplex || __webpack_require__(42770); - return state.inside[type].length > 0; -}; + if (!(this instanceof Readable)) return new Readable(options); -/** - * 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 - */ + this._readableState = new ReadableState(options, this); -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'); + // legacy + this.readable = true; - if (Array.isArray(type)) { - for (var i = 0; i < type.length; i++) { - if (utils.isInside(state, node, type[i])) { - return true; - } - } - return false; - } + if (options) { + if (typeof options.read === 'function') this._read = options.read; - var parent = node.parent; - if (typeof type === 'string') { - return (parent && parent.type === type) || utils.isInsideType(state, type); + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - if (typeOf(type) === 'regexp') { - if (parent && parent.type && type.test(parent.type)) { - return true; + 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; } - 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]; + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); - if (Array.isArray(val) && val.length !== 0 && type.test(key)) { - return true; +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 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 - */ + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; -/** - * 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 - */ +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); + } -utils.arrayify = function(val) { - if (typeof val === 'string' && val !== '') { - return [val]; - } - if (!Array.isArray(val)) { - return []; + 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 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 - */ + return needMoreData(state); +} -utils.stringify = function(val) { - return utils.arrayify(val).join(','); -}; +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); -/** - * 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'; + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); } -/** - * Return true if val is a string - */ - -function isString(val) { - return typeof val === 'string'; +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; } -/** - * Return true if val is a function - */ - -function isFunction(val) { - return typeof val === 'function'; +// 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); } -/** - * Return true if val is an array - */ - -function isArray(val) { - return Array.isArray(val); -} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; -/** - * Shim to ensure the `.append` methods work with any version of snapdragon - */ +// 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; +}; -function append(compiler, val, node) { - if (typeof compiler.append !== 'function') { - return compiler.emit(val, node); +// 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 compiler.append(val, node); + return n; } -/** - * Simplified assertion. Throws an error is `val` is falsey. - */ - -function assert(val, message) { - if (!val) throw new Error(message); +// 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; -/***/ 79285: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // 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; + } -"use strict"; + 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; + } -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 = {}; + // 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. -/** - * Create a new instance of `Snapdragon` with the given `options`. - * - * ```js - * var snapdragon = new Snapdragon(); - * ``` - * - * @param {Object} `options` - * @api public - */ + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); -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); + // 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); + } - Object.defineProperty(this, 'compilers', { - get: function() { - return this.compiler.compilers; - } - }); + // 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); + } - Object.defineProperty(this, 'parsers', { - get: function() { - return this.parser.parsers; - } - }); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - Object.defineProperty(this, 'regex', { - get: function() { - return this.parser.regex; - } - }); -} + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } -/** - * Inherit Base - */ + 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; -Base.extend(Snapdragon); + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } -/** - * 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 - */ + if (ret !== null) this.emit('data', ret); -Snapdragon.prototype.capture = function() { - return this.parser.capture.apply(this.parser, arguments); + return ret; }; -/** - * 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; -}; +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; -/** - * 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 - */ + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} -Snapdragon.prototype.parse = function(str, options) { - this.options = utils.extend({}, this.options, options); - var parsed = this.parser.parse(str, this.options); +// 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); + } +} - // add non-enumerable parser reference - define(parsed, 'parser', this.parser); - return parsed; -}; +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} -/** - * 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 - */ +// 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); + } +} -Snapdragon.prototype.compile = function(ast, options) { - this.options = utils.extend({}, this.options, options); - var compiled = this.compiler.compile(ast, this.options); +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; +} - // add non-enumerable compiler reference - define(compiled, 'compiler', this.compiler); - return compiled; +// 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')); }; -/** - * Expose `Snapdragon` - */ +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -module.exports = Snapdragon; + 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); -/** - * Expose `Parser` and `Compiler` - */ + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; -module.exports.Compiler = Compiler; -module.exports.Parser = Parser; + 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(); + } -/***/ 33003: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // 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); -"use strict"; + 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; -var use = __webpack_require__(77709); -var define = __webpack_require__(5477); -var debug = __webpack_require__(31185)('snapdragon:compiler'); -var utils = __webpack_require__(622); + // 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(); + } -/** - * Create a new `Compiler` with the given `options`. - * @param {Object} `options` - */ + // 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(); + } + } -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); -} + // 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); + } -/** - * Prototype methods - */ + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); -Compiler.prototype = { + // 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); - /** - * Throw an error message with details including the cursor position. - * @param {String} `msg` Message to use in the Error. - */ + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - error: function(msg, node) { - var pos = node.position || {start: {column: 0}}; - var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; + // tell the dest that it's being piped to + dest.emit('pipe', src); - var err = new Error(message); - err.reason = msg; - err.column = pos.start.column; - err.source = this.pattern; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - if (this.options.silent) { - this.errors.push(err); - } else { - throw err; - } - }, + return dest; +}; - /** - * 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 - */ +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); + } + }; +} - define: function(key, val) { - define(this, key, val); - return this; - }, +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - /** - * Emit `node.val` - */ + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - emit: function(str, node) { - this.output += str; - return str; - }, + // 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; - /** - * Add a compiler `fn` with the given `name` - */ + if (!dest) dest = state.pipes; - set: function(name, fn) { - this.compilers[name] = fn; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); return this; - }, + } - /** - * Get compiler `name`. - */ + // slow case. multiple pipe destinations. - get: function(name) { - return this.compilers[name]; - }, + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - /** - * Get the previous AST node. - */ + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } - prev: function(n) { - return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; - }, + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - /** - * Get the next AST node. - */ + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - next: function(n) { - return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; - }, + dest.emit('unpipe', this, unpipeInfo); - /** - * Visit `node`. - */ + return this; +}; - visit: function(node, nodes, i) { - var fn = this.compilers[node.type]; - this.idx = i; +// 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 (typeof fn !== 'function') { - throw this.error('compiler "' + node.type + '" is not registered', node); + 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 fn.call(this, node, nodes, i); - }, + } - /** - * Map visit over array of `nodes`. - */ + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; - 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; - }, +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} - /** - * Compile `ast`. - */ +// 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; +}; - compile: function(ast, options) { - var opts = utils.extend({}, this.options, options); - this.ast = ast; - this.parsingErrors = this.ast.errors; - this.output = ''; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} - // 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; - } +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - this.mapVisit(this.ast.nodes); - return this; + 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; }; -/** - * Expose `Compiler` - */ - -module.exports = Compiler; +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; -/***/ 35573: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -"use strict"; + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -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); + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -/** - * Create a new `Parser` with the given `input` and `options`. - * @param {String} `input` - * @param {Object} `options` - * @api public - */ + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); -function Parser(options) { - debug('initializing', __filename); - this.options = utils.extend({source: 'string'}, options); - this.init(this.options); - use(this); -} + // 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); + } + } -/** - * Prototype methods - */ + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } -Parser.prototype = { - constructor: Parser, + // 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(); + } + }; - init: function(options) { - this.orig = ''; - this.input = ''; - this.parsed = ''; + return this; +}; - this.column = 1; - this.line = 1; +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; + } +}); - 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'; +// exposed for testing purposes only. +Readable._fromList = fromList; - var pos = this.position(); - this.bos = pos({type: 'bos', val: ''}); +// 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; - this.ast = { - type: 'root', - errors: this.errors, - nodes: [this.bos] - }; + 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); + } - define(this.bos, 'parent', this.ast); - this.nodes = [this.ast]; + return ret; +} - this.count = 0; - this.setCount = 0; - this.stack = []; - }, +// 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; +} - /** - * Throw a formatted error with the cursor column and `msg`. - * @param {String} `msg` Message to use in the Error. - */ +// 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; +} - 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; +// 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; +} - var message = source + ' : ' + msg; - var err = new Error(message); - err.source = source; - err.reason = msg; - err.pos = pos; +function endReadable(stream) { + var state = stream._readableState; - if (this.options.silent) { - this.errors.push(err); - } else { - throw err; - } - }, + // 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'); - /** - * 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; - }, + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} - /** - * Mark position and patch `node.position`. - */ +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'); + } +} - position: function() { - var start = { line: this.line, column: this.column }; - var self = this; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} - 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 - */ +/***/ 62826: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - set: function(type, fn) { - if (this.types.indexOf(type) === -1) { - this.types.push(type); - } - this.parsers[type] = fn.bind(this); - return this; - }, +"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. - /** - * Get parser `name` - * @param {String} `name` - * @api public - */ +// 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. - 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); - }, +module.exports = Transform; - /** - * Pop a token off of the `type` stack - * @param {String} `type` - * @returns {Object} Returns a token - * @api public - */ +var Duplex = __webpack_require__(42770); - pop: function(type) { - this.sets[type] = this.sets[type] || []; - this.count--; - this.stack.pop(); - return this.sets[type].pop(); - }, +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ - /** - * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. - * - * @param {String} `type` - * @return {Boolean} - * @api public - */ +util.inherits(Transform, Duplex); - isInside: function(type) { - this.sets[type] = this.sets[type] || []; - return this.sets[type].length > 0; - }, +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; - /** - * Return true if `node` is the given `type`. - * - * ```js - * parser.isType(node, 'brace'); - * ``` - * @param {Object} `node` - * @param {String} `type` - * @return {Boolean} - * @api public - */ + var cb = ts.writecb; - isType: function(node, type) { - return node && node.type === type; - }, + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } - /** - * Get the previous AST node - * @return {Object} - */ + ts.writechunk = null; + ts.writecb = null; - prev: function(n) { - return this.stack.length > 0 - ? utils.last(this.stack, n) - : utils.last(this.nodes, n); - }, + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); - /** - * Update line and column based on `str`. - */ + cb(er); - consume: function(len) { - this.input = this.input.substr(len); - }, + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} - /** - * Update column based on `str`. - */ +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - 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); - }, + Duplex.call(this, options); - /** - * Match `regex`, return captures, and update the cursor position by `match[0]` length. - * @param {RegExp} `regex` - * @return {Object} - */ + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; - match: function(regex) { - var m = regex.exec(this.input); - if (m) { - this.updatePosition(m[0], m[0].length); - return m; - } - }, + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - /** - * Capture `type` with the given regex. - * @param {String} `type` - * @param {RegExp} `regex` - * @return {Function} - */ + // 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; - capture: function(type, regex) { - if (typeof regex === 'function') { - return this.set.apply(this, arguments); - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - 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; + if (typeof options.flush === 'function') this._flush = options.flush; + } - var prev = this.prev(); - var node = pos({ - type: type, - val: m[0], - parsed: parsed, - rest: this.input - }); + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} - if (m[1]) { - node.inner = m[1]; - } +function prefinish() { + var _this = this; - define(node, 'inside', this.stack.length > 0); - define(node, 'parent', prev); - prev.nodes.push(node); - }.bind(this)); - return this; - }, + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} - /** - * Create a parser with open and close for parens, - * brackets or braces - */ +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - capturePair: function(type, openRegex, closeRegex, fn) { - this.sets[type] = this.sets[type] || []; +// 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'); +}; - /** - * Open - */ +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); + } +}; - this.set(type + '.open', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(openRegex); - if (!m || !m[0]) return; +// 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; - var val = m[0]; - this.setCount++; - this.specialChars = true; - var open = pos({ - type: type + '.open', - val: val, - rest: this.input - }); + 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; + } +}; - if (typeof m[1] !== 'undefined') { - open.inner = m[1]; - } +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; - var prev = this.prev(); - var node = pos({ - type: type, - nodes: [open] - }); + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; - define(node, 'rest', this.input); - define(node, 'parsed', parsed); - define(node, 'prefix', m[1]); - define(node, 'parent', prev); - define(open, 'parent', node); +function done(stream, er, data) { + if (er) return stream.emit('error', er); - if (typeof fn === 'function') { - fn.call(this, open, node); - } + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); - this.push(type, node); - prev.nodes.push(node); - }); + // 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'); - /** - * Close - */ + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - this.set(type + '.close', function() { - var pos = this.position(); - var m = this.match(closeRegex); - if (!m || !m[0]) return; + return stream.push(null); +} - 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 + '"'); - } +/***/ 78063: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.setCount--; - node.escaped = true; - return node; - } +"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. - if (node.suffix === '\\') { - parent.escaped = true; - node.escaped = true; - } +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - 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(); +var pna = __webpack_require__(58404); +/**/ - while (prev.type !== 'root' && !prev.visited) { - if (this.options.strict === true) { - throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); - } +module.exports = Writable; - if (!hasDelims(prev)) { - prev.parent.escaped = true; - prev.escaped = true; - } +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - visit(prev, function(node) { - if (!hasDelims(node.parent)) { - node.parent.escaped = true; - node.escaped = true; - } - }); +// 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; - prev = prev.parent; - } + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - 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; - } - } - }, +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ - /** - * Parse the given string. - * @return {Array} - */ +/**/ +var Duplex; +/**/ - parse: function(input) { - if (typeof input !== 'string') { - throw new TypeError('expected a string'); - } +Writable.WritableState = WritableState; - this.init(this.options); - this.orig = input; - this.input = input; - var self = this; +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ - function parse() { - // check input before calling `.next()` - input = self.input; +/**/ +var internalUtil = { + deprecate: __webpack_require__(92262) +}; +/**/ - // 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); - } - } +/**/ +var Stream = __webpack_require__(1065); +/**/ - 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) + '"'); - } - } +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; +} - 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); - } +var destroyImpl = __webpack_require__(87915); - return this.ast; - } -}; +util.inherits(Writable, Stream); -/** - * Visit `node` with the given `fn` - */ +function nop() {} -function visit(node, fn) { - if (!node.visited) { - define(node, 'visited', true); - return node.nodes ? mapVisit(node.nodes, fn) : fn(node); - } - return node; -} +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); -/** - * Map visit over array of `nodes`. - */ + options = options || {}; -function mapVisit(nodes, fn) { - var len = nodes.length; - var idx = -1; - while (++idx < len) { - visit(nodes[idx], fn); - } -} + // 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; -function hasOpen(node) { - return node.nodes && node.nodes[0].type === (node.type + '.open'); -} + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; -function hasClose(node) { - return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); -} + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; -function hasDelims(node) { - return hasOpen(node) && hasClose(node); -} + // 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; -/** - * Expose `Parser` - */ + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; -module.exports = Parser; + // 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; -/***/ 7974: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // has it been destroyed + this.destroyed = false; -"use strict"; + // 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'; -var define = __webpack_require__(5477); + // 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; -/** - * Store position for a node - */ + // a flag to see when we're in the middle of a write. + this.writing = false; -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); -}; + // 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; -/***/ 59657: -/***/ (function(module, exports, __webpack_require__) { + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; -"use strict"; + // 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; -var fs = __webpack_require__(35747); -var path = __webpack_require__(85622); -var define = __webpack_require__(5477); -var utils = __webpack_require__(622); + this.bufferedRequest = null; + this.lastBufferedRequest = null; -/** - * 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 - */ + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; -module.exports = mixin; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; -/** - * Mixin source map support into `compiler`. - * - * @param {Object} `compiler` - * @api public - */ + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; -function mixin(compiler) { - define(compiler, '_comment', compiler.comment); - compiler.map = new utils.SourceMap.SourceMapGenerator(); - compiler.position = { line: 1, column: 1 }; - compiler.content = {}; - compiler.files = {}; + // count buffered requests + this.bufferedRequestCount = 0; - for (var key in exports) { - define(compiler, key, exports[key]); - } + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); } -/** - * 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; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; }; -/** - * Emit `str` with `position`. - * - * @param {String} str - * @param {Object} [pos] - * @return {String} - */ +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); -exports.emit = function(str, node) { - var position = node.position || {}; - var source = position.source; - if (source) { - if (position.filepath) { - source = utils.unixify(position.filepath); +// 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; + }; +} - 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 - } - }); +function Writable(options) { + Duplex = Duplex || __webpack_require__(42770); - if (position.content) { - this.addContent(source, position); - } - if (position.filepath) { - this.addFile(source, position); - } + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. - this.updatePosition(str); - this.output += str; + // 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); } - 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; -}; + this._writableState = new WritableState(options, this); -/** - * Adds a content source to the source map output if it has not already been added - * @param {String} `source` - * @param {Object} `position` - */ + // legacy. + this.writable = true; -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); -}; + if (options) { + if (typeof options.write === 'function') this._write = options.write; -/** - * Applies any original source maps to the output and embeds the source file - * contents in the source map. - */ + if (typeof options.writev === 'function') this._writev = options.writev; -exports.applySourceMaps = function() { - Object.keys(this.files).forEach(function(file) { - var content = this.files[file]; - this.map.setSourceContent(file, content); + if (typeof options.destroy === 'function') this._destroy = options.destroy; - 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); -}; + if (typeof options.final === 'function') this._final = options.final; + } -/** - * Process comments, drops sourceMap comments. - * @param {Object} node - */ + Stream.call(this); +} -exports.comment = function(node) { - if (/^# sourceMappingURL=/.test(node.comment)) { - return this.emit('', node.position); - } - return this._comment(node); +// 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); +} -/***/ }), - -/***/ 622: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +// 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; -"use strict"; + 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); -/** - * Module dependencies - */ + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -exports.extend = __webpack_require__(28727); -exports.SourceMap = __webpack_require__(96241); -exports.sourceMapResolve = __webpack_require__(10227); + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -/** - * Convert backslash in the given string to forward slashes - */ + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; -exports.unixify = function(fp) { - return fp.split(/\\+/).join('/'); -}; + if (typeof cb !== 'function') cb = nop; -/** - * Return true if `val` is a non-empty string - * - * @param {String} `str` - * @return {Boolean} - */ + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } -exports.isString = function(str) { - return str && typeof str === 'string'; + return ret; }; -/** - * Cast `val` to an array - * @return {Array} - */ +Writable.prototype.cork = function () { + var state = this._writableState; -exports.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; + state.corked++; }; -/** - * Get the last `n` element from the given `array` - * @param {Array} `array` - * @return {*} - */ - -exports.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; +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); + } +}; -/***/ 56609: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -var decodeUriComponent = __webpack_require__(95748) +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 customDecodeUriComponent(string) { - // `decodeUriComponent` turns `+` into ` `, but that's not wanted. - return decodeUriComponent(string.replace(/\+/g, "%2B")) +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; } -module.exports = customDecodeUriComponent +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; -/***/ 89825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; -var url = __webpack_require__(78835) + 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); + } -function resolveUrl(/* ...urls */) { - return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { - return url.resolve(resolved, nextUrl) - }) + return ret; } -module.exports = resolveUrl +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); + } +} -/***/ 10227: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -var sourceMappingURL = __webpack_require__(21707) +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -var resolveUrl = __webpack_require__(89825) -var decodeUriComponent = __webpack_require__(56609) -var urix = __webpack_require__(67806) -var atob = __webpack_require__(83327) + 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); + } -function callbackAsync(callback, error, result) { - setImmediate(function() { callback(error, result) }) + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } } -function parseMapToJSON(string, data) { - try { - return JSON.parse(string.replace(/^\)\]\}'/, "")) - } catch (error) { - error.sourceMapData = data - throw error - } +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); } -function readSync(read, url, data) { - var readUrl = decodeUriComponent(url) - try { - return String(read(readUrl)) - } catch (error) { - error.sourceMapData = data - throw error +// 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; -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) + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - mapData.map = String(result) - try { - mapData.map = parseMapToJSON(mapData.map, mapData) - } catch (error) { - return callback(error) + 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); } - callback(null, mapData) - }) -} + 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; -function resolveSourceMapSync(code, codeUrl, read) { - var mapData = resolveSourceMapHelper(code, codeUrl) - if (!mapData || mapData.map) { - return mapData + 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; } - mapData.map = readSync(read, mapData.url, mapData) - mapData.map = parseMapToJSON(mapData.map, mapData) - return mapData -} -var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ + state.bufferedRequest = entry; + state.bufferProcessing = false; +} -/** - * 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$/ +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; -/** - * 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" +Writable.prototype._writev = null; -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 -} +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; -function decodeBase64String(b64) { - if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { - return atob(b64) + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - 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) + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - var url = sourceMappingURL.getFrom(code) - if (!url) { - return null + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - 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 + // 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); } - try { - data.map = parseMapToJSON( - lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), - data - ) - } catch (error) { - error.sourceMapData = data - throw error + 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'); } - return data } +} - var mapUrl = resolveUrl(codeUrl, url) - return { - sourceMappingURL: url, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null +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 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: [] +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; +} - if (pending === 0) { - callbackAsync(callback, null, result) - return +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; } - - var done = function() { - pending-- - if (pending === 0) { - callback(null, result) - } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; } +} - 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() - }) +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; } - }) -} -function resolveSourcesSync(map, mapUrl, read, options) { - var result = { - sourcesResolved: [], - sourcesContent: [] + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; } +}); - if (!map.sources || map.sources.length === 0) { - return result - } +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; - 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 -} +/***/ 28878: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var endingSlash = /\/?$/ +"use strict"; -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 _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 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 +function copyBuffer(src, target, offset) { + src.copy(target, offset); } +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); -/***/ }), - -/***/ 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*" - ) + this.head = null; + this.tail = null; + this.length = 0; + } - return { + 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; + }; - regex: regex, - _innerRegex: innerRegex, + 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; + }; - getFrom: function(code) { - var match = code.match(regex) - return (match ? match[1] || match[2] || "" : null) - }, + 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; + }; - existsIn: function(code) { - return regex.test(code) - }, + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; - removeFrom: function(code) { - return code.replace(regex, "") - }, + 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; + }; - 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 - } + 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; + }; +} /***/ }), -/***/ 33218: +/***/ 87915: /***/ (function(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); +var pna = __webpack_require__(58404); +/**/ -module.exports = function(str, options, fn) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; - if (typeof options === 'function') { - fn = options; - options = null; - } + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - // allow separator to be defined as a string - if (typeof options === 'string') { - options = { sep: options }; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; } - var opts = extend({sep: '.'}, options); - var quotes = opts.quotes || ['"', "'", '`']; - var brackets; + // 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 (opts.brackets === true) { - brackets = { - '<': '>', - '(': ')', - '[': ']', - '{': '}' - }; - } else if (opts.brackets) { - brackets = opts.brackets; + if (this._readableState) { + this._readableState.destroyed = true; } - 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]]; - } + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - 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); + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; } - - tok.val = ch; - tok.idx = idx = closeIdx; - } - - if (typeof fn === 'function') { - fn(tok, tokens); - ch = tok.val; - idx = tok.idx; + } else if (cb) { + cb(err); } + }); - if (tok.val === sep && tok.split !== false) { - arr.push(''); - continue; - } + return this; +} - arr[arr.length - 1] += tok.val; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - 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); + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } - 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] === '\\'; +function emitErrorNT(self, err) { + self.emit('error', err); } +module.exports = { + destroy: destroy, + undestroy: undestroy +}; /***/ }), -/***/ 66889: +/***/ 1065: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; +module.exports = __webpack_require__(92413); -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; -}; +/***/ 96788: +/***/ (function(module, exports, __webpack_require__) { -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } +/* 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 isString(val) { - return (val && typeof val === 'string'); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; +// 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 obj; + return Buffer(arg, encodingOrOffset, length) } -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); +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 } -/** - * Returns true if the given `key` is an own property of `obj`. - */ - -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) } -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } /***/ }), -/***/ 28730: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 7395: +/***/ (function(__unused_webpack_module, 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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/*! - * static-extend - * - * Copyright (c) 2016, Jon Schlinkert. - * Licensed under the MIT License. - */ +// 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 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 - */ +var Buffer = __webpack_require__(96788).Buffer; +/**/ -function extend(Parent, extendFn) { - if (typeof Parent !== 'function') { - throw new TypeError('expected Parent to be a function.'); +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; } +}; - 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); +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; } - - Ctor.extend = extend(Ctor, extendFn); - }; + } }; -/** - * Expose `extend` - */ - -module.exports = extend; - - -/***/ }), - -/***/ 16326: -/***/ (function(__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)); +// 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; +} -var _isWsl = _interopRequireDefault(__webpack_require__(47543)); +// 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); +} -var _minify = _interopRequireDefault(__webpack_require__(30787)); +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 || ''; +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +StringDecoder.prototype.end = utf8End; -const worker = __webpack_require__.ab + "worker.js"; +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; -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 +// 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; +}; - 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 +// 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; +} - this.maxConcurrentWorkers = _isWsl.default ? 1 : parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); +// 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; } - - run(tasks, callback) { - /* istanbul ignore if */ - if (!tasks.length) { - callback(null, []); - return; + 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; +} - 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); - } - }; +// 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'; } - - let toRun = tasks.length; - const results = []; - - const step = (index, data) => { - toRun -= 1; - results[index] = data; - - if (!toRun) { - callback(null, results); + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; } - }; + } + } +} - tasks.forEach((task, index) => { - const enqueue = () => { - this.boundWorkers(task, (error, data) => { - const result = error ? { - error - } : data; +// 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; +} - const done = () => step(index, result); +// 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); +} - if (this.cacheDir && !result.error) { - _cacache.default.put(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys), JSON.stringify(data)).then(done, done); - } else { - done(); - } - }); - }; +// 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; +} - if (this.cacheDir) { - _cacache.default.get(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys)).then(({ - data - }) => step(index, JSON.parse(data)), enqueue); - } else { - enqueue(); +// 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); +} - exit() { - if (this.workers) { - _workerFarm.default.end(this.workers); - } +// 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); } -exports.default = TaskRunner; +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); +} -/***/ 89301: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} -"use strict"; +/***/ }), +/***/ 68193: +/***/ (function(module, exports, __webpack_require__) { -const plugin = __webpack_require__(43884); +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); +} -module.exports = plugin.default; /***/ }), -/***/ 43884: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 30931: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; - -var _crypto = _interopRequireDefault(__webpack_require__(76417)); +var extend = __webpack_require__(39700); +var safe = __webpack_require__(71217); -var _path = _interopRequireDefault(__webpack_require__(85622)); +/** + * 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 + */ -var _sourceMap = __webpack_require__(96241); +function toRegex(pattern, options) { + return new RegExp(toRegex.create(pattern, options)); +} -var _webpackSources = __webpack_require__(53665); +/** + * 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 + */ -var _RequestShortener = _interopRequireDefault(__webpack_require__(54254)); +toRegex.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } -var _ModuleFilenameHelpers = _interopRequireDefault(__webpack_require__(71474)); + var opts = extend({}, options); + if (opts.contains === true) { + opts.strictNegate = false; + } -var _schemaUtils = _interopRequireDefault(__webpack_require__(33225)); + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var endChar = opts.endChar ? opts.endChar : '+'; + var str = pattern; -var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); + if (opts.strictNegate === false) { + str = '(?:(?!(?:' + pattern + ')).)' + endChar; + } else { + str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; + } -var _package = _interopRequireDefault(__webpack_require__(92203)); + var res = open + str + close; + if (opts.safe === true && safe(res) === false) { + throw new Error('potentially unsafe regular expression: ' + res); + } -var _options = _interopRequireDefault(__webpack_require__(11840)); + return res; +}; -var _TaskRunner = _interopRequireDefault(__webpack_require__(16326)); +/** + * Expose `toRegex` + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = toRegex; -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; } +/***/ 39700: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/; +"use strict"; -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'); - } +var isExtendable = __webpack_require__(93295); +var assignSymbols = __webpack_require__(64353); - static buildSourceMap(inputSourceMap) { - if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) { - return null; +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 new _sourceMap.SourceMapConsumer(inputSourceMap); } + return obj; +}; - 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}`); +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; } - - 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); +function isString(val) { + return (val && typeof val === 'string'); +} - if (match) { - const line = +match[1]; - const column = +match[2]; - const original = sourceMap.originalPositionFor({ - line, - column - }); +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} - if (original && original.source && original.source !== file && requestShortener) { - ({ - source - } = original); - warningMessage = `${warningMessage.replace(warningRegex, '')}`; - locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`; - } - } - } +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} - if (warningsFilter && !warningsFilter(warning, source)) { - return null; - } +/** + * Returns true if the given `key` is an own property of `obj`. + */ - return `Terser Plugin: ${warningMessage}${locationMessage}`; - } +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - apply(compiler) { - const buildModuleFn = moduleArg => { - // to get detailed location info about errors - moduleArg.useSourceMap = true; - }; +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} - 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; +/***/ 93295: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (this.options.sourceMap && asset.sourceAndMap) { - const { - source, - map - } = asset.sourceAndMap(); - input = source; +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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; +var isPlainObject = __webpack_require__(81064); - if (this.options.extractComments) { - commentsFile = this.options.extractComments.filename || `${file}.LICENSE`; +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; - 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); - } +/***/ 69523: +/***/ (function(module) { - 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; - } +"use strict"; +/*! + * repeat-element + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Licensed under the MIT license. + */ - 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 +module.exports = function repeat(ele, num) { + var arr = new Array(num); - if (error) { - compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context))); - return; - } + for (var i = 0; i < num; i++) { + arr[i] = ele; + } - let outputSource; + return arr; +}; - 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)); - } +/***/ 6332: +/***/ (function(module) { - 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)}`; +"use strict"; +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - 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`); +/** + * Results cache + */ - 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 +var res = ''; +var cache; +/** + * Expose `repeat` + */ - processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings +module.exports = repeat; - if (warnings && warnings.length > 0) { - warnings.forEach(warning => { - const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter); +/** + * 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 + */ - if (builtWarning) { - compilation.warnings.push(builtWarning); - } - }); - } - }); - taskRunner.exit(); - callback(); - }); - }; +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - const plugin = { - name: this.constructor.name - }; - compiler.hooks.compilation.tap(plugin, compilation => { - if (this.options.sourceMap) { - compilation.hooks.buildModule.tap(plugin, buildModuleFn); - } + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; - const { - mainTemplate, - chunkTemplate - } = compilation; // Regenerate `contenthash` for minified assets + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } - 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); - }); - } + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } - compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation)); - }); + num >>= 1; + str += str; } + res += str; + res = res.substr(0, max); + return res; } -var _default = TerserPlugin; -exports.default = _default; /***/ }), -/***/ 30787: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; +/***/ 25622: +/***/ (function(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); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; -var _terser = __webpack_require__(54775); +module.exports = function(regexpStr) { + var i = 0, l, c, + start = { type: types.ROOT, stack: []}, -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; } + // Keep track of last clause/group and stack. + lastGroup = start, + last = start.stack, + groupStack = []; -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 repeatErr = function(i) { + util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); + }; -const buildTerserOptions = ({ - ecma, - warnings, - parse = {}, - compress = {}, - mangle, - module, - output, - toplevel, - nameCache, - ie8, + // Decode a few escaped characters. + var str = util.strToChars(regexpStr); + l = str.length; - /* eslint-disable camelcase */ - keep_classnames, - keep_fnames, + // Iterate through each character in string. + while (i < l) { + c = str[i++]; - /* 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 -}); + switch (c) { + // Handle escaped characters, inclues a few sets. + case '\\': + c = str[i++]; -const buildComments = (options, terserOptions, extractedComments) => { - const condition = {}; - const commentsOpts = terserOptions.output.comments; // Use /^\**!|@preserve|@license|@cc_on/i RegExp + switch (c) { + case 'b': + last.push(positions.wordBoundary()); + break; - 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 + case 'B': + last.push(positions.nonWordBoundary()); + break; + case 'w': + last.push(sets.words()); + break; - ['preserve', 'extract'].forEach(key => { - let regexStr; - let regex; + case 'W': + last.push(sets.notWords()); + break; - switch (typeof condition[key]) { - case 'boolean': - condition[key] = condition[key] ? () => true : () => false; - break; + case 'd': + last.push(sets.ints()); + break; - case 'function': - break; + case 'D': + last.push(sets.notInts()); + break; - case 'string': - if (condition[key] === 'all') { - condition[key] = () => true; + case 's': + last.push(sets.whitespace()); + break; - break; - } + case 'S': + last.push(sets.notWhitespace()); + break; - if (condition[key] === 'some') { - condition[key] = (astNode, comment) => { - return comment.type === 'comment2' && /^\**!|@preserve|@license|@cc_on/i.test(comment.value); - }; + 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) }); - break; + // Escaped character. + } else { + last.push({ type: types.CHAR, value: c.charCodeAt(0) }); + } } - 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; + // Positionals. + case '^': + last.push(positions.begin()); + break; - if (minifyFn) { - return minifyFn({ - [file]: input - }, inputSourceMap); - } // Copy terser options + case '$': + last.push(positions.end()); + break; - const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap + // Handle custom sets. + case '[': + // Check if this class is 'anti' i.e. [^abc]. + var not; + if (str[i] === '^') { + not = true; + i++; + } else { + not = false; + } - if (inputSourceMap) { - terserOptions.sourceMap = true; - } + // Get all the characters in class. + var classTokens = util.tokenizeClass(str.slice(i), regexpStr); - const extractedComments = []; + // Increase index by length of class. + i += classTokens[1]; + last.push({ + type: types.SET, + set: classTokens[0], + not: not, + }); - if (extractComments) { - terserOptions.output.comments = buildComments(options, terserOptions, extractedComments); - } + break; - const { - error, - map, - code, - warnings - } = (0, _terser.minify)({ - [file]: input - }, terserOptions); - return { - error, - map, - code, - warnings, - extractedComments - }; -}; -var _default = minify; -exports.default = _default; + // Class of any character except \n. + case '.': + last.push(sets.anyChar()); + break; -/***/ }), -/***/ 71708: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Push group onto stack. + case '(': + // Create group. + var group = { + type: types.GROUP, + stack: [], + remember: true, + }; -"use strict"; -/*! - * to-object-path - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + 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; -var typeOf = __webpack_require__(48865); + // Match if not followed by. + } else if (c === '!') { + group.notFollowedBy = true; -module.exports = function toPath(args) { - if (typeOf(args) !== 'arguments') { - args = arguments; - } - return filter(args).join('.'); -}; + } else if (c !== ':') { + util.error(regexpStr, + 'Invalid group, character \'' + c + + '\' after \'?\' at column ' + (i - 1)); + } -function filter(arr) { - var len = arr.length; - var idx = -1; - var res = []; + group.remember = false; + } - 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; -} + // 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; -/***/ 51279: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; + // 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; -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 - */ + // 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; + } -var cache = {}; + // Create a new stack and add to options for rest of clause. + var stack = []; + lastGroup.options.push(stack); + last = stack; + break; -/** - * 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); -}; + // 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; -/** - * 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 - */ + last.push({ + type: types.REPETITION, + min: min, + max: max, + value: last.pop(), + }); + } else { + last.push({ + type: types.CHAR, + value: 123, + }); + } + break; -function makeRe(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } + case '?': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: 1, + value: last.pop(), + }); + break; - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } + case '+': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 1, + max: Infinity, + value: last.pop(), + }); + break; - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } + case '*': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: Infinity, + value: last.pop(), + }); + break; - 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]; + // Default is a character that is not `\[](){}?+*^$`. + default: + last.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); } - } - 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; + // Check if any groups have not been closed. + if (groupStack.length !== 0) { + util.error(regexpStr, 'Unterminated group'); } - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var flags = opts.flags || ''; - var regex; + return start; +}; - if (opts.nocase === true && !/i/.test(flags)) { - flags += 'i'; - } +module.exports.types = types; - 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); - } +/***/ 54771: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - } catch (err) { - if (opts.strictErrors === true || opts.safe === true) { - err.key = key; - err.pattern = pattern; - err.originalOptions = options; - err.createdOptions = opts; - throw err; - } +var types = __webpack_require__(40432); - try { - regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); - } catch (err) { - regex = /.^/; //<= match nothing - } - } +exports.wordBoundary = function() { + return { type: types.POSITION, value: 'b' }; +}; - if (opts.cache !== false) { - memoize(regex, key, pattern, opts); - } - return regex; -} +exports.nonWordBoundary = function() { + return { type: types.POSITION, value: 'B' }; +}; -/** - * 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. - */ +exports.begin = function() { + return { type: types.POSITION, value: '^' }; +}; -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; -} +exports.end = function() { + return { type: types.POSITION, value: '$' }; +}; -/** - * 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` - */ +/***/ 28135: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -module.exports.makeRe = makeRe; +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()); +}; -/***/ 74998: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +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 } + ]; +}; -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ +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 }; +}; -var isobject = __webpack_require__(96667); -var isDescriptor = __webpack_require__(44133); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; +exports.ints = function() { + return { type: types.SET, set: INTS(), not: false }; +}; -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'); - } +exports.notInts = function() { + return { type: types.SET, set: INTS(), not: true }; +}; - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } +exports.whitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: false }; +}; - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } +exports.notWhitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: true }; +}; - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); +exports.anyChar = function() { + return { type: types.SET, set: NOTANYCHAR(), not: true }; +}; - return obj; + +/***/ }), + +/***/ 40432: +/***/ (function(module) { + +module.exports = { + ROOT : 0, + GROUP : 1, + POSITION : 2, + SET : 3, + RANGE : 4, + REPETITION : 5, + REFERENCE : 6, + CHAR : 7, }; /***/ }), -/***/ 99793: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 10265: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; +var types = __webpack_require__(40432); +var sets = __webpack_require__(28135); -var isExtendable = __webpack_require__(78947); -var assignSymbols = __webpack_require__(64353); +// All of these are private and only used by randexp. +// It's assumed that they will always be called with the correct input. -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); +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; } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); + + 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 obj; + + return c; + }); + + return str; }; -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'); -} +/** + * 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; -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; + + 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]; + } } - return obj; -} -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + exports.error(regexpStr, 'Unterminated character class'); +}; + /** - * Returns true if the given `key` is an own property of `obj`. + * Shortcut to throw errors. + * + * @param {String} regexp + * @param {String} msg */ +exports.error = function(regexp, msg) { + throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); +}; -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +/***/ }), + +/***/ 71217: +/***/ (function(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]'; } /***/ }), -/***/ 78947: +/***/ 85841: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ -var isPlainObject = __webpack_require__(81064); +var randomBytes = __webpack_require__(79822); -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +// 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= 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); -}); +module.exports = function serialize(obj, options) { + options || (options = {}); + // Backwards-compatibility for `space` as the second argument. + if (typeof options === 'number' || typeof options === 'string') { + options = {space: options}; + } -/***/ }), + var functions = []; + var regexps = []; + var dates = []; + var maps = []; + var sets = []; + var undefs = []; + var infinities= []; -/***/ 7716: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Returns placeholders for functions and regexps (identified by index) + // which are later replaced by their string representation. + function replacer(key, value) { -"use strict"; + // For nested function + if(options.ignoreFunction){ + deleteFunctions(value); + } + if (!value && value !== undefined) { + return value; + } -var isObject = __webpack_require__(18493); -var union = __webpack_require__(69123); -var get = __webpack_require__(89304); -var set = __webpack_require__(34857); + // If the value is an object w/ a toJSON method, toJSON is called before + // the replacer runs, so we use this[key] to get the non-toJSONed value. + var origValue = this[key]; + var type = typeof origValue; -module.exports = function unionValue(obj, prop, value) { - if (!isObject(obj)) { - throw new TypeError('union-value expects the first argument to be an object.'); - } + if (type === 'object') { + if(origValue instanceof RegExp) { + return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@'; + } - if (typeof prop !== 'string') { - throw new TypeError('union-value expects `prop` to be a string.'); - } + if(origValue instanceof Date) { + return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@'; + } - var arr = arrayify(get(obj, prop)); - set(obj, prop, union(arr, arrayify(value))); - return obj; -}; + if(origValue instanceof Map) { + return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@'; + } -function arrayify(val) { - if (val === null || typeof val === 'undefined') { - return []; - } - if (Array.isArray(val)) { - return val; - } - return [val]; -} + if(origValue instanceof Set) { + return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@'; + } + } + if (type === 'function') { + return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@'; + } -/***/ }), + if (type === 'undefined') { + return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@'; + } -/***/ 5834: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) { + return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@'; + } -"use strict"; -/*! - * unset-value - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + return value; + } + function serializeFunc(fn) { + var serializedFn = fn.toString(); + if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) { + throw new TypeError('Serializing native function: ' + fn.name); + } + // pure functions, example: {key: function() {}} + if(IS_PURE_FUNCTION.test(serializedFn)) { + return serializedFn; + } -var isObject = __webpack_require__(96667); -var has = __webpack_require__(77735); + // arrow functions, example: arg1 => arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } -module.exports = function unset(obj, prop) { - if (!isObject(obj)) { - throw new TypeError('expected an object.'); - } - if (obj.hasOwnProperty(prop)) { - delete obj[prop]; - return true; - } + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); - 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; -}; + 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; + } -/***/ 77735: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // 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); + } -"use strict"; -/*! - * has-value - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ + 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); + } -var isObject = __webpack_require__(78037); -var hasValues = __webpack_require__(38719); -var get = __webpack_require__(89304); + // 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); + } -module.exports = function(obj, prop, noZero) { - if (isObject(obj)) { - return hasValues(get(obj, prop), noZero); - } - return hasValues(obj, prop); -}; + 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() + "\")"; + } -/***/ 78037: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } -"use strict"; -/*! - * isobject - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + 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' + } -var isArray = __webpack_require__(21352); + if (type === 'I') { + return infinities[valueIndex]; + } -module.exports = function isObject(val) { - return val != null && typeof val === 'object' && isArray(val) === false; -}; + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); +} /***/ }), -/***/ 38719: -/***/ (function(module) { +/***/ 34857: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /*! - * has-values + * set-value * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -module.exports = function hasValue(o, noZero) { - if (o === null || o === undefined) { - return false; - } +var split = __webpack_require__(33218); +var extend = __webpack_require__(28727); +var isPlainObject = __webpack_require__(81064); +var isObject = __webpack_require__(18493); - if (typeof o === 'boolean') { - return true; +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; } - if (typeof o === 'number') { - if (o === 0 && noZero === true) { - return false; - } - return true; + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); } - if (o.length !== undefined) { - return o.length !== 0; + if (typeof prop !== 'string') { + return obj; } - for (var key in o) { - if (o.hasOwnProperty(key)) { - return true; + 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 false; + + return obj; }; +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +} + /***/ }), -/***/ 94007: -/***/ (function(__unused_webpack_module, exports) { +/***/ 12579: +/***/ (function(module, exports, __webpack_require__) { -/** @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'; +"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]; +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; + } } -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"); - } - }; -}(); - - - - - +/** + * 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 + */ -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; +Node.prototype.push = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); - return arr2; - } else { - return Array.from(arr); - } + this.nodes = this.nodes || []; + return this.nodes.push(node); }; -/** 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' +/** + * 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 + */ -/** Regular expressions */ -var regexPunycode = /^xn--/; -var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars -var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators +Node.prototype.unshift = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); -/** 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' + this.nodes = this.nodes || []; + return this.nodes.unshift(node); }; -/** 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. + * 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 */ -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; -} +Node.prototype.pop = function() { + return this.nodes && this.nodes.pop(); +}; /** - * 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. + * 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 */ -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; -} +Node.prototype.shift = function() { + return this.nodes && this.nodes.shift(); +}; /** - * 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). + * Remove `node` from `node.nodes`. + * + * ```js + * node.remove(childNode); + * ``` + * @param {Object} `node` + * @return {Object} Returns the removed node. + * @api public */ -var ucs2encode = function ucs2encode(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); + +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; }; /** - * 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. + * 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 */ -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; + +Node.prototype.find = function(type) { + return utils.findNode(this.nodes, type); }; /** - * 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. + * 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 */ -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); + +Node.prototype.isType = function(type) { + return utils.isType(this, type); }; /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private + * 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 */ -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)); -}; + +Node.prototype.hasType = function(type) { + return utils.hasType(this, type); +}; /** - * 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. + * 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 */ -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; - } +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; + } +}); - 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)); - } +/** + * 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 + */ - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. +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; + } +}); - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ +/** + * 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 + */ - // `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) { +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; + } +}); - if (index >= inputLength) { - error$1('invalid-input'); - } +/** + * 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 + */ - var digit = basicToDigit(input.charCodeAt(index++)); +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; + } +}); - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1('overflow'); - } +/** + * 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 + */ - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; +Object.defineProperty(Node.prototype, 'first', { + get: function() { + return this.nodes ? this.nodes[0] : null; + } +}); - if (digit < t) { - break; - } +/** + * 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 + */ - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1('overflow'); - } +Object.defineProperty(Node.prototype, 'last', { + get: function() { + return this.nodes ? utils.last(this.nodes) : null; + } +}); - w *= baseMinusT; - } +/** + * 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 + */ - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); +Object.defineProperty(Node.prototype, 'scope', { + get: function() { + if (this.isScope !== true) { + return this.parent ? this.parent.scope : this; + } + return this; + } +}); - // `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'); - } +/** + * Get own property names from Node prototype, but only the + * first time `Node` is instantiated + */ - n += floor(i / out); - i %= out; +function lazyKeys() { + if (!ownNames) { + ownNames = Object.getOwnPropertyNames(Node.prototype); + } +} - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ - return String.fromCodePoint.apply(String, output); -}; +function assert(val, message) { + if (!val) throw new Error(message); +} /** - * 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. + * Expose `Node` */ -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; +exports = module.exports = Node; - // 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; +/***/ 88599: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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; - } - } - } +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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); - } +var isDescriptor = __webpack_require__(44133); - // Main encoding loop: - while (handledCPCount < inputLength) { +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } - // 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; + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; - // 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; +/***/ 82071: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; +"use strict"; - 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); - } +var typeOf = __webpack_require__(48865); +var utils = module.exports; - 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; - } - } - } +/** + * 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 + */ - ++delta; - ++n; - } - return output.join(''); +utils.isNode = function(node) { + return typeOf(node) === 'object' && node.isNode === true; }; /** - * 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. + * 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 */ -var toUnicode = function toUnicode(input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); + +utils.noop = function(node) { + append(this, '', node); }; /** - * 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. + * 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 */ -var toASCII = function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; -/*--------------------------------------------------------------------------*/ +utils.identity = function(node) { + append(this, node.val, node); +}; -/** 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 +/** + * 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); + }; }; /** - * URI.js + * 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. * - * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. - * @author Gary Court - * @see http://github.com/garycourt/uri-js + * ```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 = ''; + } +}; + /** - * Copyright 2011 Gary Court. All rights reserved. + * 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. * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: + * ```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. * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. + * ```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`. * - * 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. + * ```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: '' }; * - * 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. + * // push the parent "brace" node onto the stack + * this.push(parent); * - * 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. + * // 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 */ -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]; +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 (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } -} -function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; + if (typeof val === 'function') { + filter = val; + val = ''; + } - var _matches2 = slicedToArray(matches, 3), - address = _matches2[1], - zone = _matches2[2]; + 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; +}; - 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]; +/** + * 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 + */ - 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] : {}; +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'); - 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; -} + if (typeof val === 'function') { + filter = val; + val = ''; + } -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; -} + 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; +}; -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(""); -} +/** + * 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 + */ -function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +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'); - 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 + utils.addOpen(node, Node, filter); + utils.addClose(node, Node, filter); + return node; +}; - //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); -} +/** + * 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 + */ -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; -} +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'); -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; -} + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.push(node); + return node; +}; -function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); -} +/** + * 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 + */ -function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); -} +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'); -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; - } + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.unshift(node); }; -var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize -}; +/** + * 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 + */ -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; - } +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(); }; -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; - } -}; +/** + * 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 + */ -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; - } +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(); }; -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: -/***/ (function(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: -/***/ (function(module) { - -"use strict"; -/*! - * use +/** + * Remove the specified `node` from `parent.nodes`. * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. + * ```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; + } -module.exports = function base(app, options) { - if (!isObject(app) && typeof app !== 'function') { - throw new TypeError('expected an object or function'); + if (typeof parent.remove === 'function') { + return parent.remove(node); } - var opts = isObject(options) ? options : {}; - var prop = typeof opts.prop === 'string' ? opts.prop : 'fns'; - if (!Array.isArray(app[prop])) { - define(app, prop, []); + var idx = parent.nodes.indexOf(node); + if (idx !== -1) { + return parent.nodes.splice(idx, 1); } +}; - /** - * 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; +/** + * 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 + */ - if (!val.use || !val.run) { - define(val, prop, val[prop] || []); - define(val, 'use', use); +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'); } + } +}; - if (!val[prop] || val[prop].indexOf(base) === -1) { - val.use(base); +/** + * 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; +}; - var self = this || app; - var fns = self[prop]; - var len = fns.length; - var idx = -1; +/** + * 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 + */ - while (++idx < len) { - val.use(fns[idx]); +utils.firstOfType = function(nodes, type) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (utils.isType(node, type)) { + return node; } - return val; - }); + } +}; - /** - * Call plugin `fn`. If a function is returned push it into the - * `fns` array to be called by the `run` method. - */ +/** + * 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 + */ - function use(type, fn, options) { - var offset = 1; +utils.findNode = function(nodes, type) { + if (!Array.isArray(nodes)) { + return null; + } + if (typeof type === 'number') { + return nodes[type]; + } + return utils.firstOfType(nodes, type); +}; - if (typeof type === 'string' || Array.isArray(type)) { - fn = wrap(type, fn); - offset++; - } else { - options = fn; - fn = 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 + */ - if (typeof fn !== 'function') { - throw new TypeError('expected a function'); - } +utils.isOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-5) === '.open'; +}; - var self = this || app; - var fns = self[prop]; +/** + * 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 + */ - var args = [].slice.call(arguments, offset); - args.unshift(self); +utils.isClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-6) === '.close'; +}; - if (typeof opts.hook === 'function') { - opts.hook.apply(self, args); - } +/** + * 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 + */ - var val = fn.apply(self, args); - if (typeof val === 'function' && fns.indexOf(val) === -1) { - fns.push(val); - } - return self; +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; +}; - /** - * 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} - */ +/** + * 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 + */ - function wrap(type, fn) { - return function plugin() { - return this.type === type ? fn.apply(this, arguments) : plugin; - }; +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 app; + return false; }; -function isObject(val) { - return val && typeof val === 'object' && !Array.isArray(val); -} +/** + * 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 + */ -function define(obj, key, val) { - Object.defineProperty(obj, key, { - configurable: true, - writable: true, - value: val - }); -} +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$/, ''); -/***/ 92262: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!state.hasOwnProperty('inside')) { + state.inside = {}; + } + if (!state.inside.hasOwnProperty(type)) { + state.inside[type] = []; + } + var arr = state.inside[type]; + arr.push(node); + return arr; +}; /** - * For Node.js, simply re-export the core `util.deprecate` function. + * 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 */ -module.exports = __webpack_require__(31669).deprecate; - +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$/, ''); -/***/ 24059: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (state.inside.hasOwnProperty(type)) { + return state.inside[type].pop(); + } +}; -module.exports = __webpack_require__(47257); +/** + * 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); + } -/***/ 71118: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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; + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 + */ -const ConstDependency = __webpack_require__(71101); -const ParserHelpers = __webpack_require__(23999); +utils.isInsideType = function(state, type) { + assert(isObject(state), 'expected state to be an object'); + assert(isString(type), 'expected type to be a string'); -const NullFactory = __webpack_require__(40438); + if (!state.hasOwnProperty('inside')) { + return false; + } -/* 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" + if (!state.inside.hasOwnProperty(type)) { + return false; + } + + return state.inside[type].length > 0; }; -const NO_WEBPACK_REQUIRE = { - __non_webpack_require__: true + +/** + * 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; }; -const REPLACEMENT_TYPES = { - __webpack_public_path__: "string", - __webpack_require__: "function", - __webpack_modules__: "object", - __webpack_chunk_load__: "function", - __webpack_nonce__: "string" + +/** + * 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)]; }; -/* 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() - ); +/** + * 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 + */ - 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)); - } - }); - }; +utils.arrayify = function(val) { + if (typeof val === 'string' && val !== '') { + return [val]; + } + if (!Array.isArray(val)) { + return []; + } + return val; +}; - 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); - } - ); - } -} +/** + * 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 + */ -module.exports = APIPlugin; +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() : ''; +}; -/***/ 36104: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Return true if val is an object + */ -"use strict"; +function isObject(val) { + return typeOf(val) === 'object'; +} +/** + * Return true if val is a string + */ -const WebpackError = __webpack_require__(97391); -const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; +function isString(val) { + return typeof val === 'string'; +} /** - * @param {string=} method method name - * @returns {string} message + * Return true if val is a function */ -function createMessage(method) { - return `Abstract method${method ? " " + method : ""}. Must be overridden.`; + +function isFunction(val) { + return typeof val === 'function'; } /** - * @constructor + * Return true if val is an array */ -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(); +function isArray(val) { + return Array.isArray(val); } /** - * Error for abstract method - * @example - * class FooClass { - * abstractMethod() { - * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overriden. - * } - * } - * + * Shim to ensure the `.append` methods work with any version of snapdragon */ -class AbstractMethodError extends WebpackError { - constructor() { - super(new Message().message); - this.name = "AbstractMethodError"; - } + +function append(compiler, val, node) { + if (typeof compiler.append !== 'function') { + return compiler.emit(val, node); + } + return compiler.append(val, node); } -module.exports = AbstractMethodError; +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ + +function assert(val, message) { + if (!val) throw new Error(message); +} /***/ }), -/***/ 9701: +/***/ 79285: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + + +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; + } + }); -const { ConcatSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); + Object.defineProperty(this, 'parsers', { + get: function() { + return this.parser.parsers; + } + }); -/** @typedef {import("./Compilation")} Compilation */ + Object.defineProperty(this, 'regex', { + get: function() { + return this.parser.regex; + } + }); +} /** - * @typedef {Object} AmdMainTemplatePluginOptions - * @param {string=} name the library name - * @property {boolean=} requireAsWrapper + * Inherit Base */ -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; - } - } +Base.extend(Snapdragon); - /** - * @param {Compilation} compilation the compilation instance - * @returns {void} - */ - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; +/** + * 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 + */ - 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(", "); +Snapdragon.prototype.capture = function() { + return this.parser.capture.apply(this.parser, arguments); +}; - if (this.requireAsWrapper) { - return new ConcatSource( - `require(${externalsDepsArray}, function(${externalsArguments}) { return `, - source, - "});" - ); - } else if (this.name) { - const name = mainTemplate.getAssetPath(this.name, { - hash, - chunk - }); +/** + * 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 + */ - 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, "});"); - } - }; +Snapdragon.prototype.use = function(fn) { + fn.call(this, this); + return this; +}; - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "AmdMainTemplatePlugin", - onRenderWithEntry - ); - } +/** + * 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 + */ - mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { - if (this.name) { - paths.push(this.name); - } - return paths; - }); +Snapdragon.prototype.parse = function(str, options) { + this.options = utils.extend({}, this.options, options); + var parsed = this.parser.parse(str, this.options); - mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { - hash.update("exports amd"); - if (this.name) { - hash.update(this.name); - } - }); - } -} + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; +}; -module.exports = AmdMainTemplatePlugin; +/** + * 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; /***/ }), -/***/ 22814: +/***/ 33003: /***/ (function(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); +var use = __webpack_require__(77709); +var define = __webpack_require__(5477); +var debug = __webpack_require__(31185)('snapdragon:compiler'); +var utils = __webpack_require__(622); -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./util/createHash").Hash} Hash */ -/** @typedef {TODO} GroupOptions */ +/** + * Create a new `Compiler` with the given `options`. + * @param {Object} `options` + */ -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; - } +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); +} - /** - * @returns {string} The name of the chunk - */ - get chunkName() { - return this.groupOptions.name; - } +/** + * Prototype methods + */ - /** - * @param {string} value The new chunk name - * @returns {void} - */ - set chunkName(value) { - this.groupOptions.name = value; - } +Compiler.prototype = { - /** - * @returns {never} this throws and should never be called - */ - get chunks() { - throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); - } + /** + * Throw an error message with details including the cursor position. + * @param {String} `msg` Message to use in the Error. + */ - /** - * @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"); - } + error: function(msg, node) { + var pos = node.position || {start: {column: 0}}; + var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; - /** - * @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); - } + var err = new Error(message); + err.reason = msg; + err.column = pos.start.column; + err.source = this.pattern; - /** - * @returns {void} - */ - disconnect() { - this.chunkGroup = undefined; - super.disconnect(); - } + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, - /** - * @returns {void} - */ - unseal() { - this.chunkGroup = undefined; - super.unseal(); - } + /** + * 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 + */ - /** - * @returns {void} - */ - sortItems() { - super.sortItems(); - } -}; + define: function(key, val) { + define(this, key, val); + return this; + }, + /** + * Emit `node.val` + */ -/***/ }), + emit: function(str, node) { + this.output += str; + return str; + }, -/***/ 67089: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Add a compiler `fn` with the given `name` + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + set: function(name, fn) { + this.compilers[name] = fn; + return this; + }, + /** + * Get compiler `name`. + */ -const WebpackError = __webpack_require__(97391); + get: function(name) { + return this.compilers[name]; + }, -/** @typedef {import("./Module")} Module */ + /** + * Get the previous AST node. + */ -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.` - ); + prev: function(n) { + return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; + }, - this.name = "AsyncDependencyToInitialChunkError"; - this.module = module; - this.loc = loc; + /** + * Get the next AST node. + */ - Error.captureStackTrace(this, this.constructor); - } -} + next: function(n) { + return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; + }, -module.exports = AsyncDependencyToInitialChunkError; + /** + * 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); + }, -/***/ 51596: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Map visit over array of `nodes`. + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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`. + */ -const asyncLib = __webpack_require__(36386); -const PrefetchDependency = __webpack_require__(14237); -const NormalModule = __webpack_require__(25963); + compile: function(ast, options) { + var opts = utils.extend({}, this.options, options); + this.ast = ast; + this.parsingErrors = this.ast.errors; + this.output = ''; -/** @typedef {import("./Compiler")} Compiler */ + // 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; + } -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; + this.mapVisit(this.ast.nodes); + return this; + } +}; + +/** + * Expose `Compiler` + */ + +module.exports = Compiler; /***/ }), -/***/ 4009: +/***/ 35573: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - -const { ConcatSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); -const Template = __webpack_require__(96066); +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); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(10171); +/** + * Create a new `Parser` with the given `input` and `options`. + * @param {String} `input` + * @param {Object} `options` + * @api public + */ -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ +function Parser(options) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.init(this.options); + use(this); +} -const wrapComment = str => { - if (!str.includes("\n")) { - return Template.toComment(str); - } - return `/*!\n * ${str - .replace(/\*\//g, "* /") - .split("\n") - .join("\n * ")}\n */`; -}; +/** + * Prototype methods + */ -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)" - ); - } +Parser.prototype = { + constructor: Parser, - validateOptions(schema, options, "Banner Plugin"); + init: function(options) { + this.orig = ''; + this.input = ''; + this.parsed = ''; - if (typeof options === "string" || typeof options === "function") { - options = { - banner: options - }; - } + this.column = 1; + this.line = 1; - /** @type {BannerPluginOptions} */ - this.options = options; + 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'; - 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; - } - } + var pos = this.position(); + this.bos = pos({type: 'bos', val: ''}); - apply(compiler) { - const options = this.options; - const banner = this.banner; - const matchObject = ModuleFilenameHelpers.matchObject.bind( - undefined, - options - ); + this.ast = { + type: 'root', + errors: this.errors, + nodes: [this.bos] + }; - compiler.hooks.compilation.tap("BannerPlugin", compilation => { - compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { - for (const chunk of chunks) { - if (options.entryOnly && !chunk.canBeInitial()) { - continue; - } + define(this.bos, 'parent', this.ast); + this.nodes = [this.ast]; - for (const file of chunk.files) { - if (!matchObject(file)) { - continue; - } + this.count = 0; + this.setCount = 0; + this.stack = []; + }, - let query = ""; - let filename = file; - const hash = compilation.hash; - const querySplit = filename.indexOf("?"); + /** + * Throw a formatted error with the cursor column and `msg`. + * @param {String} `msg` Message to use in the Error. + */ - if (querySplit >= 0) { - query = filename.substr(querySplit); - filename = filename.substr(0, querySplit); - } + 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; - const lastSlashIndex = filename.lastIndexOf("/"); + var message = source + ' : ' + msg; + var err = new Error(message); + err.source = source; + err.reason = msg; + err.pos = pos; - const basename = - lastSlashIndex === -1 - ? filename - : filename.substr(lastSlashIndex + 1); + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, - const data = { - hash, - chunk, - filename, - basename, - query - }; + /** + * 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 + */ - const comment = compilation.getPath(banner(data), data); + define: function(key, val) { + define(this, key, val); + return this; + }, - compilation.updateAsset( - file, - old => new ConcatSource(comment, "\n", old) - ); - } - } - }); - }); - } -} + /** + * Mark position and patch `node.position`. + */ -module.exports = BannerPlugin; + 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 + */ -/***/ 96770: -/***/ (function(module) { + set: function(type, fn) { + if (this.types.indexOf(type) === -1) { + this.types.push(type); + } + this.parsers[type] = fn.bind(this); + return this; + }, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * 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 + */ -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; + push: function(type, token) { + this.sets[type] = this.sets[type] || []; + this.count++; + this.stack.push(token); + return this.sets[type].push(token); + }, -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; - } + /** + * Pop a token off of the `type` stack + * @param {String} `type` + * @returns {Object} Returns a token + * @api public + */ - isNull() { - return this.type === TypeNull; - } + pop: function(type) { + this.sets[type] = this.sets[type] || []; + this.count--; + this.stack.pop(); + return this.sets[type].pop(); + }, - isString() { - return this.type === TypeString; - } + /** + * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. + * + * @param {String} `type` + * @return {Boolean} + * @api public + */ - isNumber() { - return this.type === TypeNumber; - } + isInside: function(type) { + this.sets[type] = this.sets[type] || []; + return this.sets[type].length > 0; + }, - isBoolean() { - return this.type === TypeBoolean; - } + /** + * Return true if `node` is the given `type`. + * + * ```js + * parser.isType(node, 'brace'); + * ``` + * @param {Object} `node` + * @param {String} `type` + * @return {Boolean} + * @api public + */ - isRegExp() { - return this.type === TypeRegExp; - } + isType: function(node, type) { + return node && node.type === type; + }, - isConditional() { - return this.type === TypeConditional; - } + /** + * Get the previous AST node + * @return {Object} + */ - isArray() { - return this.type === TypeArray; - } + prev: function(n) { + return this.stack.length > 0 + ? utils.last(this.stack, n) + : utils.last(this.nodes, n); + }, - isConstArray() { - return this.type === TypeConstArray; - } + /** + * Update line and column based on `str`. + */ - isIdentifier() { - return this.type === TypeIdentifier; - } + consume: function(len) { + this.input = this.input.substr(len); + }, - isWrapped() { - return this.type === TypeWrapped; - } + /** + * Update column based on `str`. + */ - isTemplateString() { - return this.type === TypeTemplateString; - } + 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); + }, - isTruthy() { - return this.truthy; - } + /** + * Match `regex`, return captures, and update the cursor position by `match[0]` length. + * @param {RegExp} `regex` + * @return {Object} + */ - isFalsy() { - return this.falsy; - } + match: function(regex) { + var m = regex.exec(this.input); + if (m) { + this.updatePosition(m[0], m[0].length); + return m; + } + }, - 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; - } + /** + * Capture `type` with the given regex. + * @param {String} `type` + * @param {RegExp} `regex` + * @return {Function} + */ - 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; - } + capture: function(type, regex) { + if (typeof regex === 'function') { + return this.set.apply(this, arguments); + } - setString(string) { - this.type = TypeString; - this.string = string; - return this; - } + 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; - setNull() { - this.type = TypeNull; - return this; - } + var prev = this.prev(); + var node = pos({ + type: type, + val: m[0], + parsed: parsed, + rest: this.input + }); - setNumber(number) { - this.type = TypeNumber; - this.number = number; - return this; - } + if (m[1]) { + node.inner = m[1]; + } - setBoolean(bool) { - this.type = TypeBoolean; - this.bool = bool; - return this; - } + define(node, 'inside', this.stack.length > 0); + define(node, 'parent', prev); + prev.nodes.push(node); + }.bind(this)); + return this; + }, - setRegExp(regExp) { - this.type = TypeRegExp; - this.regExp = regExp; - return this; - } + /** + * Create a parser with open and close for parens, + * brackets or braces + */ - setIdentifier(identifier) { - this.type = TypeIdentifier; - this.identifier = identifier; - return this; - } + capturePair: function(type, openRegex, closeRegex, fn) { + this.sets[type] = this.sets[type] || []; - setWrapped(prefix, postfix, innerExpressions) { - this.type = TypeWrapped; - this.prefix = prefix; - this.postfix = postfix; - this.wrappedInnerExpressions = innerExpressions; - return this; - } + /** + * Open + */ - setOptions(options) { - this.type = TypeConditional; - this.options = options; - return this; - } + this.set(type + '.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(openRegex); + if (!m || !m[0]) return; - addOptions(options) { - if (!this.options) { - this.type = TypeConditional; - this.options = []; - } - for (const item of options) { - this.options.push(item); - } - return this; - } + var val = m[0]; + this.setCount++; + this.specialChars = true; + var open = pos({ + type: type + '.open', + val: val, + rest: this.input + }); - setItems(items) { - this.type = TypeArray; - this.items = items; - return this; - } + if (typeof m[1] !== 'undefined') { + open.inner = m[1]; + } - setArray(array) { - this.type = TypeConstArray; - this.array = array; - return this; - } + var prev = this.prev(); + var node = pos({ + type: type, + nodes: [open] + }); - setTemplateString(quasis, parts, kind) { - this.type = TypeTemplateString; - this.quasis = quasis; - this.parts = parts; - this.templateStringKind = kind; - return this; - } + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'prefix', m[1]); + define(node, 'parent', prev); + define(open, 'parent', node); - setTruthy() { - this.falsy = false; - this.truthy = true; - return this; - } + if (typeof fn === 'function') { + fn.call(this, open, node); + } - setFalsy() { - this.falsy = true; - this.truthy = false; - return this; - } + this.push(type, node); + prev.nodes.push(node); + }); - setRange(range) { - this.range = range; - return this; - } + /** + * Close + */ - setExpression(expression) { - this.expression = expression; - return this; - } -} + this.set(type + '.close', function() { + var pos = this.position(); + var m = this.match(closeRegex); + if (!m || !m[0]) return; -module.exports = BasicEvaluatedExpression; + 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; + } -/***/ 6465: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (node.suffix === '\\') { + parent.escaped = true; + node.escaped = true; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + parent.nodes.push(node); + define(node, 'parent', parent); + }); + return this; + }, -const asyncLib = __webpack_require__(36386); + /** + * Capture end-of-string + */ -class CachePlugin { - constructor(cache) { - this.cache = cache || {}; - this.FS_ACCURACY = 2000; - } + eos: function() { + var pos = this.position(); + if (this.input) return; + var prev = this.prev(); - 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); - } + while (prev.type !== 'root' && !prev.visited) { + if (this.options.strict === true) { + throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); + } - if (stat.mtime) this.applyMtime(+stat.mtime); + if (!hasDelims(prev)) { + prev.parent.escaped = true; + prev.escaped = true; + } - fileTs.set(file, +stat.mtime || Infinity); + visit(prev, function(node) { + if (!hasDelims(node.parent)) { + node.parent.escaped = true; + node.escaped = true; + } + }); - callback(); - }); - }, - err => { - if (err) return callback(err); + prev = prev.parent; + } - for (const [file, ts] of fileTs) { - fileTs.set(file, ts + this.FS_ACCURACY); - } + var tok = pos({ + type: 'eos', + val: this.append || '' + }); - callback(); - } - ); - }); - compiler.hooks.afterCompile.tap("CachePlugin", compilation => { - compilation.compiler._lastCompilationFileDependencies = - compilation.fileDependencies; - compilation.compiler._lastCompilationContextDependencies = - compilation.contextDependencies; - }); - } - } + define(tok, 'parent', this.ast); + return tok; + }, - /* 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; + /** + * 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; + } + } + }, -/***/ 8335: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Parse the given string. + * @return {Array} + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; -const WebpackError = __webpack_require__(97391); + function parse() { + // check input before calling `.next()` + input = self.input; -/** @typedef {import("./Module")} Module */ + // 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; + } +}; /** - * @param {Module[]} modules the modules to be sorted - * @returns {Module[]} sorted version of original modules + * Visit `node` with the given `fn` */ -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; - }); -}; + +function visit(node, fn) { + if (!node.visited) { + define(node, 'visited', true); + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + return node; +} /** - * @param {Module[]} modules each module from throw - * @returns {string} each message from provided moduels + * Map visit over array of `nodes`. */ -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"); -}; +function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } +} -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}`); +function hasOpen(node) { + return node.nodes && node.nodes[0].type === (node.type + '.open'); +} - this.name = "CaseSensitiveModulesWarning"; - this.origin = this.module = sortedModules[0]; +function hasClose(node) { + return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); +} - Error.captureStackTrace(this, this.constructor); - } +function hasDelims(node) { + return hasOpen(node) && hasClose(node); } -module.exports = CaseSensitiveModulesWarning; +/** + * Expose `Parser` + */ + +module.exports = Parser; /***/ }), -/***/ 2919: +/***/ 7974: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* -MIT License http://www.opensource.org/licenses/mit-license.php -Author Tobias Koppers @sokra -*/ -const util = __webpack_require__(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()"; +var define = __webpack_require__(5477); -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./ModuleReason")} ModuleReason */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./util/createHash").Hash} Hash */ +/** + * 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: +/***/ (function(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); /** - * @typedef {Object} WithId an object who has an id property * - * @property {string | number} id the id of the object + * 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; + /** - * Compare two Modules based on their ids for sorting - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} sort value + * Mixin source map support into `compiler`. + * + * @param {Object} `compiler` + * @api public */ -// TODO use @callback -/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ -/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ -/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ +function mixin(compiler) { + define(compiler, '_comment', compiler.comment); + compiler.map = new utils.SourceMap.SourceMapGenerator(); + compiler.position = { line: 1, column: 1 }; + compiler.content = {}; + compiler.files = {}; -const sortModuleById = (a, b) => { - if (a.id < b.id) return -1; - if (b.id < a.id) return 1; - return 0; -}; + for (var key in exports) { + define(compiler, key, exports[key]); + } +} /** - * 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 + * Update position. + * + * @param {String} str */ -const sortChunkGroupById = (a, b) => { - if (a.id < b.id) return -1; - if (b.id < a.id) return 1; - return 0; + +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; }; /** - * 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 + * Emit `str` with `position`. + * + * @param {String} str + * @param {Object} [pos] + * @return {String} */ -const sortByIdentifier = (a, b) => { - if (a.identifier() > b.identifier()) return 1; - if (a.identifier() < b.identifier()) return -1; - return 0; + +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; }; /** - * @returns {string} a concatenation of module identifiers sorted - * @param {SortableSet} set to pull module identifiers from + * Adds a file to the source map output if it has not already been added + * @param {String} `file` + * @param {Object} `pos` */ -const getModulesIdent = set => { - set.sort(); - let str = ""; - for (const m of set) { - str += m.identifier() + "#"; - } - return str; + +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; }; /** - * @template T - * @param {SortableSet} set the sortable set to convert to array - * @returns {Array} the array returned from Array.from(set) + * Adds a content source to the source map output if it has not already been added + * @param {String} `source` + * @param {Object} `position` */ -const getArray = set => Array.from(set); + +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); +}; /** - * @param {SortableSet} set the sortable Set to get the count/size of - * @returns {number} the size of the modules + * Applies any original source maps to the output and embeds the source file + * contents in the source map. */ -const getModulesSize = set => { - let size = 0; - for (const module of set) { - size += module.size(); - } - return size; + +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); }; /** - * A Chunk is a unit of encapsulation for Modules. - * Chunks are "rendered" into bundles that get emitted when the build completes. + * Process comments, drops sourceMap comments. + * @param {Object} node */ -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); - } +exports.comment = function(node) { + if (/^# sourceMappingURL=/.test(node.comment)) { + return this.emit('', node.position); + } + return this._comment(node); +}; - /** - * @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); - } +/***/ 622: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - /** - * @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; - } +"use strict"; - /** - * @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; - } +/** + * Module dependencies + */ - /** - * @returns {boolean} if this chunk contains the entry module - */ - hasEntryModule() { - return !!this.entryModule; - } +exports.extend = __webpack_require__(28727); +exports.SourceMap = __webpack_require__(96241); +exports.sourceMapResolve = __webpack_require__(10227); - /** - * @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; - } +/** + * Convert backslash in the given string to forward slashes + */ - /** - * @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; - } +exports.unixify = function(fp) { + return fp.split(/\\+/).join('/'); +}; - /** - * @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); - } +/** + * Return true if `val` is a non-empty string + * + * @param {String} `str` + * @return {Boolean} + */ - /** - * @returns {number} the amount of modules in chunk - */ - getNumberOfModules() { - return this._modules.size; - } +exports.isString = function(str) { + return str && typeof str === 'string'; +}; - /** - * @returns {SortableSet} return the modules SortableSet for this chunk - */ - get modulesIterable() { - return this._modules; - } +/** + * Cast `val` to an array + * @return {Array} + */ - /** - * @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; - } +exports.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; - /** - * @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; - } +/** + * Get the last `n` element from the given `array` + * @param {Array} `array` + * @return {*} + */ - /** - * @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); - } +exports.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; - /** - * @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; - } - } +/***/ 56609: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {Module} module Module to check - * @returns {boolean} returns true if module does exist in this chunk - */ - containsModule(module) { - return this._modules.has(module); - } +var decodeUriComponent = __webpack_require__(95748) - /** - * @returns {Module[]} an array of modules (do not modify) - */ - getModules() { - return this._modules.getFromCache(getArray); - } +function customDecodeUriComponent(string) { + // `decodeUriComponent` turns `+` into ` `, but that's not wanted. + return decodeUriComponent(string.replace(/\+/g, "%2B")) +} - getModulesIdent() { - return this._modules.getFromUnorderedCache(getModulesIdent); - } +module.exports = customDecodeUriComponent - /** - * @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; - } +/***/ 89825: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 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; - } +var url = __webpack_require__(78835) - // 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(); +function resolveUrl(/* ...urls */) { + return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { + return url.resolve(resolved, nextUrl) + }) +} - if (otherChunk.entryModule) { - this.entryModule = otherChunk.entryModule; - } +module.exports = resolveUrl - 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); - } - } +/***/ 10227: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - isEmpty() { - return this._modules.size === 0; - } +var sourceMappingURL = __webpack_require__(21707) - 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); - } - } +var resolveUrl = __webpack_require__(89825) +var decodeUriComponent = __webpack_require__(56609) +var urix = __webpack_require__(67806) +var atob = __webpack_require__(83327) - 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(); +function callbackAsync(callback, error, result) { + setImmediate(function() { callback(error, result) }) +} - if (selfHasRuntime !== otherChunkHasRuntime) { - if (selfHasRuntime) { - return isAvailable(this, otherChunk); - } else if (otherChunkHasRuntime) { - return isAvailable(otherChunk, this); - } else { - return false; - } - } +function parseMapToJSON(string, data) { + try { + return JSON.parse(string.replace(/^\)\]\}'/, "")) + } catch (error) { + error.sourceMapData = data + throw error + } +} - if (this.hasEntryModule() || otherChunk.hasEntryModule()) { - return false; - } +function readSync(read, url, data) { + var readUrl = decodeUriComponent(url) + try { + return String(read(readUrl)) + } catch (error) { + error.sourceMapData = data + throw error + } +} - 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; - } +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) + }) +} - /** - * @returns {number} the size of all modules - */ - modulesSize() { - return this._modules.getFromUnorderedCache(getModulesSize); - } +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 +} - /** - * @param {Object} options the size display options - * @returns {number} the chunk size - */ - size(options = {}) { - return this.addMultiplierAndOverhead(this.modulesSize(), options); - } +var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ - /** - * @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; - } +/** + * 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$/ - 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(); - } - } +/** + * 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" - return this.addMultiplierAndOverhead(integratedModulesSize, options); - } +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 +} - /** - * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules - * @returns {void} - */ - sortModules(sortByFn) { - this._modules.sortWith(sortByFn || sortModuleById); - } +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); +} - sortItems() { - this.sortModules(); - } +function resolveSourceMapHelper(code, codeUrl) { + codeUrl = urix(codeUrl) - /** - * @returns {Set} a set of all the async chunks - */ - getAllAsyncChunks() { - const queue = new Set(); - const chunks = new Set(); + var url = sourceMappingURL.getFrom(code) + if (!url) { + return null + } - const initialChunks = intersect( - Array.from(this.groupsIterable, g => new Set(g.chunks)) - ); + 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 + } - for (const chunkGroup of this.groupsIterable) { - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } + var mapUrl = resolveUrl(codeUrl, url) + return { + sourceMappingURL: url, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } +} - 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 - */ +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: [] + } - /** - * @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); + if (pending === 0) { + callbackAsync(callback, null, result) + return + } - 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; - } - } + var done = function() { + pending-- + if (pending === 0) { + callback(null, result) + } + } - return { - hash: chunkHashMap, - contentHash: chunkContentHashMap, - name: chunkNameMap - }; - } + 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() + }) + } + }) +} - /** - * @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; - } +function resolveSourcesSync(map, mapUrl, read, options) { + var result = { + sourcesResolved: [], + sourcesContent: [] + } - getChildIdsByOrdersMap(includeDirectChildren) { - const chunkMaps = Object.create(null); + if (!map.sources || map.sources.length === 0) { + return result + } - 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]; - } - }; + 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 + } + } + } + }) - 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); - } - } + return result +} - for (const chunk of this.getAllAsyncChunks()) { - addChildIdsByOrdersToMap(chunk); - } +var endingSlash = /\/?$/ - return chunkMaps; - } +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) + } +} - /** - * @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(); - } - } +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) + }) + } - return { - id: chunkModuleIdMap, - hash: chunkModuleHashMap - }; - } + 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) + }) + } +} - /** - * - * @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(); +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 +} - 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()}]`; - } + +module.exports = { + resolveSourceMap: resolveSourceMap, + resolveSourceMapSync: resolveSourceMapSync, + resolveSources: resolveSources, + resolveSourcesSync: resolveSourcesSync, + resolve: resolve, + resolveSync: resolveSync, + parseMapToJSON: parseMapToJSON } -// 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"); - } -}); +/***/ 21707: +/***/ (function(module) { -// 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"); - } -}); +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) -// 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"); - } -}); +void (function(root, factory) { + if (typeof define === "function" && define.amd) { + define(factory) + } else if (true) { + module.exports = factory() + } else {} +}(this, function() { -// 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"); - } -}); + var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ -module.exports = Chunk; + var regex = RegExp( + "(?:" + + "/\\*" + + "(?:\\s*\r?\n(?://)?)?" + + "(?:" + innerRegex.source + ")" + + "\\s*" + + "\\*/" + + "|" + + "//(?:" + innerRegex.source + ")" + + ")" + + "\\s*" + ) + return { -/***/ }), + regex: regex, + _innerRegex: innerRegex, -/***/ 52911: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + getFrom: function(code) { + var match = code.match(regex) + return (match ? match[1] || match[2] || "" : null) + }, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + existsIn: function(code) { + return regex.test(code) + }, + removeFrom: function(code) { + return code.replace(regex, "") + }, -const SortableSet = __webpack_require__(50071); -const compareLocations = __webpack_require__(22562); + 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 + } + } + } -/** @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); +/***/ 33218: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * 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 +"use strict"; +/*! + * split-string + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -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}` - ); - } - } - } - } +var extend = __webpack_require__(66889); - /** - * returns the name of current ChunkGroup - * @returns {string|undefined} returns the ChunkGroup name - */ - get name() { - return this.options.name; - } +module.exports = function(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - /** - * sets a new name for current ChunkGroup - * @param {string} value the new name for ChunkGroup - * @returns {void} - */ - set name(value) { - this.options.name = value; - } + if (typeof options === 'function') { + fn = options; + options = null; + } - /** - * 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("+"); - } + // allow separator to be defined as a string + if (typeof options === 'string') { + options = { sep: options }; + } - /** - * 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("+"); - } + var opts = extend({sep: '.'}, options); + var quotes = opts.quotes || ['"', "'", '`']; + var brackets; - /** - * Performs an unshift of a specific chunk - * @param {Chunk} chunk chunk being unshifted - * @returns {boolean} returns true if attempted chunk shift is accepted - */ - unshiftChunk(chunk) { - const oldIdx = this.chunks.indexOf(chunk); - if (oldIdx > 0) { - this.chunks.splice(oldIdx, 1); - this.chunks.unshift(chunk); - } else if (oldIdx < 0) { - this.chunks.unshift(chunk); - return true; - } - return false; - } + if (opts.brackets === true) { + brackets = { + '<': '>', + '(': ')', + '[': ']', + '{': '}' + }; + } else if (opts.brackets) { + brackets = opts.brackets; + } - /** - * 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; - } + var tokens = []; + var stack = []; + var arr = ['']; + var sep = opts.sep; + var len = str.length; + var idx = -1; + var closeIdx; - /** - * 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; - } + function expected() { + if (brackets && stack.length) { + return brackets[stack[stack.length - 1]]; + } + } - /** - * @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; - } - } + 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); - removeChunk(chunk) { - const idx = this.chunks.indexOf(chunk); - if (idx >= 0) { - this.chunks.splice(idx, 1); - return true; - } - return false; - } + 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; + } - isInitial() { - return false; - } + if (brackets && brackets[ch]) { + stack.push(ch); + var e = expected(); + var i = idx + 1; - addChild(chunk) { - if (this._children.has(chunk)) { - return false; - } - this._children.add(chunk); - return true; - } + if (str.indexOf(e, i + 1) !== -1) { + while (stack.length && i < len) { + var s = str[++i]; + if (s === '\\') { + s++; + continue; + } - getChildren() { - return this._children.getFromCache(getArray); - } + if (quotes.indexOf(s) !== -1) { + i = getClosingQuote(str, s, i + 1); + continue; + } - getNumberOfChildren() { - return this._children.size; - } + e = expected(); + if (stack.length && str.indexOf(e, i + 1) === -1) { + break; + } - get childrenIterable() { - return this._children; - } + if (brackets[s]) { + stack.push(s); + continue; + } - removeChild(chunk) { - if (!this._children.has(chunk)) { - return false; - } + if (e === s) { + stack.pop(); + } + } + } - this._children.delete(chunk); - chunk.removeParent(this); - return true; - } + closeIdx = i; + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } - addParent(parentChunk) { - if (!this._parents.has(parentChunk)) { - this._parents.add(parentChunk); - return true; - } - return false; - } + ch = str.slice(idx, closeIdx + 1); + tok.val = ch; + tok.idx = idx = closeIdx; + } - getParents() { - return this._parents.getFromCache(getArray); - } + if (quotes.indexOf(ch) !== -1) { + closeIdx = getClosingQuote(str, ch, idx + 1); + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } - setParents(newParents) { - this._parents.clear(); - for (const p of newParents) { - this._parents.add(p); - } - } + if (keepQuotes(ch, opts) === true) { + ch = str.slice(idx, closeIdx + 1); + } else { + ch = str.slice(idx + 1, closeIdx); + } - getNumberOfParents() { - return this._parents.size; - } + tok.val = ch; + tok.idx = idx = closeIdx; + } - hasParent(parent) { - return this._parents.has(parent); - } + if (typeof fn === 'function') { + fn(tok, tokens); + ch = tok.val; + idx = tok.idx; + } - get parentsIterable() { - return this._parents; - } + if (tok.val === sep && tok.split !== false) { + arr.push(''); + continue; + } - removeParent(chunk) { - if (this._parents.delete(chunk)) { - chunk.removeChunk(this); - return true; - } - return false; - } + arr[arr.length - 1] += tok.val; + } - /** - * @returns {Array} - an array containing the blocks - */ - getBlocks() { - return this._blocks.getFromCache(getArray); - } + return arr; +}; - getNumberOfBlocks() { - return this._blocks.size; - } +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; +} - hasBlock(block) { - return this._blocks.has(block); - } +function keepQuotes(ch, opts) { + if (opts.keepDoubleQuotes === true && ch === '"') return true; + if (opts.keepSingleQuotes === true && ch === "'") return true; + return opts.keepQuotes; +} - get blocksIterable() { - return this._blocks; - } +function keepEscaping(opts, str, idx) { + if (typeof opts.keepEscaping === 'function') { + return opts.keepEscaping(str, idx); + } + return opts.keepEscaping === true || str[idx + 1] === '\\'; +} - 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; - } +/***/ 66889: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getFiles() { - const files = new Set(); +"use strict"; - for (const chunk of this.chunks) { - for (const file of chunk.files) { - files.add(file); - } - } - return Array.from(files); - } +var isExtendable = __webpack_require__(28730); +var assignSymbols = __webpack_require__(64353); - /** - * @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); +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; +}; - // 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); - } - } +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} - /** - * 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); - } +function isString(val) { + return (val && typeof val === 'string'); +} - // cleanup blocks - for (const block of this._blocks) { - block.chunkGroup = null; - } +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} - // remove chunks - for (const chunk of this.chunks) { - chunk.removeGroup(this); - } - } +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} - sortItems() { - this.origins.sort(sortOrigin); - this._parents.sort(); - this._children.sort(); - } +/** + * Returns true if the given `key` is an own property of `obj`. + */ - /** - * 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; - } - } +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - 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; - } +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} - /** - * 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); - } +/***/ 28730: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * 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); - } +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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; + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; /***/ }), -/***/ 69865: +/***/ 69457: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/*! + * static-extend + * + * Copyright (c) 2016, Jon Schlinkert. + * Licensed under the MIT License. + */ -const WebpackError = __webpack_require__(97391); -/** @typedef {import("./Chunk")} Chunk */ +var copy = __webpack_require__(31368); +var define = __webpack_require__(5477); +var util = __webpack_require__(31669); -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(); +/** + * 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 + */ - this.name = "ChunkRenderError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.file = file; - this.chunk = chunk; +function extend(Parent, extendFn) { + if (typeof Parent !== 'function') { + throw new TypeError('expected Parent to be a function.'); + } - Error.captureStackTrace(this, this.constructor); - } -} + return function(Ctor, proto) { + if (typeof Ctor !== 'function') { + throw new TypeError('expected Ctor to be a function.'); + } -module.exports = ChunkRenderError; + 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; /***/ }), -/***/ 6170: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 16326: +/***/ (function(__unused_webpack_module, 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__(56758); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Module")} Module} */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ -/** @typedef {import("./util/createHash").Hash} Hash} */ +var _os = _interopRequireDefault(__webpack_require__(12087)); -/** - * @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 - */ +var _cacache = _interopRequireDefault(__webpack_require__(36801)); -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"]) - }; - } +var _findCacheDir = _interopRequireDefault(__webpack_require__(61844)); - /** - * - * @param {RenderManifestOptions} options render manifest options - * @returns {TODO[]} returns render manifest - */ - getRenderManifest(options) { - const result = []; +var _workerFarm = _interopRequireDefault(__webpack_require__(18921)); - this.hooks.renderManifest.call(result, options); +var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); - return result; - } +var _isWsl = _interopRequireDefault(__webpack_require__(47543)); - /** - * 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); - } +var _minify = _interopRequireDefault(__webpack_require__(30787)); - /** - * 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); - } -}; +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 -/***/ 51760: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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 -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + } -const WebpackError = __webpack_require__(97391); + 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"); -/** @typedef {import("./Module")} Module */ + 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); + } + }; + } -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + let toRun = tasks.length; + const results = []; -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); + const step = (index, data) => { + toRun -= 1; + results[index] = data; - this.name = "CommentCompilationWarning"; + if (!toRun) { + callback(null, results); + } + }; - this.module = module; - this.loc = loc; + tasks.forEach((task, index) => { + const enqueue = () => { + this.boundWorkers(task, (error, data) => { + const result = error ? { + error + } : data; - Error.captureStackTrace(this, this.constructor); - } -} + const done = () => step(index, result); -module.exports = CommentCompilationWarning; + 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; /***/ }), -/***/ 85736: +/***/ 89301: /***/ (function(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; +const plugin = __webpack_require__(43884); +module.exports = plugin.default; /***/ }), -/***/ 85918: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 43884: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -const ConstDependency = __webpack_require__(71101); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; -const NullFactory = __webpack_require__(40438); +var _crypto = _interopRequireDefault(__webpack_require__(76417)); -/** @typedef {import("./Compiler")} Compiler */ +var _path = _interopRequireDefault(__webpack_require__(85622)); -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() - ); +var _sourceMap = __webpack_require__(96241); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", (parser, parserOptions) => { - if ( - parserOptions.browserify !== undefined && - !parserOptions.browserify - ) - return; +var _webpackSources = __webpack_require__(53665); - 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; +var _RequestShortener = _interopRequireDefault(__webpack_require__(54254)); +var _ModuleFilenameHelpers = _interopRequireDefault(__webpack_require__(71474)); -/***/ }), +var _schemaUtils = _interopRequireDefault(__webpack_require__(33225)); -/***/ 34968: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ +var _package = _interopRequireDefault(__webpack_require__(92203)); +var _options = _interopRequireDefault(__webpack_require__(11840)); -const asyncLib = __webpack_require__(36386); -const util = __webpack_require__(31669); -const { CachedSource } = __webpack_require__(53665); -const { - Tapable, - SyncHook, - SyncBailHook, - SyncWaterfallHook, - AsyncSeriesHook -} = __webpack_require__(56758); -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); +var _TaskRunner = _interopRequireDefault(__webpack_require__(16326)); -/** @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 */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// 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 */ +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; } -/** - * @typedef {Object} ModuleFactoryCreateDataContextInfo - * @property {string} issuer - * @property {string} compiler - */ +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; } -/** - * @typedef {Object} ModuleFactoryCreateData - * @property {ModuleFactoryCreateDataContextInfo} contextInfo - * @property {any=} resolveOptions - * @property {string} context - * @property {Dependency[]} dependencies - */ +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; } -/** - * @typedef {Object} ModuleFactory - * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create - */ +const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/; -/** - * @typedef {Object} SortedDependency - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - */ +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) + }; + } -/** - * @typedef {Object} DependenciesBlockLike - * @property {Dependency[]} dependencies - * @property {AsyncDependenciesBlock[]} blocks - * @property {DependenciesBlockVariable[]} variables - */ + 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'); + } -/** - * @typedef {Object} LogEntry - * @property {string} type - * @property {any[]} args - * @property {number} time - * @property {string[]=} trace - */ + static buildSourceMap(inputSourceMap) { + if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) { + return null; + } -/** - * @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) - */ + return new _sourceMap.SourceMapConsumer(inputSourceMap); + } -/** - * @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 - */ + 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 + }); -/** - * @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; -}; + 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}]`); + } -/** - * @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; -}; + 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}`); + } -/** - * @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; -}; + return new Error(`${file} from Terser\n${err.message}`); + } -/** - * @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; -}; + static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) { + let warningMessage = warning; + let locationMessage = ''; + let source = null; -/** - * @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]); - } - } -}; + if (sourceMap) { + const match = warningRegex.exec(warning); -/** - * @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]); - } -}; + if (match) { + const line = +match[1]; + const column = +match[2]; + const original = sourceMap.originalPositionFor({ + line, + column + }); -/** - * @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); - } -}; + if (original && original.source && original.source !== file && requestShortener) { + ({ + source + } = original); + warningMessage = `${warningMessage.replace(warningRegex, '')}`; + locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`; + } + } + } -/** - * @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); -}; + if (warningsFilter && !warningsFilter(warning, source)) { + return null; + } -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"]), + return `Terser Plugin: ${warningMessage}${locationMessage}`; + } - /** @type {SyncHook} */ - addEntry: new SyncHook(["entry", "name"]), - /** @type {SyncHook} */ - failedEntry: new SyncHook(["entry", "name", "error"]), - /** @type {SyncHook} */ - succeedEntry: new SyncHook(["entry", "name", "module"]), + apply(compiler) { + const buildModuleFn = moduleArg => { + // to get detailed location info about errors + moduleArg.useSourceMap = true; + }; - /** @type {SyncWaterfallHook} */ - dependencyReference: new SyncWaterfallHook([ - "dependencyReference", - "dependency", - "module" - ]), + 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]; - /** @type {AsyncSeriesHook} */ - finishModules: new AsyncSeriesHook(["modules"]), - /** @type {SyncHook} */ - finishRebuildingModule: new SyncHook(["module"]), - /** @type {SyncHook} */ - unseal: new SyncHook([]), - /** @type {SyncHook} */ - seal: new SyncHook([]), + if (processedAssets.has(asset)) { + return; + } - /** @type {SyncHook} */ - beforeChunks: new SyncHook([]), - /** @type {SyncHook} */ - afterChunks: new SyncHook(["chunks"]), + try { + let input; - /** @type {SyncBailHook} */ - optimizeDependenciesBasic: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeDependencies: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - afterOptimizeDependencies: new SyncHook(["modules"]), + if (this.options.sourceMap && asset.sourceAndMap) { + const { + source, + map + } = asset.sourceAndMap(); + input = source; - /** @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"]), + 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 - /** @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"]), + let commentsFile = false; - /** @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([]), + if (this.options.extractComments) { + commentsFile = this.options.extractComments.filename || `${file}.LICENSE`; - /** @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"]), + if (typeof commentsFile === 'function') { + commentsFile = commentsFile(file); + } + } - /** @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"]), + const task = { + file, + input, + inputSourceMap, + commentsFile, + extractComments: this.options.extractComments, + terserOptions: this.options.terserOptions, + minify: this.options.minify + }; - /** @type {SyncHook} */ - recordModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook} */ - recordChunks: new SyncHook(["chunks", "records"]), + 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); + } - /** @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"]), + 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; + } - /** @type {SyncHook} */ - beforeModuleAssets: new SyncHook([]), - /** @type {SyncBailHook} */ - shouldGenerateChunkAssets: new SyncBailHook([]), - /** @type {SyncHook} */ - beforeChunkAssets: new SyncHook([]), - /** @type {SyncHook} */ - additionalChunkAssets: new SyncHook(["chunks"]), + results.forEach((data, index) => { + const { + file, + input, + inputSourceMap, + commentsFile + } = tasks[index]; + const { + error, + map, + code, + warnings + } = data; + let { + extractedComments + } = data; + let sourceMap = null; - /** @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"]), + if (error || warnings && warnings.length > 0) { + sourceMap = TerserPlugin.buildSourceMap(inputSourceMap); + } // Handling results + // Error case: add errors, and go to next file - /** @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"]), + if (error) { + compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context))); + return; + } - /** @type {SyncWaterfallHook} */ - assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate + let outputSource; - /** @type {SyncBailHook} */ - needAdditionalPass: new SyncBailHook([]), + 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 - /** @type {SyncHook} */ - childCompiler: new SyncHook([ - "childCompiler", - "compilerName", - "compilerIndex" - ]), - /** @type {SyncBailHook} */ - log: new SyncBailHook(["origin", "logEntry"]), + if (commentsFile && extractedComments && extractedComments.length > 0) { + if (commentsFile in compilation.assets) { + const commentsFileSource = compilation.assets[commentsFile].source(); + extractedComments = extractedComments.filter(comment => !commentsFileSource.includes(comment)); + } - // TODO the following hooks are weirdly located here - // TODO move them for webpack 5 - /** @type {SyncHook} */ - normalModuleLoader: new SyncHook(["loaderContext", "module"]), + 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)}`; - /** @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; + if (typeof banner === 'function') { + banner = banner(commentsFile); + } - 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; + if (banner) { + outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource); + } + } - 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") - }; + const commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`); - this.semaphore = new Semaphore(options.parallelism || 100); + 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 - 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); - } + processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings - /** - * @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]}`); - } - } - } - }); - } + if (warnings && warnings.length > 0) { + warnings.forEach(warning => { + const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter); - /** - * @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 - */ + if (builtWarning) { + compilation.warnings.push(builtWarning); + } + }); + } + }); + taskRunner.exit(); + callback(); + }); + }; - /** - * @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]; + const plugin = { + name: this.constructor.name + }; + compiler.hooks.compilation.tap(plugin, compilation => { + if (this.options.sourceMap) { + compilation.hooks.buildModule.tap(plugin, buildModuleFn); + } - if (typeof cacheModule.updateCacheModule === "function") { - cacheModule.updateCacheModule(module); - } + const { + mainTemplate, + chunkTemplate + } = compilation; // Regenerate `contenthash` for minified assets - let rebuild = true; - if (this.fileTimestamps && this.contextTimestamps) { - rebuild = cacheModule.needRebuild( - this.fileTimestamps, - this.contextTimestamps - ); - } + 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); + }); + } - 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 - }; - } + compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation)); + }); + } - /** - * 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); - } +var _default = TerserPlugin; +exports.default = _default; - /** - * @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])); +/***/ 30787: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - const callback = err => { - this._buildingModules.delete(module); - for (const cb of callbackList) { - cb(err); - } - }; +"use strict"; - 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(); - } - ); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; - /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered - * @returns {void} - */ - processModuleDependencies(module, callback) { - const dependencies = new Map(); +var _terser = __webpack_require__(54775); - 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); - } - }; +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; } - const addDependenciesBlock = block => { - if (block.dependencies) { - iterationOfArrayCallback(block.dependencies, addDependency); - } - if (block.blocks) { - iterationOfArrayCallback(block.blocks, addDependenciesBlock); - } - if (block.variables) { - iterationBlockVariable(block.variables, addDependency); - } - }; +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; } - try { - addDependenciesBlock(module); - } catch (e) { - callback(e); - } +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 sortedDependencies = []; +const buildTerserOptions = ({ + ecma, + warnings, + parse = {}, + compress = {}, + mangle, + module, + output, + toplevel, + nameCache, + ie8, - for (const pair1 of dependencies) { - for (const pair2 of pair1[1]) { - sortedDependencies.push({ - factory: pair1[0], - dependencies: pair2[1] - }); - } - } + /* eslint-disable camelcase */ + keep_classnames, + keep_fnames, - this.addModuleDependencies( - module, - sortedDependencies, - this.bail, - null, - true, - callback - ); - } + /* 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 +}); - /** - * @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 && {}; +const buildComments = (options, terserOptions, extractedComments) => { + const condition = {}; + const commentsOpts = terserOptions.output.comments; // Use /^\**!|@preserve|@license|@cc_on/i RegExp - asyncLib.forEach( - dependencies, - (item, callback) => { - const dependencies = item.dependencies; + 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 - 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; + ['preserve', 'extract'].forEach(key => { + let regexStr; + let regex; - const isOptional = () => { - return dependencies.every(d => d.optional); - }; + switch (typeof condition[key]) { + case 'boolean': + condition[key] = condition[key] ? () => true : () => false; + break; - const errorOrWarningAndCallback = err => { - if (isOptional()) { - return warningAndCallback(err); - } else { - return errorAndCallback(err); - } - }; + case 'function': + break; - 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; - } + case 'string': + if (condition[key] === 'all') { + condition[key] = () => true; - const iterationDependencies = depend => { - for (let index = 0; index < depend.length; index++) { - const dep = depend[index]; - dep.module = dependentModule; - dependentModule.addReason(module, dep); - } - }; + break; + } - const addModuleResult = this.addModule( - dependentModule, - cacheGroup - ); - dependentModule = addModuleResult.module; - iterationDependencies(dependencies); + if (condition[key] === 'some') { + condition[key] = (astNode, comment) => { + return comment.type === 'comment2' && /^\**!|@preserve|@license|@cc_on/i.test(comment.value); + }; - const afterBuild = () => { - if (recursive && addModuleResult.dependencies) { - this.processModuleDependencies(dependentModule, callback); - } else { - return callback(); - } - }; + break; + } - if (addModuleResult.issuer) { - if (currentProfile) { - dependentModule.profile = currentProfile; - } + regexStr = condition[key]; - 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; - } - } - } - } + condition[key] = (astNode, comment) => { + return new RegExp(regexStr).test(comment.value); + }; - if (addModuleResult.build) { - this.buildModule( - dependentModule, - isOptional(), - module, - dependencies, - err => { - if (err) { - semaphore.release(); - return errorOrWarningAndCallback(err); - } + break; - if (currentProfile) { - const afterBuilding = Date.now(); - currentProfile.building = afterBuilding - afterFactory; - } + default: + regex = condition[key]; - 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. + condition[key] = (astNode, comment) => regex.test(comment.value); - if (err) { - // eslint-disable-next-line no-self-assign - err.stack = err.stack; - return callback(err); - } + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions - return process.nextTick(callback); - } - ); - } + return (astNode, comment) => { + if (condition.extract(astNode, comment)) { + const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments - /** - * - * @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 && {}; + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } - const errorAndCallback = this.bail - ? err => { - callback(err); - } - : err => { - err.dependencies = [dependency]; - this.errors.push(err); - callback(); - }; + return condition.preserve(astNode, comment); + }; +}; - 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}` - ); - } +const minify = options => { + const { + file, + input, + inputSourceMap, + extractComments, + minify: minifyFn + } = options; - 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)); - } + if (minifyFn) { + return minifyFn({ + [file]: input + }, inputSourceMap); + } // Copy terser options - let afterFactory; - if (currentProfile) { - afterFactory = Date.now(); - currentProfile.factory = afterFactory - start; - } + const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap - const addModuleResult = this.addModule(module); - module = addModuleResult.module; + if (inputSourceMap) { + terserOptions.sourceMap = true; + } - onModule(module); + const extractedComments = []; - dependency.module = module; - module.addReason(null, dependency); + if (extractComments) { + terserOptions.output.comments = buildComments(options, terserOptions, extractedComments); + } - const afterBuild = () => { - if (addModuleResult.dependencies) { - this.processModuleDependencies(module, err => { - if (err) return callback(err); - callback(null, module); - }); - } else { - return callback(null, module); - } - }; + const { + error, + map, + code, + warnings + } = (0, _terser.minify)({ + [file]: input + }, terserOptions); + return { + error, + map, + code, + warnings, + extractedComments + }; +}; - if (addModuleResult.issuer) { - if (currentProfile) { - module.profile = currentProfile; - } - } +var _default = minify; +exports.default = _default; - 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; - } +/***/ 71708: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.semaphore.release(); - afterBuild(); - }); - } else { - this.semaphore.release(); - this.waitForBuildingFinished(module, afterBuild); - } - } - ); - }); - } +"use strict"; +/*! + * to-object-path + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - /** - * - * @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; - } +var typeOf = __webpack_require__(48865); - // 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); - } +module.exports = function toPath(args) { + if (typeOf(args) !== 'arguments') { + args = arguments; + } + return filter(args).join('.'); +}; - 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); - } - ); - } +function filter(arr) { + var len = arr.length; + var idx = -1; + var res = []; - /** - * @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 - ); - } + 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; +} - /** - * @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); - } +/***/ 51279: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.processModuleDependencies(module, err => { - if (err) return callback(err); - this.removeReasonsOfDependencyBlock(module, { - dependencies: oldDependencies, - variables: oldVariables, - blocks: oldBlocks - }); - this.hooks.finishRebuildingModule.call(module); - callback(); - }); - }); - } +"use strict"; - 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]); - } +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; - callback(); - }); - } +/** + * Session cache + */ - 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(); - } - } +var cache = {}; - /** - * @param {Callback} callback signals when the seal method is finishes - * @returns {void} - */ - seal(callback) { - this.hooks.seal.call(); +/** + * 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 + */ - 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); +module.exports = function(patterns, options) { + if (!Array.isArray(patterns)) { + return makeRe(patterns, options); + } + return makeRe(patterns.join('|'), options); +}; - 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); +/** + * 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 + */ - GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); - GraphHelpers.connectChunkAndModule(chunk, module); +function makeRe(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } - chunk.entryModule = module; - chunk.name = name; + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } - this.assignDepth(module); - } - buildChunkGraph( - this, - /** @type {Entrypoint[]} */ (this.chunkGroups.slice()) - ); - this.sortModules(this.modules); - this.hooks.afterChunks.call(this.chunks); + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } - this.hooks.optimize.call(); + var key = pattern; + // do this before shallow cloning options, it's a lot faster + if (!options || (options && options.cache !== false)) { + key = createKey(pattern, options); - 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); + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + } - 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); + var opts = extend({}, options); + if (opts.contains === true) { + if (opts.negate === true) { + opts.strictNegate = false; + } else { + opts.strict = false; + } + } - this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { - if (err) { - return callback(err); - } + if (opts.strict === false) { + opts.strictOpen = false; + opts.strictClose = false; + } - this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var flags = opts.flags || ''; + var regex; - 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); + if (opts.nocase === true && !/i/.test(flags)) { + flags += 'i'; + } - const shouldRecord = this.hooks.shouldRecord.call() !== false; + try { + if (opts.negate || typeof opts.strictNegate === 'boolean') { + pattern = not.create(pattern, opts); + } - 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); + var str = open + '(?:' + pattern + ')' + close; + regex = new RegExp(str, flags); - this.sortItemsWithModuleIds(); + if (opts.safe === true && safe(regex) === false) { + throw new Error('potentially unsafe regular expression: ' + regex.source); + } - 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); + } catch (err) { + if (opts.strictErrors === true || opts.safe === true) { + err.key = key; + err.pattern = pattern; + err.originalOptions = options; + err.createdOptions = opts; + throw err; + } - this.sortItemsWithChunkIds(); + try { + regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); + } catch (err) { + regex = /.^/; //<= match nothing + } + } - if (shouldRecord) { - this.hooks.recordModules.call(this.modules, this.records); - this.hooks.recordChunks.call(this.chunks, this.records); - } + if (opts.cache !== false) { + memoize(regex, key, pattern, opts); + } + return regex; +} - this.hooks.beforeHash.call(); - this.createHash(); - this.hooks.afterHash.call(); +/** + * 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. + */ - if (shouldRecord) { - this.hooks.recordHash.call(this.records); - } +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; +} - 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); - } +/** + * 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. + */ - 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); - }); - }); - }); - }); - } +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; +} - /** - * @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); - } +/** + * Expose `makeRe` + */ - /** - * @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; +module.exports.makeRe = makeRe; - 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); - } - } - } +/***/ 74998: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * - * @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); - }; +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ - 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); - } - } +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; - applyModuleIds() { - const unusedIds = []; - let nextFreeModuleId = 0; - const usedIds = new Set(); - if (this.usedModuleIds) { - for (const id of this.usedModuleIds) { - usedIds.add(id); - } - } +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'); + } - 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 (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } - if (usedIds.size > 0) { - let usedIdMax = -1; - for (const usedIdKey of usedIds) { - if (typeof usedIdKey !== "number") { - continue; - } + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } - usedIdMax = Math.max(usedIdMax, usedIdKey); - } + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); - let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); + return obj; +}; - 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(); +/***/ 99793: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Get used ids from usedChunkIds property (i. e. from records) - if (this.usedChunkIds) { - for (const id of this.usedChunkIds) { - if (typeof id !== "number") { - continue; - } +"use strict"; - 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; +var isExtendable = __webpack_require__(78947); +var assignSymbols = __webpack_require__(64353); - if (typeof usedIdValue !== "number") { - continue; - } +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; +}; - usedIds.add(usedIdValue); - } +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} - // Calculate maximum assigned chunk id - let nextFreeChunkId = -1; - for (const id of usedIds) { - nextFreeChunkId = Math.max(nextFreeChunkId, id); - } - nextFreeChunkId++; +function isString(val) { + return (val && typeof val === 'string'); +} - // 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); - } - } - } +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} - // 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]; - } - } - } +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} - sortItemsWithModuleIds() { - this.modules.sort(byIdOrIdentifier); +/** + * Returns true if the given `key` is an own property of `obj`. + */ - const modules = this.modules; - for (let indexModule = 0; indexModule < modules.length; indexModule++) { - modules[indexModule].sortItems(false); - } +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - const chunks = this.chunks; - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - chunks[indexChunk].sortItems(); - } +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} - chunks.sort((a, b) => a.compareTo(b)); - } - sortItemsWithChunkIds() { - for (const chunkGroup of this.chunkGroups) { - chunkGroup.sortItems(); - } +/***/ }), - this.chunks.sort(byId); +/***/ 78947: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for ( - let indexModule = 0; - indexModule < this.modules.length; - indexModule++ - ) { - this.modules[indexModule].sortItems(true); - } +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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); - } +var isPlainObject = __webpack_require__(81064); - summarizeDependencies() { - this.fileDependencies = new SortableSet(this.compilationDependencies); - this.contextDependencies = new SortableSet(); - this.missingDependencies = new SortableSet(); +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; - 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]; +/***/ 29859: +/***/ (function(module) { - 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(); - } +/*! ***************************************************************************** +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); +}); - 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); - } +/***/ 7716: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {string} file file name - * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new - * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new - */ - updateAsset( - file, - newSourceOrFunction, - assetInfoUpdateOrFunction = undefined - ) { - if (!this.assets[file]) { - throw new Error( - `Called Compilation.updateAsset for not existing filename ${file}` - ); - } - if (typeof newSourceOrFunction === "function") { - this.assets[file] = newSourceOrFunction(this.assets[file]); - } else { - this.assets[file] = newSourceOrFunction; - } - if (assetInfoUpdateOrFunction !== undefined) { - const oldInfo = this.assetsInfo.get(file); - if (typeof assetInfoUpdateOrFunction === "function") { - this.assetsInfo.set(file, assetInfoUpdateOrFunction(oldInfo || {})); - } else { - this.assetsInfo.set( - file, - Object.assign({}, oldInfo, assetInfoUpdateOrFunction) - ); - } - } - } +"use strict"; - 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) || {} - }; - } +var isObject = __webpack_require__(18493); +var union = __webpack_require__(69123); +var get = __webpack_require__(89304); +var set = __webpack_require__(34857); - 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); - } - } - } - } +module.exports = function unionValue(obj, prop, value) { + if (!isObject(obj)) { + throw new TypeError('union-value expects the first argument to be an object.'); + } - 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; + if (typeof prop !== 'string') { + throw new TypeError('union-value expects `prop` to be a string.'); + } - // 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) - ); - } - } - } + var arr = arrayify(get(obj, prop)); + set(obj, prop, union(arr, arrayify(value))); + return obj; +}; - /** - * @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); - } +function arrayify(val) { + if (val === null || typeof val === 'undefined') { + return []; + } + if (Array.isArray(val)) { + return val; + } + return [val]; +} - /** - * @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(); +/***/ 5834: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); - } +"use strict"; +/*! + * unset-value + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - 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" -); +var isObject = __webpack_require__(96667); +var has = __webpack_require__(77735); -// 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 = function unset(obj, prop) { + if (!isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (obj.hasOwnProperty(prop)) { + delete obj[prop]; + return true; + } -module.exports = Compilation; + 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; +}; /***/ }), -/***/ 58705: +/***/ 77735: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/*! + * has-value + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ -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__(56758); -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); +var isObject = __webpack_require__(78037); +var hasValues = __webpack_require__(38719); +var get = __webpack_require__(89304); -const RequestShortener = __webpack_require__(54254); -const { makePathsRelative } = __webpack_require__(94658); -const ConcurrentCompilationError = __webpack_require__(18933); -const { Logger } = __webpack_require__(47194); +module.exports = function(obj, prop, noZero) { + if (isObject(obj)) { + return hasValues(get(obj, prop), noZero); + } + return hasValues(obj, prop); +}; -/** @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"]), +/***/ 78037: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @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"]), +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - /** @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"]), +var isArray = __webpack_require__(21352); - // 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; +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; +}; - 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; +/***/ 38719: +/***/ (function(module) { - /** @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(); +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - 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} */ ({}); +module.exports = function hasValue(o, noZero) { + if (o === null || o === undefined) { + return false; + } - this.context = context; + if (typeof o === 'boolean') { + return true; + } - this.requestShortener = new RequestShortener(context); + if (typeof o === 'number') { + if (o === 0 && noZero === true) { + return false; + } + return true; + } - /** @type {boolean} */ - this.running = false; + if (o.length !== undefined) { + return o.length !== 0; + } - /** @type {boolean} */ - this.watchMode = false; + for (var key in o) { + if (o.hasOwnProperty(key)) { + return true; + } + } + return 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()); +/***/ 94007: +/***/ (function(__unused_webpack_module, exports) { - this.running = true; - this.watchMode = true; - this.fileTimestamps = new Map(); - this.contextTimestamps = new Map(); - this.removedFiles = new Set(); - return new Watching(this, watchOptions, handler); - } +/** @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'; - run(callback) { - if (this.running) return callback(new ConcurrentCompilationError()); +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } - const finalCallback = (err, stats) => { - this.running = false; + 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; +} - if (err) { - this.hooks.failed.call(err); - } +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); - if (callback !== undefined) return callback(err, stats); - }; +var IRI_PROTOCOL = buildExps(true); - const startTime = Date.now(); +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; - this.running = true; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); - const onCompiled = (err, compilation) => { - if (err) return finalCallback(err); + 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; + } + } - 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; - } + return _arr; + } - this.emitAssets(compilation, err => { - if (err) return finalCallback(err); + 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"); + } + }; +}(); - 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); - }); - } +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - purgeInputFileSystem() { - if (this.inputFileSystem && this.inputFileSystem.purge) { - this.inputFileSystem.purge(); - } - } + return arr2; + } else { + return Array.from(arr); + } +}; - emitAssets(compilation, callback) { - let outputPath; - const emitFiles = err => { - if (err) return callback(err); +/** Highest positive signed 32-bit float value */ - asyncLib.forEachLimit( - compilation.getAssets(), - 15, - ({ name: file, source }, callback) => { - let targetFile = file; - const queryStringIdx = targetFile.indexOf("?"); - if (queryStringIdx >= 0) { - targetFile = targetFile.substr(0, queryStringIdx); - } +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - 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 - ); +/** 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' - // 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); - } +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - // 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) +/** 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' +}; - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size: cacheEntry.sizeOnlySource.size() - }); +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; - return callback(); - } - } +/*--------------------------------------------------------------------------*/ - // TODO webpack 5: if info.immutable check if file already exists in output - // skip emitting if it's already there +/** + * 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]); +} - // 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"); - } - } +/** + * 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; +} - // 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 - }); +/** + * 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; +} - // Write the file to output file system - this.outputFileSystem.writeFile(targetPath, content, err => { - if (err) return callback(err); +/** + * 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; +} - // information marker that the asset has been emitted - compilation.emittedAssets.add(file); +/** + * 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)); +}; - // 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(); +/** + * 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; +}; - 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(); - }); - } - ); - }; +/** + * 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); +}; - this.hooks.emit.callAsync(compilation, err => { - if (err) return callback(err); - outputPath = compilation.getPath(this.outputPath); - this.outputFileSystem.mkdirp(outputPath, emitFiles); - }); +/** + * 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)); +}; - 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); - } +/** + * 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; - const writeFile = () => { - this.outputFileSystem.writeFile( - this.recordsOutputPath, - JSON.stringify(this.records, undefined, 2), - callback - ); - }; + // 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. - if (!recordsOutputPathDirectory) { - return writeFile(); - } - this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { - if (err) return callback(err); - writeFile(); - }); + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; } - readRecords(callback) { - if (!this.recordsInputPath) { - this.records = {}; - return callback(); + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); } - this.inputFileSystem.stat(this.recordsInputPath, err => { - // It doesn't exist - // We can ignore this. - if (err) return callback(); + output.push(input.charCodeAt(j)); + } - this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { - if (err) return callback(err); + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. - try { - this.records = parseJson(content.toString("utf-8")); - } catch (e) { - e.message = "Cannot parse records: " + e.message; - return callback(e); - } + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ - return callback(); - }); - }); - } + // `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) { - 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(); - } + if (index >= inputLength) { + error$1('invalid-input'); } - } - 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 = {})); - } + var digit = basicToDigit(input.charCodeAt(index++)); - 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; + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } - compilation.hooks.childCompiler.call( - childCompiler, - compilerName, - compilerIndex - ); + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - return childCompiler; - } + if (digit < t) { + break; + } - isChild() { - return !!this.parentCompilation; - } + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } - createCompilation() { - return new Compilation(this); - } + w *= baseMinusT; + } - 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; - } + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); - createNormalModuleFactory() { - const normalModuleFactory = new NormalModuleFactory( - this.options.context, - this.resolverFactory, - this.options.module || {} - ); - this.hooks.normalModuleFactory.call(normalModuleFactory); - return normalModuleFactory; - } + // `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'); + } - createContextModuleFactory() { - const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); - this.hooks.contextModuleFactory.call(contextModuleFactory); - return contextModuleFactory; - } + n += floor(i / out); + i %= out; - newCompilationParams() { - const params = { - normalModuleFactory: this.createNormalModuleFactory(), - contextModuleFactory: this.createContextModuleFactory(), - compilationDependencies: new Set() - }; - return params; + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); } - 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); + return String.fromCodePoint.apply(String, output); +}; - compilation.seal(err => { - if (err) return callback(err); +/** + * 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 = []; - this.hooks.afterCompile.callAsync(compilation, err => { - if (err) return callback(err); + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); - return callback(null, compilation); - }); - }); - }); - }); - }); - } -} + // Cache the length. + var inputLength = input.length; -module.exports = Compiler; + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; -class SizeOnlySource extends Source { - constructor(size) { - super(); - this._size = size; - } + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - _error() { - return new Error( - "Content and Map of this Source is no longer available (only size() is supported)" - ); - } + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; - size() { - return this._size; + 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; + } + } } - /** - * @param {any} options options - * @returns {string} the source - */ - source(options) { - throw this._error(); - } + var basicLength = output.length; + var handledCPCount = basicLength; - node() { - throw this._error(); - } + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - listMap() { - throw this._error(); + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); } - map() { - throw this._error(); - } + // Main encoding loop: + while (handledCPCount < inputLength) { - listNode() { - throw this._error(); - } + // 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; - updateHash() { - throw this._error(); - } -} + 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; + } + } + } -/***/ 18933: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Maksim Nazarjev @acupofspirt -*/ + delta += (m - n) * handledCPCountPlusOne; + n = m; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; -const WebpackError = __webpack_require__(97391); + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; -module.exports = class ConcurrentCompilationError extends WebpackError { - constructor() { - super(); + 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); + } - this.name = "ConcurrentCompilationError"; - this.message = - "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; + 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; + } + } + } - Error.captureStackTrace(this, this.constructor); + ++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; + }); +}; -/***/ }), - -/***/ 84072: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const ConstDependency = __webpack_require__(71101); -const NullFactory = __webpack_require__(40438); -const ParserHelpers = __webpack_require__(23999); - -const getQuery = request => { - const i = request.indexOf("?"); - return i !== -1 ? request.substr(i) : ""; +/** + * 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; + }); }; -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); +/** 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 }; -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); - } - ); - } +/** + * 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; } -module.exports = ConstPlugin; - - -/***/ }), - -/***/ 10706: -/***/ (function(module) { - -"use strict"; - - -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; -class ContextExclusionPlugin { - /** - * @param {RegExp} negativeMatcher Matcher regular expression - */ - constructor(negativeMatcher) { - this.negativeMatcher = negativeMatcher; - } + var _matches = slicedToArray(matches, 2), + address = _matches[1]; - /** - * 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)); - }); - }); - } + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } } +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; -module.exports = ContextExclusionPlugin; - + 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]; -/***/ 20090: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const util = __webpack_require__(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 */ + 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] : {}; -/** - * @callback ResolveDependenciesCallback - * @param {Error=} err - * @param {ContextElementDependency[]} dependencies - */ + 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; +} -/** - * @callback ResolveDependencies - * @param {TODO} fs - * @param {TODO} options - * @param {ResolveDependenciesCallback} callback - */ +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; +} -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 = ""; - } +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(""); +} - super("javascript/dynamic", resource); +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - // Info from Factory - this.resolveDependencies = resolveDependencies; - this.options = Object.assign({}, options, { - resource: resource, - resourceQuery: resourceQuery - }); - if (options.resolveOptions !== undefined) { - this.resolveOptions = options.resolveOptions; - } + 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 - // Info from Build - this._contextDependencies = new Set([this.context]); + //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 +} - if (typeof options.mode !== "string") { - throw new Error("options.mode is a required option"); - } +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; - this._identifier = this._createIdentifier(); - } + 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; +} - updateCacheModule(module) { - this.resolveDependencies = module.resolveDependencies; - this.options = module.options; - this.resolveOptions = module.resolveOptions; - } +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} - prettyRegExp(regexString) { - // remove the "/" at the front and the beginning - // "/foo/" -> "foo" - return regexString.substring(1, regexString.length - 1); - } +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; +} - _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"; - } +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; +} - return identifier; - } +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} - identifier() { - return this._identifier; - } +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} - 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"; - } +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; + } +}; - return identifier; - } +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; - 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 + "")}`; - } +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; + } +}; - return identifier; - } +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; + } +}; - needRebuild(fileTimestamps, contextTimestamps) { - const ts = contextTimestamps.get(this.context); - if (!ts) { - return true; - } +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; + } +}; - return ts >= this.buildInfo.builtTime; - } +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; - 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); +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; - // abort if something failed - // this will create an empty context - if (!dependencies) { - callback(); - return; - } +Object.defineProperty(exports, '__esModule', { value: true }); - // enhance dependencies with meta info - for (const dep of dependencies) { - dep.loc = { - name: dep.userRequest - }; - dep.request = this.options.addon + dep.request; - } +}))); +//# sourceMappingURL=uri.all.js.map - 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; - } +/***/ 67806: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getFakeMapInitStatement(fakeMap) { - return typeof fakeMap === "object" - ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` - : ""; - } +// 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 - 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); +/***/ 77709: +/***/ (function(module) { - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} +"use strict"; +/*! + * use + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -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)} +module.exports = function base(app, options) { + if (!isObject(app) && typeof app !== 'function') { + throw new TypeError('expected an object or function'); + } -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;`; - } + var opts = isObject(options) ? options : {}; + var prop = typeof opts.prop === 'string' ? opts.prop : 'fns'; + if (!Array.isArray(app[prop])) { + define(app, prop, []); + } - getAsyncWeakSource(dependencies, id) { - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + /** + * 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 + */ - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + define(app, 'use', use); -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;`; - } + /** + * 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 + */ - 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)} + define(app, 'run', function(val) { + if (!isObject(val)) return; -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;`; - } + if (!val.use || !val.run) { + define(val, prop, val[prop] || []); + define(val, 'use', use); + } - 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__"; + if (!val[prop] || val[prop].indexOf(base) === -1) { + val.use(base); + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + var self = this || app; + var fns = self[prop]; + var len = fns.length; + var idx = -1; -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;`; - } + while (++idx < len) { + val.use(fns[idx]); + } + return val; + }); - 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; + /** + * Call plugin `fn`. If a function is returned push it into the + * `fns` array to be called by the `run` method. + */ - 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) - ); - } + function use(type, fn, options) { + var offset = 1; - return map; - }, Object.create(null)); + if (typeof type === 'string' || Array.isArray(type)) { + fn = wrap(type, fn); + offset++; + } else { + options = fn; + fn = type; + } - 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]" - ); + if (typeof fn !== 'function') { + throw new TypeError('expected a function'); + } - 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; - } + var self = this || app; + var fns = self[prop]; - ${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 args = [].slice.call(arguments, offset); + args.unshift(self); - var ids = map[req], id = ids[0]; - return ${requestPrefix}.then(function() { - ${returnModuleObject} - }); -}`; + if (typeof opts.hook === 'function') { + opts.hook.apply(self, args); + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${webpackAsyncContext} -webpackAsyncContext.keys = function webpackAsyncContextKeys() { - return Object.keys(map); + 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; }; -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; +function isObject(val) { + return val && typeof val === 'object' && !Array.isArray(val); } -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; - }); +function define(obj, key, val) { + Object.defineProperty(obj, key, { + configurable: true, + writable: true, + value: val + }); } -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; +/***/ 92262: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 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" - ) -}); +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ -// 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" - ) -}); +module.exports = __webpack_require__(31669).deprecate; -// 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" - ) -}); +/***/ 24059: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = ContextModule; +module.exports = __webpack_require__(47257); /***/ }), -/***/ 88239: +/***/ 71118: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -72406,705 +68952,254 @@ module.exports = ContextModule; */ -const asyncLib = __webpack_require__(36386); -const path = __webpack_require__(85622); - -const { - Tapable, - AsyncSeriesWaterfallHook, - SyncWaterfallHook -} = __webpack_require__(56758); -const ContextModule = __webpack_require__(20090); -const ContextElementDependency = __webpack_require__(89079); +const ConstDependency = __webpack_require__(71101); +const ParserHelpers = __webpack_require__(23999); -/** @typedef {import("./Module")} Module */ +const NullFactory = __webpack_require__(40438); -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; - } +/* 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 */ - const contextResolver = this.resolverFactory.get( - "context", - resolveOptions || EMPTY_RESOLVE_OPTIONS - ); - const loaderResolver = this.resolverFactory.get( - "loader", - EMPTY_RESOLVE_OPTIONS +class APIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "APIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() ); - 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 + 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)); } - ], - (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) - ); - } - ); - } - ); + 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); } ); } +} - 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); - } -}; +module.exports = APIPlugin; /***/ }), -/***/ 27295: +/***/ 36104: /***/ (function(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); +const WebpackError = __webpack_require__(97391); +const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; -class ContextReplacementPlugin { - constructor( - resourceRegExp, - newContentResource, - newContentRecursive, - newContentRegExp - ) { - this.resourceRegExp = resourceRegExp; +/** + * @param {string=} method method name + * @returns {string} message + */ +function createMessage(method) { + return `Abstract method${method ? " " + method : ""}. Must be overridden.`; +} - 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; - } - } +/** + * @constructor + */ +function Message() { + this.stack = undefined; + Error.captureStackTrace(this); + /** @type {RegExpMatchArray} */ + const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP); - 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; + this.message = match && match[1] ? createMessage(match[1]) : createMessage(); +} - 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; - }); - }); +/** + * 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"; } } -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; +module.exports = AbstractMethodError; /***/ }), -/***/ 97374: +/***/ 9701: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 */ +const { ConcatSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); -class RuntimeValue { - constructor(fn, fileDependencies) { - this.fn = fn; - this.fileDependencies = fileDependencies || []; - } +/** @typedef {import("./Compilation")} Compilation */ - exec(parser) { - if (this.fileDependencies === true) { - parser.state.module.buildInfo.cacheable = false; +/** + * @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 { - for (const fileDependency of this.fileDependencies) { - parser.state.module.buildInfo.fileDependencies.add(fileDependency); - } + this.name = options.name; + this.requireAsWrapper = options.requireAsWrapper; } - - 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 + * @param {Compilation} compilation the compilation instance * @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(compilation) { + const { mainTemplate, chunkTemplate } = compilation; - /** - * 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); - }); - }; + 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(", "); - /** - * 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); - }); - }; + if (this.requireAsWrapper) { + return new ConcatSource( + `require(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (this.name) { + const name = mainTemplate.getAssetPath(this.name, { + hash, + chunk + }); - /** - * 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); + 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, "});"); + } + }; - 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); - }); - }; + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "AmdMainTemplatePlugin", + onRenderWithEntry + ); + } - walkDefinitions(definitions, ""); - }; + mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + }); - 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); + mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { + hash.update("exports amd"); + if (this.name) { + hash.update(this.name); } - ); + }); } } -module.exports = DefinePlugin; + +module.exports = AmdMainTemplatePlugin; /***/ }), -/***/ 42173: +/***/ 22814: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73114,119 +69209,154 @@ module.exports = DefinePlugin; */ -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); +const DependenciesBlock = __webpack_require__(16071); -/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {TODO} GroupOptions */ -class DelegatedModule extends Module { - constructor(sourceRequest, data, type, userRequest, originalRequest) { - super("javascript/dynamic", null); +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; + } - // Info from Factory - this.sourceRequest = sourceRequest; - this.request = data.id; - this.type = type; - this.userRequest = userRequest; - this.originalRequest = originalRequest; - this.delegateData = data; + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } - // Build info - this.delegatedSourceDependency = undefined; + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + this.groupOptions.name = value; } - libIdent(options) { - return typeof this.originalRequest === "string" - ? this.originalRequest - : this.originalRequest.libIdent(options); + /** + * @returns {never} this throws and should never be called + */ + get chunks() { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); } - identifier() { - return `delegated ${JSON.stringify(this.request)} from ${ - this.sourceRequest - }`; + /** + * @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"); } - readableIdentifier() { - return `delegated ${this.userRequest} from ${this.sourceRequest}`; + /** + * @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); } - needRebuild() { - return false; + /** + * @returns {void} + */ + disconnect() { + this.chunkGroup = undefined; + super.disconnect(); } - 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(); + /** + * @returns {void} + */ + unseal() { + this.chunkGroup = undefined; + super.unseal(); } - source(depTemplates, runtime) { - const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); - const sourceModule = dep.module; - let str; + /** + * @returns {void} + */ + sortItems() { + super.sortItems(); + } +}; - 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 += ";"; - } +/***/ 67089: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (this.useSourceMap) { - return new OriginalSource(str, this.identifier()); - } else { - return new RawSource(str); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - size() { - return 42; - } +const WebpackError = __webpack_require__(97391); + +/** @typedef {import("./Module")} Module */ + +class AsyncDependencyToInitialChunkError extends WebpackError { /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} + * Creates an instance of AsyncDependencyToInitialChunkError. + * @param {string} chunkName Name of Chunk + * @param {Module} module module tied to dependency + * @param {TODO} loc location of dependency */ - updateHash(hash) { - hash.update(this.type); - hash.update(JSON.stringify(this.request)); - super.updateHash(hash); + 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 = DelegatedModule; +module.exports = AsyncDependencyToInitialChunkError; /***/ }), -/***/ 81002: +/***/ 51596: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73236,100 +69366,62 @@ module.exports = DelegatedModule; */ -const DelegatedModule = __webpack_require__(42173); +const asyncLib = __webpack_require__(36386); +const PrefetchDependency = __webpack_require__(14237); +const NormalModule = __webpack_require__(25963); -// 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" - ]; - } +/** @typedef {import("./Compiler")} Compiler */ - 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; - } - ); - } +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 = DelegatedModuleFactoryPlugin; +module.exports = AutomaticPrefetchPlugin; /***/ }), -/***/ 16071: +/***/ 4009: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73339,210 +69431,128 @@ module.exports = DelegatedModuleFactoryPlugin; */ -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 = []; - } +const { ConcatSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const Template = __webpack_require__(96066); - /** - * 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; - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(10171); - /** - * @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) - ); - } +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ - /** - * @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); +const wrapComment = str => { + if (!str.includes("\n")) { + return Template.toComment(str); } + return `/*!\n * ${str + .replace(/\*\//g, "* /") + .split("\n") + .join("\n * ")}\n */`; +}; +class BannerPlugin { /** - * @param {Dependency} dependency dependency being removed - * @returns {void} + * @param {BannerPluginArgument} options options object */ - removeDependency(dependency) { - const idx = this.dependencies.indexOf(dependency); - if (idx >= 0) { - this.dependencies.splice(idx, 1); + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "BannerPlugin only takes one argument (pass an options object)" + ); } - } - /** - * @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); - } + validateOptions(schema, options, "Banner Plugin"); - 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(); - } + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } - unseal() { - for (const block of this.blocks) block.unseal(); - } + /** @type {BannerPluginOptions} */ + this.options = options; - /** - * @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; - } + const bannerOption = options.banner; + if (typeof bannerOption === "function") { + const getBanner = bannerOption; + this.banner = this.options.raw + ? getBanner + : data => wrapComment(getBanner(data)); } 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; + const banner = this.options.raw + ? bannerOption + : wrapComment(bannerOption); + this.banner = () => banner; } - return false; - } - - sortItems() { - for (const block of this.blocks) block.sortItems(); } -} - -module.exports = DependenciesBlock; + apply(compiler) { + const options = this.options; + const banner = this.banner; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); -/***/ }), - -/***/ 82904: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + } -const { RawSource, ReplaceSource } = __webpack_require__(53665); + let query = ""; + let filename = file; + const hash = compilation.hash; + const querySplit = filename.indexOf("?"); -/** @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 */ + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } -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 || []; - } + const lastSlashIndex = filename.lastIndexOf("/"); - /** - * @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); - } - } + const basename = + lastSlashIndex === -1 + ? filename + : filename.substr(lastSlashIndex + 1); - /** - * @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; - } + const data = { + hash, + chunk, + filename, + basename, + query + }; - disconnect() { - for (const d of this.dependencies) { - d.disconnect(); - } - } + const comment = compilation.getPath(banner(data), data); - hasDependencies(filter) { - if (filter) { - return this.dependencies.some(filter); - } - return this.dependencies.length > 0; + compilation.updateAsset( + file, + old => new ConcatSource(comment, "\n", old) + ); + } + } + }); + }); } } -module.exports = DependenciesBlockVariable; +module.exports = BannerPlugin; /***/ }), -/***/ 57282: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 96770: +/***/ (function(module) { "use strict"; /* @@ -73551,224 +69561,253 @@ module.exports = DependenciesBlockVariable; */ -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 */ +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 Dependency { +class BasicEvaluatedExpression { 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; + 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; } - getResourceIdentifier() { - return null; + isNull() { + return this.type === TypeNull; } - // Returns the referenced module and export - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, true, this.weak); + isString() { + return this.type === TypeString; } - // Returns the exported names - getExports() { - return null; + isNumber() { + return this.type === TypeNumber; } - getWarnings() { - return null; + isBoolean() { + return this.type === TypeBoolean; } - getErrors() { - return null; + isRegExp() { + return this.type === TypeRegExp; } - updateHash(hash) { - hash.update((this.module && this.module.id) + ""); + isConditional() { + return this.type === TypeConditional; } - disconnect() { - this.module = null; + isArray() { + return this.type === TypeArray; } -} - -// 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; + isConstArray() { + return this.type === TypeConstArray; + } + isIdentifier() { + return this.type === TypeIdentifier; + } -/***/ }), + isWrapped() { + return this.type === TypeWrapped; + } -/***/ 6659: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + isTemplateString() { + return this.type === TypeTemplateString; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + isTruthy() { + return this.truthy; + } + isFalsy() { + return this.falsy; + } -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; + 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; } - apply(compiler) { - compiler.hooks.compilation.tap( - "DllEntryPlugin", - (compilation, { normalModuleFactory }) => { - const dllModuleFactory = new DllModuleFactory(); - compilation.dependencyFactories.set( - DllEntryDependency, - dllModuleFactory - ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); + 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); } - ); - 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 - ); - }); + 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; } -} - -module.exports = DllEntryPlugin; + setString(string) { + this.type = TypeString; + this.string = string; + return this; + } -/***/ }), + setNull() { + this.type = TypeNull; + return this; + } -/***/ 24803: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + setNumber(number) { + this.type = TypeNumber; + this.number = number; + return this; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + return this; + } + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + return this; + } -const { RawSource } = __webpack_require__(53665); -const Module = __webpack_require__(75993); + setIdentifier(identifier) { + this.type = TypeIdentifier; + this.identifier = identifier; + return this; + } -/** @typedef {import("./util/createHash").Hash} Hash */ + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + return this; + } -class DllModule extends Module { - constructor(context, dependencies, name, type) { - super("javascript/dynamic", context); + setOptions(options) { + this.type = TypeConditional; + this.options = options; + return this; + } - // Info from Factory - this.dependencies = dependencies; - this.name = name; - this.type = type; + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + } + for (const item of options) { + this.options.push(item); + } + return this; } - identifier() { - return `dll ${this.name}`; + setItems(items) { + this.type = TypeArray; + this.items = items; + return this; } - readableIdentifier() { - return `dll ${this.name}`; + setArray(array) { + this.type = TypeConstArray; + this.array = array; + return this; } - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = {}; - return callback(); + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + return this; } - source() { - return new RawSource("module.exports = __webpack_require__;"); + setTruthy() { + this.falsy = false; + this.truthy = true; + return this; } - needRebuild() { - return false; + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; } - size() { - return 12; + setRange(range) { + this.range = range; + return this; } - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - hash.update("dll module"); - hash.update(this.name || ""); - super.updateHash(hash); + setExpression(expression) { + this.expression = expression; + return this; } } -module.exports = DllModule; +module.exports = BasicEvaluatedExpression; /***/ }), -/***/ 62468: +/***/ 6465: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73778,941 +69817,1063 @@ module.exports = DllModule; */ -const { Tapable } = __webpack_require__(56758); -const DllModule = __webpack_require__(24803); +const asyncLib = __webpack_require__(36386); -class DllModuleFactory extends Tapable { - constructor() { - super(); - this.hooks = {}; +class CachePlugin { + constructor(cache) { + this.cache = cache || {}; + this.FS_ACCURACY = 2000; } - create(data, callback) { - const dependency = data.dependencies[0]; - callback( - null, - new DllModule( - data.context, - dependency.dependencies, - dependency.name, - dependency.type - ) - ); + + 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; + }); + } } -} -module.exports = DllModuleFactory; + /* 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; /***/ }), -/***/ 45255: +/***/ 8335: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra - */ +*/ -const DllEntryPlugin = __webpack_require__(6659); -const FlagAllModulesAsUsedPlugin = __webpack_require__(47163); -const LibManifestPlugin = __webpack_require__(30735); +const WebpackError = __webpack_require__(97391); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(7303); +/** @typedef {import("./Module")} Module */ -/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ +/** + * @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; + }); +}; -class DllPlugin { +/** + * @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 { /** - * @param {DllPluginOptions} options options object + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Module[]} modules modules that were detected */ - constructor(options) { - validateOptions(schema, options, "Dll Plugin"); - this.options = options; - } + 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}`); - 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); - } + this.name = "CaseSensitiveModulesWarning"; + this.origin = this.module = sortedModules[0]; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = DllPlugin; +module.exports = CaseSensitiveModulesWarning; /***/ }), -/***/ 86231: +/***/ 2919: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra +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 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()"; -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(61112); +/** @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 {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ +/** + * @typedef {Object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ -class DllReferencePlugin { - /** - * @param {DllReferencePluginOptions} options options object - */ - constructor(options) { - validateOptions(schema, options, "Dll Reference Plugin"); - this.options = options; - } +/** + * Compare two Modules based on their ids for sorting + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} sort value + */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DllReferencePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - DelegatedSourceDependency, - normalModuleFactory - ); - compilation.dependencyFactories.set( - DelegatedExportsDependency, - new NullFactory() - ); - } - ); +// TODO use @callback +/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ - 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); - } - } - } - } - ); - } -} +const sortModuleById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; -class DllManifestError extends WebpackError { - constructor(filename, message) { - super(); +/** + * 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; +}; - this.name = "DllManifestError"; - this.message = `Dll manifest ${filename}\n${message}`; +/** + * 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; +}; - Error.captureStackTrace(this, this.constructor); +/** + * @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() + "#"; } -} - -module.exports = DllReferencePlugin; - - -/***/ }), - -/***/ 49784: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Naoyuki Kanezawa @nkzawa -*/ + 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); -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); +/** + * @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; +}; -/** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */ -/** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */ -/** @typedef {import("./Compiler")} Compiler */ +/** + * 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; + } -class DynamicEntryPlugin { /** - * @param {string} context the context path - * @param {EntryDynamic} entry the entry value + * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead + * @returns {never} Throws an error trying to access this property */ - constructor(context, entry) { - this.context = context; - this.entry = entry; + get entry() { + throw new Error(ERR_CHUNK_ENTRY); } /** - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @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 */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DynamicEntryPlugin", - (compilation, { normalModuleFactory }) => { - const multiModuleFactory = new MultiModuleFactory(); + set entry(data) { + throw new Error(ERR_CHUNK_ENTRY); + } - compilation.dependencyFactories.set( - MultiEntryDependency, - multiModuleFactory - ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); - } - ); + /** + * @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); + } - 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(); - }); - }); - }; + /** + * @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); + } - 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); - } - }); + /** + * @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; } -} -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); + /** + * @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; } -}; - - -/***/ }), - -/***/ 99531: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(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); + /** + * @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; } -} - -module.exports = EntryModuleNotFoundError; - - -/***/ }), - -/***/ 14604: -/***/ (function(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); + /** + * @returns {boolean} if this chunk contains the entry module + */ + hasEntryModule() { + return !!this.entryModule; } - return new SingleEntryPlugin(context, item, name); -}; -module.exports = class EntryOptionPlugin { /** - * @param {Compiler} compiler the compiler instance one is tapping into - * @returns {void} + * @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 */ - 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); - } + addModule(module) { + if (!this._modules.has(module)) { + this._modules.add(module); return true; - }); + } + return false; } -}; - - -/***/ }), - -/***/ 71931: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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; + } -const ChunkGroup = __webpack_require__(52911); + /** + * @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); + } -/** @typedef {import("./Chunk")} Chunk */ + /** + * @returns {number} the amount of modules in chunk + */ + getNumberOfModules() { + return this._modules.size; + } -/** - * 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 + * @returns {SortableSet} return the modules SortableSet for this chunk */ - constructor(name) { - super(name); - /** @type {Chunk=} */ - this.runtimeChunk = undefined; + get modulesIterable() { + return this._modules; } /** - * isInitial will always return true for Entrypoint ChunkGroup. - * @returns {true} returns true as all entrypoints are initial ChunkGroups + * @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 */ - isInitial() { + addGroup(chunkGroup) { + if (this._groups.has(chunkGroup)) return false; + this._groups.add(chunkGroup); return true; } /** - * Sets the runtimeChunk for an entrypoint. - * @param {Chunk} chunk the chunk being set as the runtime chunk. - * @returns {void} + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed */ - setRuntimeChunk(chunk) { - this.runtimeChunk = chunk; + removeGroup(chunkGroup) { + if (!this._groups.has(chunkGroup)) return false; + this._groups.delete(chunkGroup); + return true; } /** - * Fetches the chunk reference containing the webpack bootstrap code - * @returns {Chunk} returns the runtime chunk or first chunk in `this.chunks` + * @param {ChunkGroup} chunkGroup the chunkGroup to check + * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup */ - getRuntimeChunk() { - return this.runtimeChunk || this.chunks[0]; + isInGroup(chunkGroup) { + return this._groups.has(chunkGroup); } /** - * @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 + * @returns {number} the amount of groups said chunk is in */ - replaceChunk(oldChunk, newChunk) { - if (this.runtimeChunk === oldChunk) this.runtimeChunk = newChunk; - return super.replaceChunk(oldChunk, newChunk); + getNumberOfGroups() { + return this._groups.size; } -} - -module.exports = Entrypoint; - - -/***/ }), - -/***/ 6098: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Authors Simen Brekken @simenbrekken, Einar Löve @einarlove -*/ - + /** + * @returns {SortableSet} the chunkGroups that said chunk is referenced in + */ + get groupsIterable() { + return this._groups; + } -/** @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 {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 {Compiler} compiler webpack compiler instance - * @returns {void} + * @param {Module} module Module to check + * @returns {boolean} returns true if module does exist in this chunk */ - 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." - ); + containsModule(module) { + return this._modules.has(module); + } - error.name = "EnvVariableNotDefinedError"; - compilation.warnings.push(error); - }); - } + /** + * @returns {Module[]} an array of modules (do not modify) + */ + getModules() { + return this._modules.getFromCache(getArray); + } - defs[`process.env.${key}`] = - value === undefined ? "undefined" : JSON.stringify(value); + getModulesIdent() { + return this._modules.getFromUnorderedCache(getModulesIdent); + } - return defs; - }, {}); + /** + * @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); + } + } - new DefinePlugin(definitions).apply(compiler); + /** + * + * @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]); } -} -module.exports = EnvironmentPlugin; + /** + * + * @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(); -/***/ 80140: -/***/ (function(__unused_webpack_module, exports) { + if (otherChunk.entryModule) { + this.entryModule = otherChunk.entryModule; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (const chunkGroup of otherChunk._groups) { + chunkGroup.replaceChunk(otherChunk, this); + this.addGroup(chunkGroup); + } + otherChunk._groups.clear(); + return true; + } -const loaderFlag = "LOADER_EXECUTION"; + /** + * @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); + } + } -const webpackOptionsFlag = "WEBPACK_OPTIONS"; + isEmpty() { + return this._modules.size === 0; + } -exports.cutOffByFlag = (stack, flag) => { - stack = stack.split("\n"); - for (let i = 0; i < stack.length; i++) { - if (stack[i].includes(flag)) { - stack.length = i; + 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); } } - return stack.join("\n"); -}; -exports.cutOffLoaderExecution = stack => - exports.cutOffByFlag(stack, loaderFlag); + canBeIntegrated(otherChunk) { + if (this.preventIntegration || otherChunk.preventIntegration) { + return false; + } -exports.cutOffWebpackOptions = stack => - exports.cutOffByFlag(stack, webpackOptionsFlag); + /** + * @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; + }; -exports.cutOffMultilineMessage = (stack, message) => { - stack = stack.split("\n"); - message = message.split("\n"); + const selfHasRuntime = this.hasRuntime(); + const otherChunkHasRuntime = otherChunk.hasRuntime(); - return stack - .reduce( - (acc, line, idx) => - line.includes(message[idx]) ? acc : acc.concat(line), - [] - ) - .join("\n"); -}; + if (selfHasRuntime !== otherChunkHasRuntime) { + if (selfHasRuntime) { + return isAvailable(this, otherChunk); + } else if (otherChunkHasRuntime) { + return isAvailable(otherChunk, this); + } else { + return false; + } + } -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; - } -}; + if (this.hasEntryModule() || otherChunk.hasEntryModule()) { + return false; + } -exports.cleanUp = (stack, message) => { - stack = exports.cutOffLoaderExecution(stack); - stack = exports.cutOffMessage(stack, message); - return stack; -}; + return true; + } -exports.cleanUpWebpackOptions = (stack, message) => { - stack = exports.cutOffWebpackOptions(stack); - stack = exports.cutOffMultilineMessage(stack, message); - return stack; -}; + /** + * + * @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); + } -/***/ 65200: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Object} options the size display options + * @returns {number} the chunk size + */ + size(options = {}) { + return this.addMultiplierAndOverhead(this.modulesSize(), options); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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(); + } + } -const EvalDevToolModuleTemplatePlugin = __webpack_require__(24157); + return this.addMultiplierAndOverhead(integratedModulesSize, options); + } -class EvalDevToolModulePlugin { - constructor(options) { - this.sourceUrlComment = options.sourceUrlComment; - this.moduleFilenameTemplate = options.moduleFilenameTemplate; - this.namespace = options.namespace; + /** + * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules + * @returns {void} + */ + sortModules(sortByFn) { + this._modules.sortWith(sortByFn || sortModuleById); } - apply(compiler) { - compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { - new EvalDevToolModuleTemplatePlugin({ - sourceUrlComment: this.sourceUrlComment, - moduleFilenameTemplate: this.moduleFilenameTemplate, - namespace: this.namespace - }).apply(compilation.moduleTemplates.javascript); - }); + sortItems() { + this.sortModules(); } -} -module.exports = EvalDevToolModulePlugin; + /** + * @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); + } + } -/***/ 24157: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return chunks; + } + /** + * @typedef {Object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name + */ -const { RawSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); + /** + * @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); -const cache = new WeakMap(); + 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; + } + } -class EvalDevToolModuleTemplatePlugin { - constructor(options) { - this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[loaders]"; - this.namespace = options.namespace || ""; + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; } - 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; + /** + * @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 + }); + } + } + } + } } - ); - moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { - hash.update("EvalDevToolModuleTemplatePlugin"); - hash.update("2"); - }); + } + 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; } -} -module.exports = EvalDevToolModuleTemplatePlugin; - - -/***/ }), - -/***/ 51352: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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]; + } + }; -const { RawSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); -const { absolutify } = __webpack_require__(94658); + 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); + } + } -const cache = new WeakMap(); + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } -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; + return chunkMaps; } - 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; - } + /** + * @typedef {Object} ChunkModuleMaps + * @property {Record} id + * @property {Record} hash + */ - /** @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; - } + /** + * @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); - // 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; + 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; } - ); - 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 + array.push(module.id); + chunkModuleHashMap[module.id] = module.renderedHash; + } + } + if (array !== undefined) { + array.sort(); + } + } - const evalSource = new RawSource( - `eval(${JSON.stringify(content + footer)});` - ); + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } - cache.set(source, evalSource); + /** + * + * @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(); - return evalSource; + 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; + } + } + } + } } - ); - moduleTemplate.hooks.hash.tap( - "EvalSourceMapDevToolModuleTemplatePlugin", - hash => { - hash.update("eval-source-map"); - hash.update("2"); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); } - ); + } + return false; } -} -module.exports = EvalSourceMapDevToolModuleTemplatePlugin; - -/***/ }), + toString() { + return `Chunk[${Array.from(this._modules).join()}]`; + } +} -/***/ 99994: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +// 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" + ) +}); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +// 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"); + } +}); -const EvalSourceMapDevToolModuleTemplatePlugin = __webpack_require__(51352); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); +// 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"); + } +}); -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; +// 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"); } +}); - 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); - } +// 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 = EvalSourceMapDevToolPlugin; +module.exports = Chunk; /***/ }), -/***/ 50471: +/***/ 52911: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74722,341 +70883,518 @@ module.exports = EvalSourceMapDevToolPlugin; */ -const { ConcatSource } = __webpack_require__(53665); +const SortableSet = __webpack_require__(50071); +const compareLocations = __webpack_require__(22562); -/** @typedef {import("./Compilation")} Compilation */ +/** @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; /** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path + * @template T + * @param {SortableSet} set set to convert to array. + * @returns {T[]} the array format of existing set */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +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; }; -class ExportPropertyMainTemplatePlugin { +/** + * @param {OriginRecord} a the first comparator in sort + * @param {OriginRecord} b the second comparator in sort + * @returns {1|-1|0} returns sorting order as index + */ +const sortOrigin = (a, b) => { + const aIdent = a.module ? a.module.identifier() : ""; + const bIdent = b.module ? b.module.identifier() : ""; + if (aIdent < bIdent) return -1; + if (aIdent > bIdent) return 1; + return compareLocations(a.loc, b.loc); +}; + +class ChunkGroup { /** - * @param {string|string[]} property the name of the property to export + * Creates an instance of ChunkGroup. + * @param {ChunkGroupOptions=} options chunk group options passed to chunkGroup */ - constructor(property) { - this.property = property; + 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(); } /** - * @param {Compilation} compilation the compilation instance + * when a new chunk is added to a chunkGroup, addingOptions will occur. + * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions * @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 - ); + 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}` + ); + } + } } - - mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { - hash.update("export property"); - hash.update(`${this.property}`); - }); } -} -module.exports = ExportPropertyMainTemplatePlugin; + /** + * 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("+"); + } -/***/ 17270: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * 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("+"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * 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; + } -const Template = __webpack_require__(96066); -const ConstDependency = __webpack_require__(71101); -const ParserHelpers = __webpack_require__(23999); -const NullFactory = __webpack_require__(40438); + /** + * 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; + } -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" -}; + /** + * @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; + } + } -class ExtendedAPIPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "ExtendedAPIPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); + removeChunk(chunk) { + const idx = this.chunks.indexOf(chunk); + if (idx >= 0) { + this.chunks.splice(idx, 1); + return true; + } + return false; + } - 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); + isInitial() { + return false; + } - 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]) - ); - }); - }; + addChild(chunk) { + if (this._children.has(chunk)) { + return false; + } + this._children.add(chunk); + return true; + } - 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); - } - ); + getChildren() { + return this._children.getFromCache(getArray); } -} -module.exports = ExtendedAPIPlugin; + getNumberOfChildren() { + return this._children.size; + } + get childrenIterable() { + return this._children; + } -/***/ }), + removeChild(chunk) { + if (!this._children.has(chunk)) { + return false; + } -/***/ 17204: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this._children.delete(chunk); + chunk.removeParent(this); + return true; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + addParent(parentChunk) { + if (!this._parents.has(parentChunk)) { + this._parents.add(parentChunk); + return true; + } + return false; + } + getParents() { + return this._parents.getFromCache(getArray); + } -const { OriginalSource, RawSource } = __webpack_require__(53665); -const Module = __webpack_require__(75993); -const WebpackMissingModule = __webpack_require__(75386); -const Template = __webpack_require__(96066); + setParents(newParents) { + this._parents.clear(); + for (const p of newParents) { + this._parents.add(p); + } + } -/** @typedef {import("./util/createHash").Hash} Hash */ + getNumberOfParents() { + return this._parents.size; + } -class ExternalModule extends Module { - constructor(request, type, userRequest) { - super("javascript/dynamic", null); + hasParent(parent) { + return this._parents.has(parent); + } - // Info from Factory - this.request = request; - this.externalType = type; - this.userRequest = userRequest; - this.external = true; + get parentsIterable() { + return this._parents; } - libIdent() { - return this.userRequest; + removeParent(chunk) { + if (this._parents.delete(chunk)) { + chunk.removeChunk(this); + return true; + } + return false; } - chunkCondition(chunk) { - return chunk.hasEntryModule(); + /** + * @returns {Array} - an array containing the blocks + */ + getBlocks() { + return this._blocks.getFromCache(getArray); } - identifier() { - return "external " + JSON.stringify(this.request); + getNumberOfBlocks() { + return this._blocks.size; } - readableIdentifier() { - return "external " + JSON.stringify(this.request); + hasBlock(block) { + return this._blocks.has(block); } - needRebuild() { + get blocksIterable() { + return this._blocks; + } + + addBlock(block) { + if (!this._blocks.has(block)) { + this._blocks.add(block); + return true; + } return false; } - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = {}; - callback(); + addOrigin(module, loc, request) { + this.origins.push({ + module, + loc, + request + }); } - getSourceForGlobalVariableExternal(variableName, type) { - if (!Array.isArray(variableName)) { - // make it an array as the look up works the same basically - variableName = [variableName]; + containsModule(module) { + for (const chunk of this.chunks) { + if (chunk.containsModule(module)) return true; } - - // needed for e.g. window["some"]["thing"] - const objectLookup = variableName - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - return `(function() { module.exports = ${type}${objectLookup}; }());`; + return false; } - getSourceForCommonJsExternal(moduleAndSpecifiers) { - if (!Array.isArray(moduleAndSpecifiers)) { - return `module.exports = require(${JSON.stringify( - moduleAndSpecifiers - )});`; + getFiles() { + const files = new Set(); + + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); + } } - const moduleName = moduleAndSpecifiers[0]; - const objectLookup = moduleAndSpecifiers - .slice(1) - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - return `module.exports = require(${JSON.stringify( - moduleName - )})${objectLookup};`; + return Array.from(files); } - checkExternalVariable(variableToCheck, request) { - return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( - request - )}}\n`; - } + /** + * @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); - getSourceForAmdOrUmdExternal(id, optional, request) { - const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${id}` - )}__`; - const missingModuleError = optional - ? this.checkExternalVariable(externalVariable, request) - : ""; - return `${missingModuleError}module.exports = ${externalVariable};`; - } + // 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); + } + } - getSourceForDefaultCase(optional, request) { - if (!Array.isArray(request)) { - // make it an array as the look up works the same basically - request = [request]; + /** + * 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); } - 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};`; - } + // cleanup blocks + for (const block of this._blocks) { + block.chunkGroup = null; + } - 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); + // remove chunks + for (const chunk of this.chunks) { + chunk.removeGroup(this); } } - getSource(sourceString) { - if (this.useSourceMap) { - return new OriginalSource(sourceString, this.identifier()); + 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; } + } - return new RawSource(sourceString); + 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; } - source(dependencyTemplates, runtime) { - return this.getSource(this.getSourceString(runtime)); + /** + * 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); } - size() { - return 42; + /** + * 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); } /** - * @param {Hash} hash the hash used to track dependencies + * 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} */ - updateHash(hash) { - hash.update(this.externalType); - hash.update(JSON.stringify(this.request)); - hash.update(JSON.stringify(Boolean(this.optional))); - super.updateHash(hash); + 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 = ExternalModule; +module.exports = ChunkGroup; /***/ }), -/***/ 67876: +/***/ 69865: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75066,115 +71404,37 @@ module.exports = ExternalModule; */ -const ExternalModule = __webpack_require__(17204); +const WebpackError = __webpack_require__(97391); -class ExternalModuleFactoryPlugin { - constructor(type, externals) { - this.type = type; - this.externals = externals; +/** @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); } +} - 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; +module.exports = ChunkRenderError; /***/ }), -/***/ 75705: +/***/ 6170: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75184,29 +71444,93 @@ module.exports = ExternalModuleFactoryPlugin; */ -const ExternalModuleFactoryPlugin = __webpack_require__(67876); +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); -class ExternalsPlugin { - constructor(type, externals) { - this.type = type; - this.externals = externals; +/** @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"]) + }; } - apply(compiler) { - compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { - new ExternalModuleFactoryPlugin(this.type, this.externals).apply( - normalModuleFactory - ); - }); + + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + + this.hooks.renderManifest.call(result, options); + + return result; } -} -module.exports = ExternalsPlugin; + /** + * 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); + } +}; /***/ }), -/***/ 47163: -/***/ (function(module) { +/***/ 51760: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -75215,43 +71539,37 @@ module.exports = ExternalsPlugin; */ +const WebpackError = __webpack_require__(97391); -/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ -class FlagAllModulesAsUsedPlugin { - constructor(explanation) { - this.explanation = explanation; - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +class CommentCompilationWarning extends WebpackError { /** - * @param {Compiler} compiler webpack compiler - * @returns {void} + * + * @param {string} message warning message + * @param {Module} module affected module + * @param {DependencyLocation} loc affected lines of code */ - 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); - } - } - ); - } - ); + constructor(message, module, loc) { + super(message); + + this.name = "CommentCompilationWarning"; + + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = FlagAllModulesAsUsedPlugin; +module.exports = CommentCompilationWarning; /***/ }), -/***/ 73599: +/***/ 85736: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75261,180 +71579,117 @@ module.exports = FlagAllModulesAsUsedPlugin; */ -const Queue = __webpack_require__(38637); - -const addToSet = (a, b) => { - for (const item of b) { - a.add(item); - } -}; +const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); -class FlagDependencyExportsPlugin { +class CommonJsStuffPlugin { 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); + "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, "/")}`; } } - }; - - // 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(); + return ParserHelpers.addParsedVariableToModule( + parser, + "module", + `require(${JSON.stringify(moduleJsPath)})(module)` + ); + }); + }; - 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); - } - ); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsStuffPlugin", handler); } ); } } - -module.exports = FlagDependencyExportsPlugin; +module.exports = CommonJsStuffPlugin; /***/ }), -/***/ 33632: -/***/ (function(module) { +/***/ 85918: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -75443,2823 +71698,2410 @@ module.exports = FlagDependencyExportsPlugin; */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ - -/** @typedef {false | true | string[]} UsedExports */ +const ConstDependency = __webpack_require__(71101); -const addToSet = (a, b) => { - for (const item of b) { - if (!a.includes(item)) a.push(item); - } - return a; -}; +const NullFactory = __webpack_require__(40438); -const isSubset = (biggerSet, subset) => { - if (biggerSet === true) return true; - if (subset === true) return false; - return subset.every(item => biggerSet.indexOf(item) >= 0); -}; +/** @typedef {import("./Compiler")} Compiler */ -class FlagDependencyUsagePlugin { +class CompatibilityPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ 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]); - } - }; + compiler.hooks.compilation.tap( + "CompatibilityPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - 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; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", (parser, parserOptions) => { 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: -/***/ (function(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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { ConcatSource } = __webpack_require__(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; - } - ); + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) + return; - 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; + 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; + }); + }); } ); - - moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { - hash.update("FunctionModuleTemplatePlugin"); - hash.update("2"); - }); } } -module.exports = FunctionModuleTemplatePlugin; +module.exports = CompatibilityPlugin; /***/ }), -/***/ 39172: -/***/ (function(module) { +/***/ 34968: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra -*/ + */ -/** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +const asyncLib = __webpack_require__(36386); +const util = __webpack_require__(31669); +const { CachedSource } = __webpack_require__(53665); +const { + Tapable, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook +} = __webpack_require__(56758); +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 */ -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; - } +/** + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {any=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ - /** - * @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 - ); - } -} +/** + * @typedef {Object} ModuleFactory + * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create + */ -module.exports = Generator; +/** + * @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 + */ -/***/ 32973: -/***/ (function(__unused_webpack_module, exports) { +/** + * @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 {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** + * @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 {ChunkGroup} chunkGroup the ChunkGroup to connect - * @param {Chunk} chunk chunk to tie to ChunkGroup - * @returns {void} + * @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 connectChunkGroupAndChunk = (chunkGroup, chunk) => { - if (chunkGroup.pushChunk(chunk)) { - chunk.addGroup(chunkGroup); +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 {ChunkGroup} parent parent ChunkGroup to connect - * @param {ChunkGroup} child child ChunkGroup to connect - * @returns {void} + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value */ -const connectChunkGroupParentAndChild = (parent, child) => { - if (parent.addChild(child)) { - child.addParent(parent); +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 {Chunk} chunk Chunk to connect to Module - * @param {Module} module Module to connect to Chunk - * @returns {void} + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value */ -const connectChunkAndModule = (chunk, module) => { - if (module.addChunk(chunk)) { - chunk.addModule(module); - } +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 {Chunk} chunk Chunk being disconnected - * @param {Module} module Module being disconnected - * @returns {void} + * @param {Compilation} a first compilation to sort by + * @param {Compilation} b second compilation to sort by + * @returns {-1|0|1} sort value */ -const disconnectChunkAndModule = (chunk, module) => { - chunk.removeModule(module); - module.removeChunk(chunk); +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 {AsyncDependenciesBlock} depBlock DepBlock being tied to ChunkGroup - * @param {ChunkGroup} chunkGroup ChunkGroup being tied to DepBlock + * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over + * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements * @returns {void} */ -const connectDependenciesBlockAndChunkGroup = (depBlock, chunkGroup) => { - if (chunkGroup.addBlock(depBlock)) { - depBlock.chunkGroup = chunkGroup; +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]); + } } }; -exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; -exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; -exports.connectChunkAndModule = connectChunkAndModule; -exports.disconnectChunkAndModule = disconnectChunkAndModule; -exports.connectDependenciesBlockAndChunkGroup = connectDependenciesBlockAndChunkGroup; - +/** + * @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); + } +}; -/***/ 30327: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @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); +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ +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"]), -const WebpackError = __webpack_require__(97391); + /** @type {SyncWaterfallHook} */ + dependencyReference: new SyncWaterfallHook([ + "dependencyReference", + "dependency", + "module" + ]), -module.exports = class HarmonyLinkingError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "HarmonyLinkingError"; - this.hideStack = true; + /** @type {AsyncSeriesHook} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {SyncHook} */ + finishRebuildingModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + unseal: new SyncHook([]), + /** @type {SyncHook} */ + seal: new SyncHook([]), - Error.captureStackTrace(this, this.constructor); - } -}; + /** @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"]), -/***/ 50268: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @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"]), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {AsyncSeriesHook} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), -const createHash = __webpack_require__(15660); + /** @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([]), -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(45843); + /** @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"]), -/** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ + /** @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"]), -class HashedModuleIdsPlugin { - /** - * @param {HashedModuleIdsPluginOptions=} options options object - */ - constructor(options) { - if (!options) options = {}; + /** @type {SyncHook} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook} */ + recordChunks: new SyncHook(["chunks", "records"]), - validateOptions(schema, options, "Hashed Module Ids Plugin"); + /** @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 {HashedModuleIdsPluginOptions} */ - this.options = Object.assign( - { - context: null, - hashFunction: "md4", - hashDigest: "base64", - hashDigestLength: 4 - }, - options - ); - } + /** @type {SyncHook} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook} */ + beforeChunkAssets: new SyncHook([]), + /** @type {SyncHook} */ + additionalChunkAssets: new SyncHook(["chunks"]), - 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); - } - } - } - ); - }); - } -} + /** @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"]), -module.exports = HashedModuleIdsPlugin; + /** @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 -/***/ 65217: -/***/ (function(module) { + /** @type {SyncBailHook} */ + needAdditionalPass: new SyncBailHook([]), -/* - 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; + /** @type {SyncHook} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), -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 = []; + /** @type {SyncBailHook} */ + log: new SyncBailHook(["origin", "logEntry"]), - // 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; - }); + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook} */ + normalModuleLoader: new SyncHook(["loaderContext", "module"]), - 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); + /** @type {SyncBailHook} */ + optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunks: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeExtractedChunks: new SyncHook(["chunks"]) }; - 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; - } - }, + 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; - // 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); - }, + 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; - //inherit from previous dispose call - data: hotCurrentModuleData[moduleId] + 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") }; - hotCurrentChildModule = undefined; - return hot; - } - var hotStatusHandlers = []; - var hotStatus = "idle"; + this.semaphore = new Semaphore(options.parallelism || 100); - function hotSetStatus(newStatus) { - hotStatus = newStatus; - for (var i = 0; i < hotStatusHandlers.length; i++) - hotStatusHandlers[i].call(null, newStatus); + 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(); } - // 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; + getStats() { + return new Stats(this); } - function hotCheck(apply) { - if (hotStatus !== "idle") { - throw new Error("check() is only allowed in idle status"); + /** + * @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"); } - hotApplyOnUpdate = apply; - hotSetStatus("check"); - return hotDownloadManifest(hotRequestTimeout).then(function(update) { - if (!update) { - hotSetStatus(hotApplyInvalidatedModules() ? "ready" : "idle"); - return null; + /** @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" + ); + } } - 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); + 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; } - if ( - hotStatus === "prepare" && - hotChunksLoading === 0 && - hotWaitingFiles === 0 - ) { - hotUpdateDownloaded(); + /** @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]}`); + } + } } - 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(); - } - } + /** + * @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 + */ - function hotEnsureUpdateChunk(chunkId) { - if (!hotAvailableFilesMap[chunkId]) { - hotWaitingFilesMap[chunkId] = true; - } else { - hotRequestedFilesMap[chunkId] = true; - hotWaitingFiles++; - hotDownloadUpdateChunk(chunkId); + /** + * @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]; - 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); - } + if (typeof cacheModule.updateCacheModule === "function") { + cacheModule.updateCacheModule(module); + } + + let rebuild = true; + if (this.fileTimestamps && this.contextTimestamps) { + rebuild = cacheModule.needRebuild( + this.fileTimestamps, + this.contextTimestamps ); - } else { - var outdatedModules = []; - for (var id in hotUpdate) { - if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { - outdatedModules.push(toModuleId(id)); + } + + 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 + }; } - deferred.resolve(outdatedModules); + 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 + }; } - function hotApply(options) { - if (hotStatus !== "ready") - throw new Error("apply() is only allowed in ready status"); - options = options || {}; - return hotApplyInternal(options); + /** + * 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); } - function hotApplyInternal(options) { - hotApplyInvalidatedModules(); + /** + * 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); + } - var cb; - var i; - var j; - var module; - var moduleId; + /** + * @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); + } + } - function getAffectedStuff(updateModuleId) { - var outdatedModules = [updateModuleId]; - var outdatedDependencies = {}; + /** + * 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])); - 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 - }; + 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); + } } - if (module.hot._main) { - return { - type: "unaccepted", - chain: chain, - moduleId: moduleId - }; + + 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); } - 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 - }); + 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(); } + ); + } - return { - type: "accepted", - moduleId: updateModuleId, - outdatedModules: outdatedModules, - outdatedDependencies: outdatedDependencies - }; - } + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + const dependencies = new Map(); - function addAllToSet(a, b) { - for (var i = 0; i < b.length; i++) { - var item = b[i]; - if (a.indexOf(item) === -1) a.push(item); + 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); } - // 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 = {}; + const sortedDependencies = []; - var warnUnexpectedRequire = function warnUnexpectedRequire() { - console.warn( - "[HMR] unexpected require(" + result.moduleId + ") to disposed module" - ); - }; + for (const pair1 of dependencies) { + for (const pair2 of pair1[1]) { + sortedDependencies.push({ + factory: pair1[0], + dependencies: pair2[1] + }); + } + } - 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; - } - } - } + this.addModuleDependencies( + module, + sortedDependencies, + this.bail, + null, + true, + callback + ); + } - // 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 - }); - } - } + /** + * @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 && {}; - // Now in "dispose" phase - hotSetStatus("dispose"); - Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { - if (hotAvailableFilesMap[chunkId] === false) { - hotDisposeChunk(chunkId); - } - }); + asyncLib.forEach( + dependencies, + (item, callback) => { + const dependencies = item.dependencies; - var idx; - var queue = outdatedModules.slice(); - while (queue.length > 0) { - moduleId = queue.pop(); - module = installedModules[moduleId]; - if (!module) continue; + 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(); + }; - var data = {}; + 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; - // Call dispose handlers - var disposeHandlers = module.hot._disposeHandlers; - for (j = 0; j < disposeHandlers.length; j++) { - cb = disposeHandlers[j]; - cb(data); - } - hotCurrentModuleData[moduleId] = data; + const isOptional = () => { + return dependencies.every(d => d.optional); + }; - // disable module (this disables requires from this module) - module.hot.active = false; + const errorOrWarningAndCallback = err => { + if (isOptional()) { + return warningAndCallback(err); + } else { + return errorAndCallback(err); + } + }; - // remove module from cache - delete installedModules[moduleId]; + 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; + } - // when disposing there is no need to call dispose handler - delete outdatedDependencies[moduleId]; + const iterationDependencies = depend => { + for (let index = 0; index < depend.length; index++) { + const dep = depend[index]; + dep.module = dependentModule; + dependentModule.addReason(module, dep); + } + }; - // 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); - } - } - } + const addModuleResult = this.addModule( + dependentModule, + cacheGroup + ); + dependentModule = addModuleResult.module; + iterationDependencies(dependencies); - // 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); - } - } - } - } + const afterBuild = () => { + if (recursive && addModuleResult.dependencies) { + this.processModuleDependencies(dependentModule, callback); + } else { + return callback(); + } + }; - // Now in "apply" phase - hotSetStatus("apply"); + if (addModuleResult.issuer) { + if (currentProfile) { + dependentModule.profile = currentProfile; + } - if (hotUpdateNewHash !== undefined) { - hotCurrentHash = hotUpdateNewHash; - hotUpdateNewHash = undefined; - } - hotUpdate = undefined; + 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; + } + } + } + } - // insert new code - for (moduleId in appliedUpdate) { - if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { - modules[moduleId] = appliedUpdate[moduleId]; - } - } + if (addModuleResult.build) { + this.buildModule( + dependentModule, + isOptional(), + module, + dependencies, + err => { + if (err) { + semaphore.release(); + return errorOrWarningAndCallback(err); + } - // 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; + 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. - // 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; - } + if (err) { + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + return callback(err); } - } - } - // handle errors in accept handlers and self accepted module load - if (error) { - hotSetStatus("fail"); - return Promise.reject(error); - } + return process.nextTick(callback); + } + ); + } - if (hotQueuedInvalidatedModules) { - return hotApplyInternal(options).then(function(list) { - outdatedModules.forEach(function(moduleId) { - if (list.indexOf(moduleId) < 0) list.push(moduleId); - }); - return list; - }); - } + /** + * + * @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 && {}; - hotSetStatus("idle"); - return new Promise(function(resolve) { - resolve(outdatedModules); - }); - } + const errorAndCallback = this.bail + ? err => { + callback(err); + } + : err => { + err.dependencies = [dependency]; + this.errors.push(err); + callback(); + }; - function hotApplyInvalidatedModules() { - if (hotQueuedInvalidatedModules) { - if (!hotUpdate) hotUpdate = {}; - hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); - hotQueuedInvalidatedModules = undefined; - return true; + 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}` + ); } - } - function hotApplyInvalidatedModule(moduleId) { - if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) - hotUpdate[moduleId] = modules[moduleId]; - } -}; + 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; + } -/***/ 69575: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const addModuleResult = this.addModule(module); + module = addModuleResult.module; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + onModule(module); + dependency.module = module; + module.addReason(null, dependency); -const { SyncBailHook } = __webpack_require__(56758); -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); + const afterBuild = () => { + if (addModuleResult.dependencies) { + this.processModuleDependencies(module, err => { + if (err) return callback(err); + callback(null, module); }); - 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()); + } else { + return callback(null, module); } - 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; - } + if (addModuleResult.issuer) { + if (currentProfile) { + module.profile = currentProfile; } - 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); - } - ); + if (addModuleResult.build) { + this.buildModule(module, false, null, null, err => { + if (err) { + this.semaphore.release(); + return errorAndCallback(err); + } - const needChunkLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.chunks.length > 1) return true; - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } - 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)};` - ) - ]); + this.semaphore.release(); + afterBuild(); + }); + } else { + this.semaphore.release(); + this.waitForBuildingFinished(module, afterBuild); } - ); + } + ); + }); + } - mainTemplate.hooks.globalHash.tap( - "HotModuleReplacementPlugin", - () => true - ); + /** + * + * @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); - mainTemplate.hooks.currentHash.tap( - "HotModuleReplacementPlugin", - (_, length) => { - if (isFinite(length)) { - return `hotCurrentHash.substr(0, ${length})`; - } else { - return "hotCurrentHash"; - } - } - ); + const slot = { + name: name, + // TODO webpack 5 remove `request` + request: null, + module: null + }; - mainTemplate.hooks.moduleObj.tap( - "HotModuleReplacementPlugin", - (source, chunk, hash, varModuleId) => { - return Template.asString([ - `${source},`, - `hot: hotCreateModule(${varModuleId}),`, - "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", - "children: []" - ]); - } - ); + if (entry instanceof ModuleDependency) { + slot.request = entry.request; + } - // 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); + // 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); + } - compilation.hooks.normalModuleLoader.tap( - "HotModuleReplacementPlugin", - context => { - context.hot = true; + 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); } ); } -}; -const hotInitCode = Template.getFunctionContent( - __webpack_require__(65217) -); + /** + * @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); + } + }; -/***/ 26782: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); -const Chunk = __webpack_require__(2919); + for (let index = 0; index < modules.length; index++) { + const module = modules[index]; + this.reportDependencyErrorsAndWarnings(module, [module]); + } -class HotUpdateChunk extends Chunk { - constructor() { - super(); - /** @type {(string|number)[]} */ - this.removedModules = undefined; + callback(); + }); } -} - -module.exports = HotUpdateChunk; - -/***/ }), + 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(); + } + } -/***/ 66062: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Callback} callback signals when the seal method is finishes + * @returns {void} + */ + seal(callback) { + this.hooks.seal.call(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); -const Template = __webpack_require__(96066); -const HotUpdateChunk = __webpack_require__(26782); -const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); + GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); + GraphHelpers.connectChunkAndModule(chunk, module); -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"]) - }; - } + chunk.entryModule = module; + chunk.name = name; - 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 + this.assignDepth(module); + } + buildChunkGraph( + this, + /** @type {Entrypoint[]} */ (this.chunkGroups.slice()) ); - return source; - } + this.sortModules(this.modules); + this.hooks.afterChunks.call(this.chunks); - updateHash(hash) { - hash.update("HotUpdateChunkTemplate"); - hash.update("1"); - this.hooks.hash.call(hash); - } -}; + 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); -/***/ 41364: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return callback(err); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(69667); + const shouldRecord = this.hooks.shouldRecord.call() !== false; -/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ + 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); -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] - }; - } + this.sortItemsWithModuleIds(); - validateOptions(schema, options, "IgnorePlugin"); - this.options = options; + 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); - /** @private @type {Function} */ - this.checkIgnore = this.checkIgnore.bind(this); - } + this.sortItemsWithChunkIds(); - /** - * 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 (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } - 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; + this.hooks.beforeHash.call(); + this.createHash(); + this.hooks.afterHash.call(); + + if (shouldRecord) { + this.hooks.recordHash.call(this.records); } - } - 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; + 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); } - } - return result; + 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 {Compiler} compiler Webpack Compiler + * @param {Module[]} modules the modules array on compilation to perform the sort for * @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); - }); + 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); } -} - -module.exports = IgnorePlugin; - - -/***/ }), - -/***/ 98509: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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 { RawSource, ReplaceSource } = __webpack_require__(53665); + const warnings = d.getWarnings(); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; -// TODO: clean up this file -// replace with newer constructs + 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]; -// TODO: remove DependencyVariables and replace them with something better + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + } + } + } -class JavascriptGenerator { - generate(module, dependencyTemplates, runtimeTemplate) { - const originalSource = module.originalSource(); - if (!originalSource) { - return new RawSource("throw new Error('No source available');"); + this.reportDependencyErrorsAndWarnings(module, block.blocks); } + } - const source = new ReplaceSource(originalSource); + /** + * @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); - this.sourceBlock( - module, - module, - [], - dependencyTemplates, - source, - runtimeTemplate - ); + GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); - return source; + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; } - sourceBlock( - module, - block, - availableVars, - dependencyTemplates, - source, - runtimeTemplate - ) { - for (const dependency of block.dependencies) { - this.sourceDependency( - dependency, - dependencyTemplates, - source, - runtimeTemplate - ); + /** + * 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; /** - * 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. + * @param {Module} module module for processeing + * @returns {void} */ - const vars = block.variables.reduce((result, value) => { - const variable = this.sourceVariables( - value, - availableVars, - dependencyTemplates, - runtimeTemplate - ); + const enqueueJob = module => { + const d = module.depth; + if (typeof d === "number" && d <= depth) return; + queue.add(module); + module.depth = depth; + }; - if (variable) { - result.push(variable); + /** + * @param {Dependency} dependency dependency to assign depth to + * @returns {void} + */ + const assignDepthToDependency = dependency => { + if (dependency.module) { + enqueueJob(dependency.module); } - - 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. + * @param {DependenciesBlock} block block to assign depth to + * @returns {void} */ - 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) - ); - } - ); + const assignDepthToDependencyBlock = block => { + if (block.variables) { + iterationBlockVariable(block.variables, assignDepthToDependency); + } - // and all the ends - const functionWrapperEnds = injectionVariableChunks.map(variableChunk => { - return this.variableInjectionFunctionWrapperEndCode( - module, - variableChunk.map(variable => variable.expression), - block - ); - }); + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, assignDepthToDependency); + } - // join them to one big string - const varStartCode = functionWrapperStarts.join(""); + if (block.blocks) { + iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); + } + }; - // reverse the ends first before joining them, as the last added must be the inner most - const varEndCode = functionWrapperEnds.reverse().join(""); + for (module of queue) { + queue.delete(module); + depth = module.depth; - // 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); - } + depth++; + assignDepthToDependencyBlock(module); } + } - for (const childBlock of block.blocks) { - this.sourceBlock( - module, - childBlock, - availableVars.concat(vars), - dependencyTemplates, - source, - runtimeTemplate - ); - } + /** + * @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); } - sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { - const template = dependencyTemplates.get(dependency.constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name + /** + * + * @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) ); } - template.apply(dependency, source, runtimeTemplate, dependencyTemplates); - } - sourceVariables( - variable, - availableVars, - dependencyTemplates, - runtimeTemplate - ) { - const name = variable.name; - const expr = variable.expressionSource( - dependencyTemplates, - runtimeTemplate - ); + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } - if ( - availableVars.some( - v => v.name === name && v.expression.source() === expr.source() - ) - ) { - return; + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); } - return { - name: name, - expression: expr - }; } - /* - * creates the start part of a IIFE around the module to inject a variable name - * (function(…){ <- this part - * }.call(…)) + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} */ - variableInjectionFunctionWrapperStartCode(varNames) { - const args = varNames.join(", "); - return `/* WEBPACK VAR INJECTION */(function(${args}) {`; - } - - contextArgument(module, block) { - if (this === block) { - return module.exportsArgument; + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons()) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk)) { + if (module.removeChunk(chunk)) { + this.removeChunkFromDependencies(module, chunk); + } } - return "this"; } - /* - * creates the end part of a IIFE around the module to inject a variable name - * (function(…){ - * }.call(…)) <- this part + /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} */ - variableInjectionFunctionWrapperEndCode(module, varExpressions, block) { - const firstParam = this.contextArgument(module, block); - const furtherParams = varExpressions.map(e => e.source()).join(", "); - return `}.call(${firstParam}, ${furtherParams}))`; + 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); + } } - 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 - ); + applyModuleIds() { + const unusedIds = []; + let nextFreeModuleId = 0; + const usedIds = new Set(); + if (this.usedModuleIds) { + for (const id of this.usedModuleIds) { + usedIds.add(id); + } + } - if (variableNameAlreadyExists) { - // start new chunk with current variable - chunks.push([variable]); - } else { - // else add it to current chunk - current.push(variable); + const modules1 = this.modules; + for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { + const module1 = modules1[indexModule1]; + if (module1.id !== null) { + usedIds.add(module1.id); } - return chunks; - }, startState); - } -} + } -module.exports = JavascriptGenerator; + 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); -/***/ 10339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + while (lengthFreeModules--) { + if (!usedIds.has(lengthFreeModules)) { + unusedIds.push(lengthFreeModules); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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(); -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); + // Get used ids from usedChunkIds property (i. e. from records) + if (this.usedChunkIds) { + for (const id of this.usedChunkIds) { + if (typeof id !== "number") { + continue; + } -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; + usedIds.add(id); + } + } - const filenameTemplate = - chunk.filenameTemplate || outputOptions.filename; + // 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; - const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); + if (typeof usedIdValue !== "number") { + continue; + } - 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; + usedIds.add(usedIdValue); + } - result.push({ - render: () => - this.renderJavascript( - compilation.chunkTemplate, - chunk, - moduleTemplates.javascript, - dependencyTemplates - ), - filenameTemplate, - pathOptions: { - chunk, - contentHashType: "javascript" - }, - identifier: `chunk${chunk.id}`, - hash: chunk.hash - }); + // Calculate maximum assigned chunk id + let nextFreeChunkId = -1; + for (const id of usedIds) { + nextFreeChunkId = Math.max(nextFreeChunkId, id); + } + nextFreeChunkId++; - 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); - }); + // 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); + } } - ); - } + } - 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); + // 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]; + } } - chunk.rendered = true; - return new ConcatSource(source, ";"); } -} - -module.exports = JavascriptModulesPlugin; + sortItemsWithModuleIds() { + this.modules.sort(byIdOrIdentifier); -/***/ }), + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + modules[indexModule].sortItems(false); + } -/***/ 72806: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { ConcatSource, RawSource } = __webpack_require__(53665); + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } -const stringifySafe = data => { - const stringified = JSON.stringify(data); - if (!stringified) { - return undefined; // Invalid JSON + chunks.sort((a, b) => a.compareTo(b)); } - 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 - }) - ); + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); } - let finalJson; - if ( - Array.isArray(module.buildMeta.providedExports) && - !module.isUsed("default") + + this.chunks.sort(byId); + + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ ) { - // 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; + this.modules[indexModule].sortItems(true); } - // 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; + 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); + } -/***/ 2859: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + summarizeDependencies() { + this.fileDependencies = new SortableSet(this.compilationDependencies); + this.contextDependencies = new SortableSet(); + this.missingDependencies = new SortableSet(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); + } -const JsonParser = __webpack_require__(5807); -const JsonGenerator = __webpack_require__(72806); + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + const module = this.modules[indexModule]; -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(); - }); + 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(); } -} - -module.exports = JsonModulesPlugin; - - -/***/ }), - -/***/ 5807: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const parseJson = __webpack_require__(48335); -const JsonExportsDependency = __webpack_require__(54396); + 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); + } -class JsonParser { - constructor(options) { - this.options = options; + /** + * @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); } - 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))); + /** + * @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; } - state.module.addDependency(new JsonExportsDependency(["default"])); - return state; + this.assets[file] = source; + this.assetsInfo.set(file, assetInfo); } -} -module.exports = JsonParser; + /** + * @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) || {} + }; + } -/***/ 30735: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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) + ); + } + } + } -const path = __webpack_require__(85622); -const asyncLib = __webpack_require__(36386); -const SingleEntryDependency = __webpack_require__(84828); + /** + * @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); + } -class LibManifestPlugin { - constructor(options) { - this.options = options; + /** + * @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); } - 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 - ); - } + /** + * 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 ); } -} -module.exports = LibManifestPlugin; - - -/***/ }), - -/***/ 65237: -/***/ (function(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(""); -}; + checkConstraints() { + /** @type {Set} */ + const usedIds = new Set(); -/** - * @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} : {}`; + 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}`); } - 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; - } + usedIds.add(moduleId); + } - /** - * @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 + 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}` ); } - 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: -/***/ (function(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]; - } - } - } - ); - }); + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } } } -module.exports = LoaderOptionsPlugin; - - -/***/ }), - -/***/ 95154: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -class LoaderTargetPlugin { - constructor(target) { - this.target = target; - } +// 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" +); - apply(compiler) { - compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { - compilation.hooks.normalModuleLoader.tap( - "LoaderTargetPlugin", - loaderContext => { - loaderContext.target = this.target; - } - ); - }); - } -} +// 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 = LoaderTargetPlugin; +module.exports = Compilation; /***/ }), -/***/ 43626: +/***/ 58705: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78269,1155 +74111,758 @@ module.exports = LoaderTargetPlugin; */ -const { - ConcatSource, - OriginalSource, - PrefixSource, - RawSource -} = __webpack_require__(53665); +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, - SyncWaterfallHook, SyncHook, - SyncBailHook + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook } = __webpack_require__(56758); -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} */ +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} 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 + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + * @property {Set} compilationDependencies */ -// 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) { +class Compiler extends Tapable { + constructor(context) { 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"]), + /** @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"]), - // TODO this should be moved somewhere else - // It's weird here - hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) + /** @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"]) }; - 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; + // 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; } - ); - 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;`); + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {string} */ + this.outputPath = ""; - 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("};"); + this.outputFileSystem = null; + this.inputFileSystem = null; - 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("};"); + /** @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(); - 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("};"); + this.infrastructureLogger = undefined; - 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("};"); + // 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.') + } + }; - buf.push(""); - buf.push("// Object.prototype.hasOwnProperty.call"); - buf.push( - `${this.requireFn}.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` - ); + /** @type {WebpackOptions} */ + this.options = /** @type {WebpackOptions} */ ({}); - 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.context = context; - this.requireFn = "__webpack_require__"; - } + this.requestShortener = new RequestShortener(context); - /** - * - * @param {RenderManifestOptions} options render manifest options - * @returns {TODO[]} returns render manifest - */ - getRenderManifest(options) { - const result = []; + /** @type {boolean} */ + this.running = false; - this.hooks.renderManifest.call(result, options); + /** @type {boolean} */ + this.watchMode = false; - return result; + /** @private @type {WeakMap }>} */ + this._assetEmittingSourceCache = new WeakMap(); + /** @private @type {Map} */ + this._assetEmittingWrittenFiles = new Map(); } /** - * 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 + * @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 */ - 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;"); + getInfrastructureLogger(name) { + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called without a name" + ); } - return buf; + 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); + } + } + }); } - /** - * @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 - ); - } + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); - /** - * - * @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 - ); + this.running = true; + this.watchMode = true; + this.fileTimestamps = new Map(); + this.contextTimestamps = new Map(); + this.removedFiles = new Set(); + return new Watching(this, watchOptions, handler); } - /** - * - * @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 - ); - } + run(callback) { + if (this.running) return callback(new ConcurrentCompilationError()); - /** - * - * @param {object} options get public path options - * @returns {string} hook call - */ - getPublicPath(options) { - return this.hooks.assetPath.call( - this.outputOptions.publicPath || "", - options - ); - } + const finalCallback = (err, stats) => { + this.running = false; - getAssetPath(path, options) { - return this.hooks.assetPath.call(path, options); - } + if (err) { + this.hooks.failed.call(err); + } - 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 }; - } + if (callback !== undefined) return callback(err, stats); + }; - /** - * 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); - } + const startTime = Date.now(); - /** - * 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); - } - } + this.running = true; - useChunkHash(chunk) { - const paths = this.hooks.globalHashPaths.call([]); - return !this.hooks.globalHash.call(chunk, paths); - } -}; + 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); -/***/ 50332: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -module.exports = __webpack_require__(32327); + 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); -/***/ 75993: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + }); + }); + }); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); -const util = __webpack_require__(31669); + this.readRecords(err => { + if (err) return finalCallback(err); -const DependenciesBlock = __webpack_require__(16071); -const ModuleReason = __webpack_require__(44576); -const SortableSet = __webpack_require__(50071); -const Template = __webpack_require__(96066); + this.compile(onCompiled); + }); + }); + }); + } -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/createHash").Hash} Hash */ + runAsChild(callback) { + this.compile((err, compilation) => { + if (err) return callback(err); -const EMPTY_RESOLVE_OPTIONS = {}; + this.parentCompilation.children.push(compilation); + for (const { name, source, info } of compilation.getAssets()) { + this.parentCompilation.emitAsset(name, source, info); + } -let debugId = 1000; + const entries = Array.from( + compilation.entrypoints.values(), + ep => ep.chunks + ).reduce((array, chunks) => { + return array.concat(chunks); + }, []); -const sortById = (a, b) => { - return a.id - b.id; -}; + return callback(null, entries, compilation); + }); + } -const sortByDebugId = (a, b) => { - return a.debugId - b.debugId; -}; + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); + } + } -/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + emitAssets(compilation, callback) { + let outputPath; + const emitFiles = err => { + if (err) return callback(err); -class Module extends DependenciesBlock { - constructor(type, context = null) { - super(); - /** @type {string} */ - this.type = type; - /** @type {string} */ - this.context = context; + asyncLib.forEachLimit( + compilation.getAssets(), + 15, + ({ name: file, source }, callback) => { + let targetFile = file; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + } - // Unique Id - /** @type {number} */ - this.debugId = debugId++; + 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 + ); - // Hash - /** @type {string} */ - this.hash = undefined; - /** @type {string} */ - this.renderedHash = undefined; + // 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); + } - // Info from Factory - /** @type {TODO} */ - this.resolveOptions = EMPTY_RESOLVE_OPTIONS; - /** @type {object} */ - this.factoryMeta = {}; + // 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) - // Info from Build - /** @type {WebpackError[]} */ - this.warnings = []; - /** @type {WebpackError[]} */ - this.errors = []; - /** @type {object} */ - this.buildMeta = undefined; - /** @type {object} */ - this.buildInfo = undefined; + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: cacheEntry.sizeOnlySource.size() + }); - // Graph (per Compilation) - /** @type {ModuleReason[]} */ - this.reasons = []; - /** @type {SortableSet} */ - this._chunks = new SortableSet(undefined, sortById); + return callback(); + } + } - // 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; + // TODO webpack 5: if info.immutable check if file already exists in output + // skip emitting if it's already there - // Info from Optimization (per Compilation) - /** @type {null | boolean} */ - this.used = null; - /** @type {false | true | string[]} */ - this.usedExports = null; - /** @type {(string | OptimizationBailoutFunction)[]} */ - this.optimizationBailout = []; + // 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"); + } + } - // delayed operations - /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ - this._rewriteChunkInReasons = undefined; + // 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 + }); - /** @type {boolean} */ - this.useSourceMap = false; + // Write the file to output file system + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); - // info from build - this._source = null; - } + // information marker that the asset has been emitted + compilation.emittedAssets.add(file); - get exportsArgument() { - return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; - } + // 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(); - get moduleArgument() { - return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; - } + if (!Buffer.isBuffer(content)) { + content = Buffer.from(content, "utf8"); + } - disconnect() { - this.hash = undefined; - this.renderedHash = undefined; + source.existsAt = targetPath; + source.emitted = true; + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); + this.hooks.assetEmitted.callAsync(file, content, callback); + }); + } + }; - this.reasons.length = 0; - this._rewriteChunkInReasons = undefined; - this._chunks.clear(); + 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.id = null; - this.index = null; - this.index2 = null; - this.depth = null; - this.issuer = null; - this.profile = undefined; - this.prefetched = false; - this.built = false; + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); - this.used = null; - this.usedExports = null; - this.optimizationBailout.length = 0; - super.disconnect(); - } + return callback(); + }); + } + ); + }; - unseal() { - this.id = null; - this.index = null; - this.index2 = null; - this.depth = null; - this._chunks.clear(); - super.unseal(); + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath); + this.outputFileSystem.mkdirp(outputPath, emitFiles); + }); } - setChunks(chunks) { - this._chunks = new SortableSet(chunks, sortById); - } + 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); + } - addChunk(chunk) { - if (this._chunks.has(chunk)) return false; - this._chunks.add(chunk); - return true; - } + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify(this.records, undefined, 2), + callback + ); + }; - removeChunk(chunk) { - if (this._chunks.delete(chunk)) { - chunk.removeModule(this); - return true; + if (!recordsOutputPathDirectory) { + return writeFile(); } - return false; + this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); } - isInChunk(chunk) { - return this._chunks.has(chunk); - } - - isEntryModule() { - for (const chunk of this._chunks) { - if (chunk.entryModule === this) return true; + readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); } - 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; - } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); - get chunksIterable() { - return this._chunks; - } + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); - 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; - } - } + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } - addReason(module, dependency, explanation) { - this.reasons.push(new ModuleReason(module, dependency, explanation)); + return callback(); + }); + }); } - 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; + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context); + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); } } - return false; - } - - hasReasonForChunk(chunk) { - if (this._rewriteChunkInReasons) { - for (const operation of this._rewriteChunkInReasons) { - this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + 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(); + } } - 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; - } + 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; - rewriteChunkInReasons(oldChunk, newChunks) { - // This is expensive. Delay operation until we really need the data - if (this._rewriteChunkInReasons === undefined) { - this._rewriteChunkInReasons = []; + const relativeCompilerName = makePathsRelative(this.context, compilerName); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; } - this._rewriteChunkInReasons.push({ - oldChunk, - newChunks - }); - } - - _doRewriteChunkInReasons(oldChunk, newChunks) { - for (let i = 0; i < this.reasons.length; i++) { - this.reasons[i].rewriteChunks(oldChunk, newChunks); + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); } - } - - /** - * @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); - } + 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]; } - return exportName; - } - - isProvided(exportName) { - if (!Array.isArray(this.buildMeta.providedExports)) return null; - return this.buildMeta.providedExports.includes(exportName); - } + childCompiler.parentCompilation = compilation; - toString() { - return `Module[${this.id || this.debugId}]`; - } + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); - needRebuild(fileTimestamps, contextTimestamps) { - return true; + return childCompiler; } - /** - * @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); + isChild() { + return !!this.parentCompilation; } - 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(); - } + createCompilation() { + return new Compilation(this); } - unbuild() { - this.dependencies.length = 0; - this.blocks.length = 0; - this.variables.length = 0; - this.buildMeta = undefined; - this.buildInfo = undefined; - this.disconnect(); + 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; } - get arguments() { - throw new Error("Module.arguments was removed, there is no replacement."); + createNormalModuleFactory() { + const normalModuleFactory = new NormalModuleFactory( + this.options.context, + this.resolverFactory, + this.options.module || {} + ); + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; } - set arguments(value) { - throw new Error("Module.arguments was removed, there is no replacement."); + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; } -} - -// 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"); + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory(), + compilationDependencies: new Set() + }; + return params; } -}); - -// 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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.hooks.compile.call(params); + const compilation = this.newCompilation(params); -const WebpackError = __webpack_require__(97391); -const { cutOffLoaderExecution } = __webpack_require__(80140); + this.hooks.make.callAsync(compilation, err => { + if (err) return callback(err); -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; - } + compilation.finish(err => { + if (err) return callback(err); - super(message); + compilation.seal(err => { + if (err) return callback(err); - this.name = "ModuleBuildError"; - this.details = details; - this.module = module; - this.error = err; + this.hooks.afterCompile.callAsync(compilation, err => { + if (err) return callback(err); - Error.captureStackTrace(this, this.constructor); + return callback(null, compilation); + }); + }); + }); + }); + }); } } -module.exports = ModuleBuildError; - +module.exports = Compiler; -/***/ }), +class SizeOnlySource extends Source { + constructor(size) { + super(); + this._size = size; + } -/***/ 14953: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _error() { + return new Error( + "Content and Map of this Source is no longer available (only size() is supported)" + ); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + size() { + return this._size; + } + /** + * @param {any} options options + * @returns {string} the source + */ + source(options) { + throw this._error(); + } -const WebpackError = __webpack_require__(97391); + node() { + throw this._error(); + } -/** @typedef {import("./Module")} Module */ + listMap() { + throw this._error(); + } -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); + map() { + throw this._error(); + } - 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; + listNode() { + throw this._error(); + } - Error.captureStackTrace(this, this.constructor); + updateHash() { + throw this._error(); } } -module.exports = ModuleDependencyError; - /***/ }), -/***/ 59136: +/***/ 18933: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Maksim Nazarjev @acupofspirt */ const WebpackError = __webpack_require__(97391); -module.exports = class ModuleDependencyWarning extends WebpackError { - constructor(module, err, loc) { - super(err.message); +module.exports = class ConcurrentCompilationError extends WebpackError { + constructor() { + super(); - 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; + 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); } @@ -79426,7 +74871,7 @@ module.exports = class ModuleDependencyWarning extends WebpackError { /***/ }), -/***/ 82528: +/***/ 84072: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79435,43 +74880,391 @@ module.exports = class ModuleDependencyWarning extends WebpackError { Author Tobias Koppers @sokra */ +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); +const ParserHelpers = __webpack_require__(23999); -const WebpackError = __webpack_require__(97391); -const { cleanUp } = __webpack_require__(80140); +const getQuery = request => { + const i = request.indexOf("?"); + return i !== -1 ? request.substr(i) : ""; +}; -class ModuleError extends WebpackError { - constructor(module, err, { from = null } = {}) { - let message = "Module Error"; - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; +const collectDeclaration = (declarations, pattern) => { + const stack = [pattern]; + while (stack.length > 0) { + const node = stack.pop(); + switch (node.type) { + case "Identifier": + declarations.add(node.name); + break; + case "ArrayPattern": + for (const element of node.elements) { + if (element) { + stack.push(element); + } + } + break; + case "AssignmentPattern": + stack.push(node.left); + break; + case "ObjectPattern": + for (const property of node.properties) { + stack.push(property.value); + } + break; + case "RestElement": + stack.push(node.argument); + break; } - if (err && typeof err === "object" && err.message) { - message += err.message; - } else if (err) { - message += err; + } +}; + +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; } - 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; + } + return Array.from(declarations); +}; - Error.captureStackTrace(this, this.constructor); +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 = ModuleError; +module.exports = ConstPlugin; /***/ }), -/***/ 71474: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 10706: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -79479,790 +75272,878 @@ module.exports = ModuleError; 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; -const createHash = __webpack_require__(15660); +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ -const ModuleFilenameHelpers = exports; +/** + * @callback ResolveDependenciesCallback + * @param {Error=} err + * @param {ContextElementDependency[]} dependencies + */ -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; +/** + * @callback ResolveDependencies + * @param {TODO} fs + * @param {TODO} options + * @param {ResolveDependenciesCallback} callback + */ -const getAfter = (str, token) => { - const idx = str.indexOf(token); - return idx < 0 ? "" : str.substr(idx); -}; +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 = ""; + } -const getBefore = (str, token) => { - const idx = str.lastIndexOf(token); - return idx < 0 ? "" : str.substr(0, idx); -}; + super("javascript/dynamic", resource); -const getHash = str => { - const hash = createHash("md4"); - hash.update(str); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, 4); -}; + // Info from Factory + this.resolveDependencies = resolveDependencies; + this.options = Object.assign({}, options, { + resource: resource, + resourceQuery: resourceQuery + }); + if (options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; + } -const asRegExp = test => { - if (typeof test === "string") { - test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + // 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(); } - return test; -}; -ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { - const opts = Object.assign( - { - namespace: "", - moduleFilenameTemplate: "" - }, - typeof options === "object" - ? options - : { - moduleFilenameTemplate: options - } - ); + updateCacheModule(module) { + this.resolveDependencies = module.resolveDependencies; + this.options = module.options; + this.resolveOptions = module.resolveOptions; + } - 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 - }); + prettyRegExp(regexString) { + // remove the "/" at the front and the beginning + // "/foo/" -> "foo" + return regexString.substring(1, regexString.length - 1); } - 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; + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; } - }); -}; - -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 (this.options.mode) { + identifier += ` ${this.options.mode}`; } - } - if (obj.include) { - if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { - return false; + if (!this.options.recursive) { + identifier += " nonrecursive"; } - } - if (obj.exclude) { - if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { - return false; + 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 true; -}; - - -/***/ }), - -/***/ 71638: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(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); + return identifier; } -} - -module.exports = ModuleNotFoundError; - - -/***/ }), - -/***/ 62500: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + identifier() { + return this._identifier; + } -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"; + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context); + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; } - 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(""); + 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]}`; } - loc = err.loc; - } else { - message += "\n" + err.stack; + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; } - super(message); - - this.name = "ModuleParseError"; - this.module = module; - this.loc = loc; - this.error = err; - - Error.captureStackTrace(this, this.constructor); + return identifier; } -} -module.exports = ModuleParseError; + 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; + } -/***/ 44576: -/***/ (function(module) { + return ts >= this.buildInfo.builtTime; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + } -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Dependency")} Dependency */ + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } -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; + 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(); + }); } - 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; + 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)); } - 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(); - } + getFakeMap(dependencies) { + if (!this.options.namespaceObject) { + return 9; } - if (this._chunks.has(oldChunk)) { - this._chunks.delete(oldChunk); - for (let i = 0; i < newChunks.length; i++) { - this._chunks.add(newChunks[i]); - } + // 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; } -} - -module.exports = ModuleReason; + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; + } -/***/ }), - -/***/ 75100: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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})`; + } -const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); + getSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Module")} Module */ + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -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); +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); -/***/ }), - -/***/ 6372: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +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); -const WebpackError = __webpack_require__(97391); -const { cleanUp } = __webpack_require__(80140); + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -class ModuleWarning extends WebpackError { - constructor(module, warning, { from = null } = {}) { - let message = "Module Warning"; - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; +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; } - if (warning && typeof warning === "object" && warning.message) { - message += warning.message; - } else if (warning) { - message += warning; + ${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; } - 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); - } + return map[req]; + }); } +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } -module.exports = ModuleWarning; - - -/***/ }), - -/***/ 10238: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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)} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +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__"; -const { Tapable, SyncHook, MultiHook } = __webpack_require__(56758); -const asyncLib = __webpack_require__(36386); -const MultiWatching = __webpack_require__(66624); -const MultiStats = __webpack_require__(55144); -const ConcurrentCompilationError = __webpack_require__(18933); + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -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]; - }); +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; } - 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++; + 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; } - compilerStats[compilerIndex] = stats; - if (doneCompilers === this.compilers.length) { - this.hooks.done.call(new MultiStats(compilerStats)); + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; } - }); - // eslint-disable-next-line no-loop-func - compiler.hooks.invalid.tap("MultiCompiler", () => { - if (compilerDone) { - compilerDone = false; - doneCompilers--; + 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; } - this.running = false; + + ${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; + }); } - 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(/[/\\][^/\\]*$/, ""); - } - } + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(function() { + ${returnModuleObject} + }); +}`; - if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; - return commonPath; + 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;`; } - get inputFileSystem() { - throw new Error("Cannot read inputFileSystem of a MultiCompiler"); + 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)};`; } - get outputFileSystem() { - throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + 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)};`; } - set inputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.inputFileSystem = value; + 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); } - set outputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.outputFileSystem = value; + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); } + return new RawSource(sourceString); } - getInfrastructureLogger(name) { - return this.compilers[0].getInfrastructureLogger(name); + source(dependencyTemplates, runtimeTemplate) { + return this.getSource( + this.getSourceString(this.options.mode, runtimeTemplate) + ); } - 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; - } + size() { + // base penalty + const initialSize = 160; - 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); + // 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); } +} - 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); - } +// 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" + ) +}); - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } +// 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" + ) +}); - const finalCallback = (err, stats) => { - this.running = false; +// 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" + ) +}); - if (callback !== undefined) { - return callback(err, stats); - } - }; +// 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" + ) +}); - 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)); - } - ); - } - } +// 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" + ) +}); - purgeInputFileSystem() { - for (const compiler of this.compilers) { - if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { - compiler.inputFileSystem.purge(); - } - } - } -}; +module.exports = ContextModule; /***/ }), -/***/ 98046: +/***/ 88239: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80272,211 +76153,267 @@ module.exports = class MultiCompiler extends Tapable { */ -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; - } +const asyncLib = __webpack_require__(36386); +const path = __webpack_require__(85622); - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "MultiEntryPlugin", - (compilation, { normalModuleFactory }) => { - const multiModuleFactory = new MultiModuleFactory(); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook +} = __webpack_require__(56758); +const ContextModule = __webpack_require__(20090); +const ContextElementDependency = __webpack_require__(89079); - compilation.dependencyFactories.set( - MultiEntryDependency, - multiModuleFactory - ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); - } - ); +/** @typedef {import("./Module")} Module */ - compiler.hooks.make.tapAsync( - "MultiEntryPlugin", - (compilation, callback) => { - const { context, entries, name } = this; +const EMPTY_RESOLVE_OPTIONS = {}; - const dep = MultiEntryPlugin.createDependency(entries, name); - compilation.addEntry(context, dep, name, callback); +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; } - /** - * @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 - ); - } -} + 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); -module.exports = MultiEntryPlugin; + // 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; + } -/***/ 4198: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const contextResolver = this.resolverFactory.get( + "context", + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + const loaderResolver = this.resolverFactory.get( + "loader", + EMPTY_RESOLVE_OPTIONS + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); -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); - } + // Ignored + if (!result) return callback(); - 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 + return callback( + null, + new ContextModule(result.resolveDependencies, result) + ); + } + ); + } ); - str.push(content); } - str.push(";\n"); - idx++; - } - return new RawSource(str.join("")); + ); } -} - -module.exports = MultiModule; + 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); -/***/ 24005: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); -const { Tapable } = __webpack_require__(56758); -const MultiModule = __webpack_require__(4198); + if (!result) return callback(null, []); -module.exports = class MultiModuleFactory extends Tapable { - constructor() { - super(); - this.hooks = {}; - } + callback( + null, + result.filter(Boolean).reduce((a, i) => a.concat(i), []) + ); + } + ); + }); + }; - create(data, callback) { - const dependency = data.dependencies[0]; - callback( - null, - new MultiModule(data.context, dependency.dependencies, dependency.name) - ); + addDirectory(resource, callback); } }; /***/ }), -/***/ 55144: +/***/ 27295: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80486,97 +76423,138 @@ module.exports = class MultiModuleFactory extends Tapable { */ -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); - } +const path = __webpack_require__(85622); +const ContextElementDependency = __webpack_require__(89079); - hasWarnings() { - return this.stats - .map(stat => stat.hasWarnings()) - .reduce((a, b) => a || b, false); - } +class ContextReplacementPlugin { + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; - 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; + 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; } - 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); + 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; - return Stats.jsonToString(obj, useColors); + 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; + }); + }); } } -module.exports = MultiStats; +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; /***/ }), -/***/ 66624: +/***/ 97374: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80586,241 +76564,98 @@ module.exports = MultiStats; */ -const asyncLib = __webpack_require__(36386); - -class MultiWatching { - constructor(watchings, compiler) { - this.watchings = watchings; - this.compiler = compiler; - } +const ConstDependency = __webpack_require__(71101); +const BasicEvaluatedExpression = __webpack_require__(96770); +const ParserHelpers = __webpack_require__(23999); +const NullFactory = __webpack_require__(40438); - invalidate() { - for (const watching of this.watchings) { - watching.invalidate(); - } - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ +/** @typedef {CodeValuePrimitive|Record|RuntimeValue} CodeValue */ - suspend() { - for (const watching of this.watchings) { - watching.suspend(); - } +class RuntimeValue { + constructor(fn, fileDependencies) { + this.fn = fn; + this.fileDependencies = fileDependencies || []; } - resume() { - for (const watching of this.watchings) { - watching.resume(); + 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); + } } - } - 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); - } - } - ); + return this.fn({ module: parser.state.module }); } } -module.exports = MultiWatching; - - -/***/ }), - -/***/ 70419: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - +const stringifyObj = (obj, parser) => { + return ( + "Object({" + + Object.keys(obj) + .map(key => { + const code = obj[key]; + return JSON.stringify(key) + ":" + toCode(code, parser); + }) + .join(",") + + "})" + ); +}; -class NamedChunksPlugin { - static defaultNameResolver(chunk) { - return chunk.name || null; +/** + * 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"; } - - constructor(nameResolver) { - this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; + if (code === undefined) { + return "undefined"; } - - 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); - } - } - }); - }); + if (code instanceof RuntimeValue) { + return toCode(code.exec(parser), parser); } -} - -module.exports = NamedChunksPlugin; - - -/***/ }), - -/***/ 86707: -/***/ (function(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()) - )}`; - } - } - } - }); - }); + if (code instanceof RegExp && code.toString) { + return code.toString(); } -} - -module.exports = NamedModulesPlugin; - - -/***/ }), - -/***/ 22615: -/***/ (function(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; - }); - }); + if (typeof code === "function" && code.toString) { + return "(" + code.toString() + ")"; } -} - -module.exports = NoEmitOnErrorsPlugin; - - -/***/ }), - -/***/ 45759: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(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); + 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; + } -/***/ }), - -/***/ 28386: -/***/ (function(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; + static runtimeValue(fn, fileDependencies) { + return new RuntimeValue(fn, fileDependencies); } + /** + * Apply the plugin + * @param {Compiler} compiler Webpack compiler + * @returns {void} + */ apply(compiler) { - const options = this.options; + const definitions = this.definitions; compiler.hooks.compilation.tap( - "NodeStuffPlugin", + "DefinePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( @@ -80828,101 +76663,195 @@ class NodeStuffPlugin { new ConstDependency.Template() ); - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; - - let localOptions = options; - if (parserOptions.node) { - localOptions = Object.assign({}, localOptions, parserOptions.node); - } + /** + * 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); + }); + }; - const setConstant = (expressionName, value) => { - parser.hooks.expression - .for(expressionName) - .tap("NodeStuffPlugin", () => { - parser.state.current.addVariable( - expressionName, - JSON.stringify(value) - ); - return true; - }); + /** + * 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); + }); }; - const setModuleConstant = (expressionName, fn) => { - parser.hooks.expression - .for(expressionName) - .tap("NodeStuffPlugin", () => { - parser.state.current.addVariable( - expressionName, - JSON.stringify(fn(parser.state.module)) - ); - return true; + /** + * 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); + } }); - }; - 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.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("__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) + .for(key) + .tap("DefinePlugin", expr => + new BasicEvaluatedExpression().setTruthy().setRange(expr.range) ); - } - parser.hooks.evaluateIdentifier - .for("__dirname") - .tap("NodeStuffPlugin", expr => { - if (!parser.state.module) return; - return ParserHelpers.evaluateToString( - parser.state.module.context + 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); - }); - } - parser.hooks.expression - .for("require.extensions") - .tap( - "NodeStuffPlugin", - ParserHelpers.expressionIsUnsupported( + } else { + return ParserHelpers.toConstantDependency( + parser, + strCode + )(expr); + } + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.toConstantDependency( parser, - "require.extensions is not supported by webpack. Use a loader instead." - ) - ); + JSON.stringify("object") + )(expr); + }); + }; + + walkDefinitions(definitions, ""); }; normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("NodeStuffPlugin", handler); + .tap("DefinePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("NodeStuffPlugin", handler); + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("DefinePlugin", handler); } ); } } -module.exports = NodeStuffPlugin; +module.exports = DefinePlugin; /***/ }), -/***/ 25963: +/***/ 42173: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80932,1123 +76861,661 @@ module.exports = NodeStuffPlugin; */ -const NativeModule = __webpack_require__(32282); - -const { - CachedSource, - LineToLineMappedSource, - OriginalSource, - RawSource, - SourceMapSource -} = __webpack_require__(53665); -const { getContext, runLoaders } = __webpack_require__(73278); +const { OriginalSource, RawSource } = __webpack_require__(53665); -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; +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 */ -const asString = buf => { - if (Buffer.isBuffer(buf)) { - return buf.toString("utf-8"); +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; } - return buf; -}; -const asBuffer = str => { - if (!Buffer.isBuffer(str)) { - return Buffer.from(str, "utf-8"); + libIdent(options) { + return typeof this.originalRequest === "string" + ? this.originalRequest + : this.originalRequest.libIdent(options); } - return str; -}; -class NonErrorEmittedError extends WebpackError { - constructor(error) { - super(); + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; + } - this.name = "NonErrorEmittedError"; - this.message = "(Emitted value instead of an instance of Error) " + error; + readableIdentifier() { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; + } - Error.captureStackTrace(this, this.constructor); + needRebuild() { + return false; } -} -/** - * @typedef {Object} CachedSourceEntry - * @property {TODO} source the generated source - * @property {string} hash the hash value - */ + 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(); + } -class NormalModule extends Module { - constructor({ - type, - request, - userRequest, - rawRequest, - loaders, - resource, - matchResource, - parser, - generator, - resolveOptions - }) { - super(type, getContext(resource)); + source(depTemplates, runtime) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = dep.module; + let str; - // 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; + if (!sourceModule) { + str = WebpackMissingModule.moduleCode(this.sourceRequest); + } else { + str = `module.exports = (${runtime.moduleExports({ + module: sourceModule, + request: dep.request + })})`; - // Info from Build - this.error = null; - this._source = null; - this._sourceSize = null; - this._buildHash = ""; - this.buildTimestamp = undefined; - /** @private @type {Map} */ - this._cachedSources = new Map(); + switch (this.type) { + case "require": + str += `(${JSON.stringify(this.request)})`; + break; + case "object": + str += `[${JSON.stringify(this.request)}]`; + break; + } - // Options for the NormalModule set by plugins - // TODO refactor this -> options object filled from Factory - this.useSourceMap = false; - this.lineToLine = false; + str += ";"; + } - // Cache - this._lastSuccessfulBuildMeta = {}; + if (this.useSourceMap) { + return new OriginalSource(str, this.identifier()); + } else { + return new RawSource(str); + } } - identifier() { - return this.request; + size() { + return 42; } - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.userRequest); + /** + * @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); } +} - libIdent(options) { - return contextify(options.context, this.userRequest); - } +module.exports = DelegatedModule; - 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); - } +/***/ 81002: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (typeof sourceMap === "string") { - return new OriginalSource(content, sourceMap); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return new SourceMapSource(content, name, sourceMap); + +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" + ]; } - 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); + 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); } - 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); - }); - }); + ); + } 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 + ); + } } - }; - }, - emitFile: (name, content, sourceMap, assetInfo) => { - if (!this.buildInfo.assets) { - this.buildInfo.assets = Object.create(null); - this.buildInfo.assetsInfo = new Map(); + return module; } - 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; } +} +module.exports = DelegatedModuleFactoryPlugin; - 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); - } +/***/ 16071: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return new OriginalSource(source, identifier); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - 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 - ); - } +const DependenciesBlockVariable = __webpack_require__(82904); - 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); - } +/** @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 */ - 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; +class DependenciesBlock { + constructor() { + /** @type {Dependency[]} */ + this.dependencies = []; + /** @type {AsyncDependenciesBlock[]} */ + this.blocks = []; + /** @type {DependenciesBlockVariable[]} */ + this.variables = []; + } - 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); - } + /** + * 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; + } - 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(); + /** + * @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) ); } - 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; + /** + * @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); } - applyNoParseRule(rule, content) { - // must start with "rule" if rule is a string - if (typeof rule === "string") { - return content.indexOf(rule) === 0; + /** + * @param {Dependency} dependency dependency being removed + * @returns {void} + */ + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); } + } - if (typeof rule === "function") { - return rule(content); - } - // we assume rule is a regexp - return rule.test(content); + /** + * @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); } - // 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; - } + 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(); + } - // 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); - } + unseal() { + for (const block of this.blocks) block.unseal(); + } - 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)) { + /** + * @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; } } - // no match found, so this module !should! be parsed + + 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; } - _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")); + sortItems() { + for (const block of this.blocks) block.sortItems(); } +} - 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(); - } +module.exports = DependenciesBlock; - // 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(); - }; +/***/ 82904: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); - } - }); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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 { RawSource, ReplaceSource } = __webpack_require__(53665); - const source = this.generator.generate( - this, - dependencyTemplates, - runtimeTemplate, - type - ); +/** @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 */ - const cachedSource = new CachedSource(source); - this._cachedSources.set(type, { - source: cachedSource, - hash: hashDigest - }); - return cachedSource; +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 || []; } - originalSource() { - return this._source; + /** + * @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); + } } - 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; + /** + * @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); } - // elsewise -> no rebuild needed - return false; + return source; } - size() { - if (this._sourceSize === null) { - this._sourceSize = this._source ? this._source.size() : -1; + disconnect() { + for (const d of this.dependencies) { + d.disconnect(); } - return this._sourceSize; } - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - hash.update(this._buildHash); - super.updateHash(hash); + hasDependencies(filter) { + if (filter) { + return this.dependencies.some(filter); + } + return this.dependencies.length > 0; } } -module.exports = NormalModule; +module.exports = DependenciesBlockVariable; /***/ }), -/***/ 22298: +/***/ 57282: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + 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 + */ -const path = __webpack_require__(85622); -const asyncLib = __webpack_require__(36386); -const { - Tapable, - AsyncSeriesWaterfallHook, - SyncWaterfallHook, - SyncBailHook, - SyncHook, - HookMap -} = __webpack_require__(56758); -const NormalModule = __webpack_require__(25963); -const RawModule = __webpack_require__(82353); -const RuleSet = __webpack_require__(84247); -const { cachedCleverMerge } = __webpack_require__(67916); +/** @typedef {Object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ -const EMPTY_RESOLVE_OPTIONS = {}; +/** @typedef {Object} SynteticDependencyLocation + * @property {string} name + * @property {number=} index + */ -const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; +/** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ -const loaderToIdent = data => { - if (!data.options) { - return data.loader; - } - if (typeof data.options === "string") { - return data.loader + "?" + data.options; +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; } - if (typeof data.options !== "object") { - throw new Error("loader options must be string or object"); + + getResourceIdentifier() { + return null; } - if (data.ident) { - return data.loader + "??" + data.ident; + + // Returns the referenced module and export + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, true, this.weak); } - 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 - }; + // Returns the exported names + getExports() { + return null; } -}; -const dependencyCache = new WeakMap(); + getWarnings() { + return null; + } -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); + getErrors() { + return null; + } - // Ignored - if (!resolver) return callback(); + updateHash(hash) { + hash.update((this.module && this.module.id) + ""); + } - resolver(result, (err, data) => { - if (err) return callback(err); + disconnect() { + this.module = null; + } +} - // Ignored - if (!data) return callback(); +// 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" +); - // direct module - if (typeof data.source === "function") return callback(null, data); +module.exports = Dependency; - 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)")); - } +/***/ 6659: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - createdModule = new NormalModule(result); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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 DllEntryDependency = __webpack_require__(66279); +const SingleEntryDependency = __webpack_require__(84828); +const DllModuleFactory = __webpack_require__(62468); - const loaderResolver = this.getResolver("loader"); - const normalResolver = this.getResolver("normal", data.resolveOptions); +class DllEntryPlugin { + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } - 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 + 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 + ); + }); + } +} - 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); +module.exports = DllEntryPlugin; - 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); +/***/ 24803: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Ignored - if (!result) return callback(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - const factory = this.hooks.factory.call(null); - // Ignored - if (!factory) return callback(); +const { RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); - factory(result, (err, module) => { - if (err) return callback(err); +/** @typedef {import("./util/createHash").Hash} Hash */ - if (module && this.cachePredicate(module)) { - for (const d of dependencies) { - dependencyCache.set(d, module); - } - } +class DllModule extends Module { + constructor(context, dependencies, name, type) { + super("javascript/dynamic", context); - callback(null, module); - }); - } - ); + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this.type = type; } - 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); + identifier() { + return `dll ${this.name}`; + } - const optionsOnly = item.options - ? { - options: item.options - } - : undefined; - return callback( - null, - Object.assign({}, item, identToLoaderRequest(result), optionsOnly) - ); - } - ); - }, - callback - ); + readableIdentifier() { + return `dll ${this.name}`; } - 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)); + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); } - 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; + source() { + return new RawSource("module.exports = __webpack_require__;"); } - 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 - )); + needRebuild() { + return false; } - 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; + size() { + return 12; } - getResolver(type, resolveOptions) { - return this.resolverFactory.get( - type, - resolveOptions || EMPTY_RESOLVE_OPTIONS - ); + /** + * @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 = NormalModuleFactory; +module.exports = DllModule; /***/ }), -/***/ 73253: +/***/ 62468: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82058,95 +77525,92 @@ module.exports = NormalModuleFactory; */ -const path = __webpack_require__(85622); +const { Tapable } = __webpack_require__(56758); +const DllModule = __webpack_require__(24803); -class NormalModuleReplacementPlugin { - constructor(resourceRegExp, newResource) { - this.resourceRegExp = resourceRegExp; - this.newResource = newResource; +class DllModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; } - - 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; - }); - } + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new DllModule( + data.context, + dependency.dependencies, + dependency.name, + dependency.type + ) ); } } -module.exports = NormalModuleReplacementPlugin; +module.exports = DllModuleFactory; /***/ }), -/***/ 40438: -/***/ (function(module) { +/***/ 45255: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "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; + */ -/***/ }), +const DllEntryPlugin = __webpack_require__(6659); +const FlagAllModulesAsUsedPlugin = __webpack_require__(47163); +const LibManifestPlugin = __webpack_require__(30735); -/***/ 4428: -/***/ (function(module) { +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(7303); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options, "Dll Plugin"); + this.options = options; + } -class OptionsApply { - process(options, compiler) {} + 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 = OptionsApply; + +module.exports = DllPlugin; /***/ }), -/***/ 3414: -/***/ (function(module) { +/***/ 86231: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -82155,146 +77619,263 @@ module.exports = OptionsApply; */ -/** - * 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()]; -}; +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); -/** - * 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]]; +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; } - 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 = {}; - } + apply(compiler) { + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + DelegatedExportsDependency, + new NullFactory() + ); + } + ); - /** - * 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]); + 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; } - 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)); + } + 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; } - break; - /** - * Adding {@link AppendConfigValues} at the end of the current array - */ - case "append": { - let oldValue = getProperty(options, name); - if (!Array.isArray(oldValue)) { - oldValue = []; + 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); + } } - oldValue.push(...this.defaults[name]); - setProperty(options, name, oldValue); - break; } - default: - throw new Error( - "OptionsDefaulter cannot process " + this.config[name] - ); } - } - return options; + ); + } +} + +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: +/***/ (function(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; } /** - * 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 + * @param {Compiler} compiler the compiler instance * @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]; - } + 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 = OptionsDefaulter; +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); + } +}; /***/ }), -/***/ 70558: +/***/ 99531: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82304,2460 +77885,1564 @@ module.exports = OptionsDefaulter; */ -// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API +const WebpackError = __webpack_require__(97391); -const acorn = __webpack_require__(77087); -const { Tapable, SyncBailHook, HookMap } = __webpack_require__(56758); -const util = __webpack_require__(31669); -const vm = __webpack_require__(92184); -const BasicEvaluatedExpression = __webpack_require__(96770); -const StackedSetMap = __webpack_require__(92251); +class EntryModuleNotFoundError extends WebpackError { + constructor(err) { + super("Entry module not found: " + err); -const acornParser = acorn.Parser; + this.name = "EntryModuleNotFoundError"; + this.details = err.details; + this.error = err; -const joinRanges = (startRange, endRange) => { - if (!endRange) return startRange; - if (!startRange) return endRange; - return [startRange[0], endRange[1]]; -}; + Error.captureStackTrace(this, this.constructor); + } +} -const defaultParserOptions = { - ranges: true, - locations: true, - ecmaVersion: 11, - sourceType: "module", - onComment: null -}; +module.exports = EntryModuleNotFoundError; -// 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 +/***/ }), + +/***/ 14604: +/***/ (function(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); }; -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; +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; }); - 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); + +/***/ }), + +/***/ 71931: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ + + + +/** @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: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const loaderFlag = "LOADER_EXECUTION"; + +const webpackOptionsFlag = "WEBPACK_OPTIONS"; + +exports.cutOffByFlag = (stack, flag) => { + stack = stack.split("\n"); + for (let i = 0; i < stack.length; i++) { + if (stack[i].includes(flag)) { + stack.length = i; + } + } + return stack.join("\n"); +}; + +exports.cutOffLoaderExecution = stack => + exports.cutOffByFlag(stack, loaderFlag); + +exports.cutOffWebpackOptions = stack => + exports.cutOffByFlag(stack, webpackOptionsFlag); + +exports.cutOffMultilineMessage = (stack, message) => { + stack = stack.split("\n"); + message = message.split("\n"); + + 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: +/***/ (function(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); }); - 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); + } +} + +module.exports = EvalDevToolModulePlugin; + + +/***/ }), + +/***/ 24157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { RawSource } = __webpack_require__(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"); }); - 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]); + } +} + +module.exports = EvalDevToolModuleTemplatePlugin; + + +/***/ }), + +/***/ 51352: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { RawSource } = __webpack_require__(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)); } - } 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; + 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; } - } 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); - } - } + ); + 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; } - }); - 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); + ); + moduleTemplate.hooks.hash.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + hash => { + hash.update("eval-source-map"); + hash.update("2"); } - }); - 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); - }); - }); + ); + } +} +module.exports = EvalSourceMapDevToolModuleTemplatePlugin; - /** - * @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 +/***/ 99994: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - prevExpr.setString(prevExpr.string + exprAsString + quasi); - prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); - // We unset the expression as it doesn't match to a single expression - prevExpr.setExpression(undefined); - continue; - } - parts.push(expr); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const part = new BasicEvaluatedExpression() - .setString(quasi) - .setRange(quasiExpr.range) - .setExpression(quasiExpr); - quasis.push(part); - parts.push(part); - } - return { - quasis, - parts + +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; + } - 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); + 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); } - 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; +module.exports = EvalSourceMapDevToolPlugin; - 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); - } +/***/ 50471: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); - }); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; - } - } +const { ConcatSource } = __webpack_require__(53665); - walkMethodDefinition(methodDefinition) { - if (methodDefinition.computed && methodDefinition.key) { - this.walkExpression(methodDefinition.key); - } - if (methodDefinition.value) { - this.walkExpression(methodDefinition.value); - } - } +/** @typedef {import("./Compilation")} Compilation */ - // 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); - } - } +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; - // 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); - } +class ExportPropertyMainTemplatePlugin { + /** + * @param {string|string[]} property the name of the property to export + */ + constructor(property) { + this.property = property; } - // 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); - } - } + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; - 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; - } - } + const onRenderWithEntry = (source, chunk, hash) => { + const postfix = `${accessorToObjectAccess([].concat(this.property))}`; + return new ConcatSource(source, postfix); + }; - 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; + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "ExportPropertyMainTemplatePlugin", + onRenderWithEntry + ); } - } - 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; - } + mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { + hash.update("export property"); + hash.update(`${this.property}`); + }); } +} - // Real Statements - prewalkBlockStatement(statement) { - this.prewalkStatements(statement.body); - } +module.exports = ExportPropertyMainTemplatePlugin; - 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); - } - } +/***/ 17270: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); +"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); } - } + ); } +} - prewalkLabeledStatement(statement) { - this.prewalkStatement(statement.body); - } +module.exports = ExtendedAPIPlugin; - 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); - } +/***/ 17204: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - prewalkSwitchStatement(statement) { - this.prewalkSwitchCases(statement.cases); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - walkSwitchStatement(statement) { - this.walkExpression(statement.discriminant); - this.walkSwitchCases(statement.cases); - } - walkTerminatingStatement(statement) { - if (statement.argument) this.walkExpression(statement.argument); - } +const { OriginalSource, RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); +const WebpackMissingModule = __webpack_require__(75386); +const Template = __webpack_require__(96066); - walkReturnStatement(statement) { - this.walkTerminatingStatement(statement); - } +/** @typedef {import("./util/createHash").Hash} Hash */ - walkThrowStatement(statement) { - this.walkTerminatingStatement(statement); +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; } - prewalkTryStatement(statement) { - this.prewalkStatement(statement.block); + libIdent() { + return this.userRequest; } - 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); + chunkCondition(chunk) { + return chunk.hasEntryModule(); } - prewalkWhileStatement(statement) { - this.prewalkStatement(statement.body); + identifier() { + return "external " + JSON.stringify(this.request); } - walkWhileStatement(statement) { - this.walkExpression(statement.test); - this.walkStatement(statement.body); + readableIdentifier() { + return "external " + JSON.stringify(this.request); } - prewalkDoWhileStatement(statement) { - this.prewalkStatement(statement.body); + needRebuild() { + return false; } - walkDoWhileStatement(statement) { - this.walkStatement(statement.body); - this.walkExpression(statement.test); + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + callback(); } - prewalkForStatement(statement) { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.prewalkStatement(statement.init); - } + getSourceForGlobalVariableExternal(variableName, type) { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; } - 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); - } - }); + // needed for e.g. window["some"]["thing"] + const objectLookup = variableName + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `(function() { module.exports = ${type}${objectLookup}; }());`; } - prewalkForInStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.prewalkVariableDeclaration(statement.left); + getSourceForCommonJsExternal(moduleAndSpecifiers) { + if (!Array.isArray(moduleAndSpecifiers)) { + return `module.exports = require(${JSON.stringify( + moduleAndSpecifiers + )});`; } - 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); - } - }); + const moduleName = moduleAndSpecifiers[0]; + const objectLookup = moduleAndSpecifiers + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `module.exports = require(${JSON.stringify( + moduleName + )})${objectLookup};`; } - prewalkForOfStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.prewalkVariableDeclaration(statement.left); - } - this.prewalkStatement(statement.body); + checkExternalVariable(variableToCheck, request) { + return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( + request + )}}\n`; } - walkForOfStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPrewalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); - } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - this.blockPrewalkStatements(body.body); - this.walkStatements(body.body); - } else { - this.walkStatement(body); - } - }); + getSourceForAmdOrUmdExternal(id, optional, request) { + const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${id}` + )}__`; + const missingModuleError = optional + ? this.checkExternalVariable(externalVariable, request) + : ""; + return `${missingModuleError}module.exports = ${externalVariable};`; } - // Declarations - prewalkFunctionDeclaration(statement) { - if (statement.id) { - this.scope.renames.set(statement.id.name, null); - this.scope.definitions.add(statement.id.name); + getSourceForDefaultCase(optional, request) { + if (!Array.isArray(request)) { + // make it an array as the look up works the same basically + request = [request]; } - } - 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; + 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};`; } - 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; - } + 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); } } - 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; + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); } - } - blockPrewalkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.blockPrewalkStatement(statement.declaration); - } + return new RawSource(sourceString); } - 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; - } - } - } - } + source(dependencyTemplates, runtime) { + return this.getSource(this.getSourceString(runtime)); } - walkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.walkStatement(statement.declaration); - } + size() { + return 42; } - blockPrewalkExportDefaultDeclaration(statement) { - if (statement.declaration.type === "ClassDeclaration") { - this.blockPrewalkClassDeclaration(statement.declaration); - } + /** + * @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); } +} - 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" - ); - } - } +module.exports = ExternalModule; - 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); - } +/***/ 67876: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - blockPrewalkVariableDeclaration(statement) { - if (statement.kind === "var") return; - const hookMap = - statement.kind === "const" - ? this.hooks.varDeclarationConst - : this.hooks.varDeclarationLet; - this._prewalkVariableDeclaration(statement, hookMap); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - _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; - } - } - } - } +const ExternalModule = __webpack_require__(17204); - blockPrewalkClassDeclaration(statement) { - if (statement.id) { - this.scope.renames.set(statement.id.name, null); - this.scope.definitions.add(statement.id.name); - } +class ExternalModuleFactoryPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; } - walkClassDeclaration(statement) { - this.walkClass(statement); - } + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factory.tap( + "ExternalModuleFactoryPlugin", + factory => (data, callback) => { + const context = data.context; + const dependency = data.dependencies[0]; - prewalkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; - this.prewalkStatements(switchCase.consequent); - } - } + 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; + }; - walkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; + 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); + }; - if (switchCase.test) { - this.walkExpression(switchCase.test); - } - this.walkStatements(switchCase.consequent); - } - } + do { + asyncFlag = true; + if (i >= externals.length) return callback(); + handleExternals(externals[i++], handleExternalsAndCallback); + } while (!asyncFlag); + asyncFlag = false; + }; - 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); + 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); }); - this.walkPattern(catchClause.param); } - this.prewalkStatement(catchClause.body); - this.walkStatement(catchClause.body); - }); + ); } +} +module.exports = ExternalModuleFactoryPlugin; - 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); - } - } - } +/***/ 75705: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - walkArrayPattern(pattern) { - for (let i = 0, len = pattern.elements.length; i < len; i++) { - const element = pattern.elements[i]; - if (element) this.walkPattern(element); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - walkRestElement(pattern) { - this.walkPattern(pattern.argument); - } - walkExpressions(expressions) { - for (const expression of expressions) { - if (expression) { - this.walkExpression(expression); - } - } - } +const ExternalModuleFactoryPlugin = __webpack_require__(67876); - 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; - } +class ExternalsPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; } - - walkAwaitExpression(expression) { - this.walkExpression(expression.argument); + apply(compiler) { + compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory + ); + }); } +} - walkArrayExpression(expression) { - if (expression.elements) { - this.walkExpressions(expression.elements); - } - } +module.exports = ExternalsPlugin; - 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; +/***/ 47163: +/***/ (function(module) { - // Add function name in scope for recursive calls - if (expression.id) { - scopeParams.push(expression.id.name); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); - } +/** @typedef {import("./Compiler")} Compiler */ - walkUpdateExpression(expression) { - this.walkExpression(expression.argument); +class FlagAllModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; } - 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; - } + /** + * @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); + } + } + ); } - } - this.walkExpression(expression.argument); + ); } +} - walkLeftRightExpression(expression) { - this.walkExpression(expression.left); - this.walkExpression(expression.right); - } +module.exports = FlagAllModulesAsUsedPlugin; - 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); - }); - } +/***/ 73599: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); - } - } +const Queue = __webpack_require__(38637); - walkYieldExpression(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } +const addToSet = (a, b) => { + for (const item of b) { + a.add(item); } +}; - walkTemplateLiteral(expression) { - if (expression.expressions) { - this.walkExpressions(expression.expressions); - } - } +class FlagDependencyExportsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagDependencyExportsPlugin", + compilation => { + compilation.hooks.finishModules.tap( + "FlagDependencyExportsPlugin", + modules => { + const dependencies = new Map(); - walkTaggedTemplateExpression(expression) { - if (expression.tag) { - this.walkExpression(expression.tag); - } - if (expression.quasi && expression.quasi.expressions) { - this.walkExpressions(expression.quasi.expressions); - } - } + const queue = new Queue(); - walkClassExpression(expression) { - this.walkClass(expression); - } + let module; + let moduleWithExports; + let moduleProvidedExports; + let providedExportsAreTemporary; - _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]); + 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; + }; - // Add function name in scope for recursive calls - if (functionExpression.id) { - scopeParams.push(functionExpression.id.name); - } + 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; + }; - 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; - } + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; - 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; + 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); + } + } + }; - 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; - } - } - } + // 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); + } + } - if (expression.callee) this.walkExpression(expression.callee); - if (expression.arguments) this.walkExpressions(expression.arguments); - } - } + while (queue.length > 0) { + module = queue.dequeue(); - 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; + 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); + } + ); } - } - 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); - } - } +module.exports = FlagDependencyExportsPlugin; - 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); +/***/ 33632: +/***/ (function(module) { - this.enterPatterns(params, ident => { - this.scope.renames.set(ident, null); - this.scope.definitions.add(ident); - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - fn(); - this.scope = oldScope; +/** @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; +}; - 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() - }; +const isSubset = (biggerSet, subset) => { + if (biggerSet === true) return true; + if (subset === true) return false; + return subset.every(item => biggerSet.indexOf(item) >= 0); +}; - if (hasThis) { - this.scope.renames.set("this", null); - } +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; + } - this.enterPatterns(params, ident => { - this.scope.renames.set(ident, null); - this.scope.definitions.add(ident); - }); + // 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; + } - fn(); + queue.push([module, module, module.usedExports]); + }; - this.scope = oldScope; - } + 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]); + } + }; - 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() - }; + 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); + } + }; - fn(); + for (const module of modules) { + if (!module.used) module.used = false; + } - this.scope = oldScope; - } + /** @type {[Module, DependenciesBlock, UsedExports][]} */ + const queue = []; + for (const preparedEntrypoint of compilation._preparedEntrypoints) { + if (preparedEntrypoint.module) { + processModule(preparedEntrypoint.module, true); + } + } - // TODO webpack 5: remove this methods - // only for backward-compat - detectStrictMode(statements) { - this.detectMode(statements); + while (queue.length) { + const queueItem = queue.pop(); + processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); + } + } + ); + }); } +} +module.exports = FlagDependencyUsagePlugin; - 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; - } - } +/***/ 31221: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - enterIdentifier(pattern, onIdent) { - onIdent(pattern.name, pattern); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); - } - } +const FunctionModuleTemplatePlugin = __webpack_require__(18864); - enterRestElement(pattern, onIdent) { - this.enterPattern(pattern.argument, onIdent); +class FunctionModulePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { + new FunctionModuleTemplatePlugin().apply( + compilation.moduleTemplates.javascript + ); + }); } +} - enterAssignmentPattern(pattern, onIdent) { - this.enterPattern(pattern.left, onIdent); - } +module.exports = FunctionModulePlugin; - 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); + +/***/ }), + +/***/ 18864: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { ConcatSource } = __webpack_require__(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__"); } - return result; + } 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; } - } 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 - }; + 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; } - 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 moduleSource; } - } - 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; + moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { + hash.update("FunctionModuleTemplatePlugin"); + hash.update("2"); + }); } } - -// 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; +module.exports = FunctionModuleTemplatePlugin; /***/ }), -/***/ 23999: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 39172: +/***/ (function(module) { "use strict"; /* @@ -84765,154 +79450,163 @@ module.exports = Parser; Author Tobias Koppers @sokra */ -const path = __webpack_require__(85622); -const BasicEvaluatedExpression = __webpack_require__(96770); -const ConstDependency = __webpack_require__(71101); -const UnsupportedFeatureWarning = __webpack_require__(99953); +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ -const ParserHelpers = exports; +/** + * + */ +class Generator { + static byType(map) { + return new ByTypeGenerator(map); + } -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; -}; + /** + * @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"); + } +} -ParserHelpers.requireFileAsExpression = (context, pathToModule) => { - var moduleJsPath = path.relative(context, pathToModule); - if (!/^[A-Z]:/i.test(moduleJsPath)) { - moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); +class ByTypeGenerator extends Generator { + constructor(map) { + super(); + this.map = map; } - 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; - }; -}; + /** + * @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 + ); + } +} -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; - }; -}; +module.exports = Generator; -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); - }; +/***/ }), + +/***/ 32973: +/***/ (function(__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); + } }; -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; - }; +/** + * @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); + } }; -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; - }; +/** + * @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); + } }; -ParserHelpers.skipTraversal = function skipTraversal() { - return true; +/** + * @param {Chunk} chunk Chunk being disconnected + * @param {Module} module Module being disconnected + * @returns {void} + */ +const disconnectChunkAndModule = (chunk, module) => { + chunk.removeModule(module); + module.removeChunk(chunk); }; -ParserHelpers.approve = function approve() { - return true; +/** + * @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; + /***/ }), -/***/ 27850: +/***/ 30327: /***/ (function(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; - } - } +const WebpackError = __webpack_require__(97391); - 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 = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); } -} -module.exports = PrefetchPlugin; +}; /***/ }), -/***/ 63123: +/***/ 50268: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84921,825 +79615,797 @@ module.exports = PrefetchPlugin; Author Tobias Koppers @sokra */ +const createHash = __webpack_require__(15660); 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(); - }; +const schema = __webpack_require__(45843); - return defaultHandler; -}; +/** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ -class ProgressPlugin { +class HashedModuleIdsPlugin { /** - * @param {ProgressPluginArgument} options options + * @param {HashedModuleIdsPluginOptions=} options options object */ constructor(options) { - if (typeof options === "function") { - options = { - handler: options - }; - } + if (!options) options = {}; - options = options || {}; - validateOptions(schema, options, "Progress Plugin"); - options = Object.assign({}, ProgressPlugin.defaultOptions, options); + validateOptions(schema, options, "Hashed Module Ids Plugin"); - this.profile = options.profile; - this.handler = options.handler; - this.modulesCount = options.modulesCount; - this.showEntries = options.entries; - this.showModules = options.modules; - this.showActiveModules = options.activeModules; + /** @type {HashedModuleIdsPluginOptions} */ + this.options = Object.assign( + { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4 + }, + options + ); } 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); + 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); } - }); - }); - }); - 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; +module.exports = HashedModuleIdsPlugin; /***/ }), -/***/ 72861: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 65217: +/***/ (function(module) { -"use strict"; /* 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 = []; -const ParserHelpers = __webpack_require__(23999); -const ConstDependency = __webpack_require__(71101); - -const NullFactory = __webpack_require__(40438); + // 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; + }); -class ProvidePlugin { - constructor(definitions) { - this.definitions = definitions; + 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; } - 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; + // 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); + }, -/***/ 82353: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + //inherit from previous dispose call + data: hotCurrentModuleData[moduleId] + }; + hotCurrentChildModule = undefined; + return hot; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + var hotStatusHandlers = []; + var hotStatus = "idle"; + function hotSetStatus(newStatus) { + hotStatus = newStatus; + for (var i = 0; i < hotStatusHandlers.length; i++) + hotStatusHandlers[i].call(null, newStatus); + } -const Module = __webpack_require__(75993); -const { OriginalSource, RawSource } = __webpack_require__(53665); + // while downloading + var hotWaitingFiles = 0; + var hotChunksLoading = 0; + var hotWaitingFilesMap = {}; + var hotRequestedFilesMap = {}; + var hotAvailableFilesMap = {}; + var hotDeferred; -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; - } + // The update info + var hotUpdate, hotUpdateNewHash, hotQueuedInvalidatedModules; - identifier() { - return this.identifierStr; + function toModuleId(id) { + var isNumber = +id + "" === id; + return isNumber ? +id : id; } - size() { - return this.sourceStr.length; - } + 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; - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); + 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; + }); } - needRebuild() { - return false; + // 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(); + } } - build(options, compilations, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = { - cacheable: true - }; - callback(); + function hotEnsureUpdateChunk(chunkId) { + if (!hotAvailableFilesMap[chunkId]) { + hotWaitingFilesMap[chunkId] = true; + } else { + hotRequestedFilesMap[chunkId] = true; + hotWaitingFiles++; + hotDownloadUpdateChunk(chunkId); + } } - source() { - if (this.useSourceMap) { - return new OriginalSource(this.sourceStr, this.identifier()); + 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 { - return new RawSource(this.sourceStr); + var outdatedModules = []; + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + outdatedModules.push(toModuleId(id)); + } + } + deferred.resolve(outdatedModules); } } - updateHash(hash) { - hash.update(this.sourceStr); - super.updateHash(hash); + function hotApply(options) { + if (hotStatus !== "ready") + throw new Error("apply() is only allowed in ready status"); + options = options || {}; + return hotApplyInternal(options); } -}; - - -/***/ }), - -/***/ 40355: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const identifierUtils = __webpack_require__(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 - */ + function hotApplyInternal(options) { + hotApplyInvalidatedModules(); -/** - * @typedef {Object} Records - * @property {RecordsChunks=} chunks - * @property {RecordsModules=} modules - */ + var cb; + var i; + var j; + var module; + var moduleId; -class RecordIdsPlugin { - /** - * @param {Object} options Options object - * @param {boolean=} options.portableIds true, when ids need to be portable - */ - constructor(options) { - this.options = options || {}; - } + function getAffectedStuff(updateModuleId) { + var outdatedModules = [updateModuleId]; + var outdatedDependencies = {}; - /** - * @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; - } + 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 + }; } - ); - 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 (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 (Array.isArray(records.modules.usedIds)) { - compilation.usedModuleIds = new Set(records.modules.usedIds); + 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 + }); } - ); + } - /** - * @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(); + return { + type: "accepted", + moduleId: updateModuleId, + outdatedModules: outdatedModules, + outdatedDependencies: outdatedDependencies }; + } - /** - * @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; - }; + function addAllToSet(a, b) { + for (var i = 0; i < b.length; i++) { + var item = b[i]; + if (a.indexOf(item) === -1) a.push(item); + } + } - 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(); - } + // 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" ); - 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; - } + }; + + 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 (Array.isArray(records.chunks.usedIds)) { - compilation.usedChunkIds = new Set(records.chunks.usedIds); - } } - ); - }); - } -} -module.exports = RecordIdsPlugin; - - -/***/ }), - -/***/ 15377: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (doDispose) { + addAllToSet(outdatedModules, [result.moduleId]); + appliedUpdate[moduleId] = warnUnexpectedRequire; + } + } + } -"use strict"; + // 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); + } + }); -const WebpackError = __webpack_require__(97391); + var idx; + var queue = outdatedModules.slice(); + while (queue.length > 0) { + moduleId = queue.pop(); + module = installedModules[moduleId]; + if (!module) continue; -module.exports = class RemovedPluginError extends WebpackError { - constructor(message) { - super(message); + var data = {}; - Error.captureStackTrace(this, this.constructor); - } -}; + // 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]; -/***/ 54254: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // when disposing there is no need to call dispose handler + delete outdatedDependencies[moduleId]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // 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); + } + } + } + } -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 = /!=!/; + // Now in "apply" phase + hotSetStatus("apply"); -const normalizeBackSlashDirection = request => { - return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); -}; + if (hotUpdateNewHash !== undefined) { + hotCurrentHash = hotUpdateNewHash; + hotUpdateNewHash = undefined; + } + hotUpdate = undefined; -const createRegExpForPath = path => { - const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); - return new RegExp(`(^|!)${regexpTypePartial}`, "g"); -}; + // insert new code + for (moduleId in appliedUpdate) { + if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { + modules[moduleId] = appliedUpdate[moduleId]; + } + } -class RequestShortener { - constructor(directory) { - directory = normalizeBackSlashDirection(directory); - if (SEPARATOR_REGEXP.test(directory)) { - directory = directory.substr(0, directory.length - 1); + // 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; + } + } + } + } + } } - if (directory) { - this.currentDirectoryRegExp = createRegExpForPath(directory); + // 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; + } + } + } } - 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}/`); + // handle errors in accept handlers and self accepted module load + if (error) { + hotSetStatus("fail"); + return Promise.reject(error); } - 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); + if (hotQueuedInvalidatedModules) { + return hotApplyInternal(options).then(function(list) { + outdatedModules.forEach(function(moduleId) { + if (list.indexOf(moduleId) < 0) list.push(moduleId); + }); + return list; + }); } - this.cache = new Map(); + hotSetStatus("idle"); + return new Promise(function(resolve) { + resolve(outdatedModules); + }); } - 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)"); + function hotApplyInvalidatedModules() { + if (hotQueuedInvalidatedModules) { + if (!hotUpdate) hotUpdate = {}; + hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); + hotQueuedInvalidatedModules = undefined; + return true; } - 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; + function hotApplyInvalidatedModule(moduleId) { + if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) + hotUpdate[moduleId] = modules[moduleId]; + } +}; /***/ }), -/***/ 88226: +/***/ 69575: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -85749,728 +80415,877 @@ module.exports = RequestShortener; */ -const ParserHelpers = __webpack_require__(23999); +const { SyncBailHook } = __webpack_require__(56758); +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 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") - ); +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; + } - 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); + 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(); } ); - } -}; - - -/***/ }), - -/***/ 50588: -/***/ (function(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__(56758); -const Factory = __webpack_require__(87450).ResolverFactory; -const { cachedCleverMerge } = __webpack_require__(67916); + 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); + }; -/** @typedef {import("enhanced-resolve").Resolver} Resolver */ + 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 EMTPY_RESOLVE_OPTIONS = {}; + const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; + if (!hotUpdateChunkTemplate) return; -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(); - } + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - 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; - } + compilation.dependencyFactories.set( + ModuleHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotAcceptDependency, + new ModuleHotAcceptDependency.Template() + ); - _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; + 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) +); + /***/ }), -/***/ 84247: -/***/ (function(module) { +/***/ 26782: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "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: [ - - ] + + +const Chunk = __webpack_require__(2919); + +class HotUpdateChunk extends Chunk { + constructor() { + super(); + /** @type {(string|number)[]} */ + this.removedModules = undefined; + } } -: /regExp/ -: function(arg) {} -: "starting" -: [] // or -: { and: [] } -: { or: [] } -: { not: [] } -: { test: , include: , exclude: } +module.exports = HotUpdateChunk; -normalized: +/***/ }), -{ - resource: function(), - resourceQuery: function(), - compiler: function(), - issuer: function(), - use: [ - { - loader: string, - options: string, - : - } - ], - rules: [], - oneOf: [], - : , -} +/***/ 66062: +/***/ (function(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__(56758); -const notMatcher = matcher => { - return str => { - return !matcher(str); - }; -}; +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"]) + }; + } -const orMatcher = items => { - return str => { - for (let i = 0; i < items.length; i++) { - if (items[i](str)) return true; - } - return false; - }; -}; + 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; + } -const andMatcher = items => { - return str => { - for (let i = 0; i < items.length; i++) { - if (!items[i](str)) return false; - } - return true; - }; + updateHash(hash) { + hash.update("HotUpdateChunkTemplate"); + hash.update("1"); + this.hooks.hash.call(hash); + } }; -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 + - ")" - ); - } +/***/ 41364: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const newRule = {}; - let useSource; - let resourceSource; - let condition; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; - }; +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(69667); - if (rule.test || rule.include || rule.exclude) { - checkResourceSource("test + include + exclude"); - condition = { - test: rule.test, - include: rule.include, - exclude: rule.exclude +/** @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] }; - 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)); - } - } + validateOptions(schema, options, "IgnorePlugin"); + this.options = options; - if (rule.realResource) { - try { - newRule.realResource = RuleSet.normalizeCondition(rule.realResource); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); - } - } + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); + } - if (rule.resourceQuery) { - try { - newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); - } - } + /** + * 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 (rule.compiler) { - try { - newRule.compiler = RuleSet.normalizeCondition(rule.compiler); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); + 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 (rule.issuer) { - try { - newRule.issuer = RuleSet.normalizeCondition(rule.issuer); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + 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; } } - if (rule.loader && rule.loaders) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "Provided loader and loaders for rule (use only one of them)" - ) - ) - ); - } + return result; + } - 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)" - ) - ) - ); - } + /** + * @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); + }); + } +} - if (rule.use) { - checkUseSource("use"); - newRule.use = RuleSet.normalizeUse(rule.use, ident); - } +module.exports = IgnorePlugin; - 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]; - } +/***/ 98509: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (Array.isArray(newRule.use)) { - for (const item of newRule.use) { - if (item.ident) { - refs[item.ident] = item.options; - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return newRule; - } - static buildErrorMessage(condition, error) { - const conditionAsText = JSON.stringify( - condition, - (key, value) => { - return value === undefined ? "undefined" : value; - }, - 2 - ); - return error.message + " in " + conditionAsText; - } +const { RawSource, ReplaceSource } = __webpack_require__(53665); - 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)]; - } +// TODO: clean up this file +// replace with newer constructs - 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 - }; - } +// TODO: remove DependencyVariables and replace them with something better - static normalizeUseItem(item, ident) { - if (typeof item === "string") { - return RuleSet.normalizeUseItemString(item); +class JavascriptGenerator { + generate(module, dependencyTemplates, runtimeTemplate) { + const originalSource = module.originalSource(); + if (!originalSource) { + return new RawSource("throw new Error('No source available');"); } - const newItem = {}; - - if (item.options && item.query) { - throw new Error("Provided options and query in use"); - } + const source = new ReplaceSource(originalSource); - if (!item.loader) { - throw new Error("No loader specified"); - } + this.sourceBlock( + module, + module, + [], + dependencyTemplates, + source, + runtimeTemplate + ); - newItem.options = item.options || item.query; + return source; + } - if (typeof newItem.options === "object" && newItem.options) { - if (newItem.options.ident) { - newItem.ident = newItem.options.ident; - } else { - newItem.ident = ident; - } + sourceBlock( + module, + block, + availableVars, + dependencyTemplates, + source, + runtimeTemplate + ) { + for (const dependency of block.dependencies) { + this.sourceDependency( + dependency, + dependencyTemplates, + source, + runtimeTemplate + ); } - const keys = Object.keys(item).filter(function(key) { - return !["options", "query"].includes(key); - }); + /** + * 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 + ); - for (const key of keys) { - newItem[key] = item[key]; - } + if (variable) { + result.push(variable); + } - return newItem; - } + return result; + }, []); - 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 + - ")" + /** + * 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 ); - } - 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"); + // 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); } - }); - if (matchers.length === 0) { - throw new Error("Excepted condition but got " + condition); } - if (matchers.length === 1) { - return matchers[0]; + + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + availableVars.concat(vars), + dependencyTemplates, + source, + runtimeTemplate + ); } - return andMatcher(matchers); } - exec(data) { - const result = []; - this._run( - data, - { - rules: this.rules - }, - result - ); - return result; + 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); } - _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; + sourceVariables( + variable, + availableVars, + dependencyTemplates, + runtimeTemplate + ) { + const name = variable.name; + const expr = variable.expressionSource( + dependencyTemplates, + runtimeTemplate + ); + if ( - data.resourceQuery && - rule.resourceQuery && - !rule.resourceQuery(data.resourceQuery) + availableVars.some( + v => v.name === name && v.expression.source() === expr.source() + ) ) { - return false; - } - if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { - return false; + return; } + return { + name: name, + expression: expr + }; + } - // 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] - }); - } + /* + * 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}) {`; + } - 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); + contextArgument(module, block) { + if (this === block) { + return module.exportsArgument; } + return "this"; + } - if (rule.rules) { - for (let i = 0; i < rule.rules.length; i++) { - this._run(data, rule.rules[i], result); - } - } + /* + * 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}))`; + } - if (rule.oneOf) { - for (let i = 0; i < rule.oneOf.length; i++) { - if (this._run(data, rule.oneOf[i], result)) break; - } - } + 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 + ); - return true; + if (variableNameAlreadyExists) { + // start new chunk with current variable + chunks.push([variable]); + } else { + // else add it to current chunk + current.push(variable); + } + return chunks; + }, startState); } +} - findOptionsByIdent(ident) { - const options = this.references[ident]; - if (!options) { - throw new Error("Can't find options with ident '" + ident + "'"); - } - return options; - } -}; +module.exports = JavascriptGenerator; /***/ }), -/***/ 44006: +/***/ 10339: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -86480,418 +81295,255 @@ module.exports = class RuleSet { */ +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); -/** @typedef {import("./Module")} Module */ +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; -module.exports = class RuntimeTemplate { - constructor(outputOptions, requestShortener) { - this.outputOptions = outputOptions || {}; - this.requestShortener = requestShortener; + 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); + }); + } + ); } - /** - * 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) + " "; + 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, ";"); } +} - 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; }`; - } +module.exports = JavascriptModulesPlugin; - missingModule({ request }) { - return `!(${this.throwMissingModuleErrorFunction({ request })}())`; - } - missingModuleStatement({ request }) { - return `${this.missingModule({ request })};\n`; - } +/***/ }), - missingModulePromise({ request }) { - return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ - request - })})`; +/***/ 72806: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { ConcatSource, RawSource } = __webpack_require__(53665); + +const stringifySafe = data => { + const stringified = JSON.stringify(data); + if (!stringified) { + return undefined; // Invalid JSON } - 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)`; - } - } + return stringified.replace(/\u2028|\u2029/g, str => + str === "\u2029" ? "\\u2029" : "\\u2028" + ); // invalid in JavaScript but valid JSON +}; - 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.` +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 + }) ); } - 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})`; + 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]; } } - 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(", ")}])`; + finalJson = reducedJson; } else { - return `Promise.resolve(${comment.trim()})`; - } - } - - onError() { - return "__webpack_require__.oe"; - } - - defineEsModuleFlagStatement({ exportsArgument }) { - return `__webpack_require__.r(${exportsArgument});\n`; - } -}; - - -/***/ }), - -/***/ 37098: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { ConcatSource } = __webpack_require__(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 - ); + finalJson = data; } - - 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}`); - }); + // 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 = SetVarMainTemplatePlugin; +module.exports = JsonGenerator; /***/ }), -/***/ 19070: +/***/ 2859: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -86900,101 +81552,71 @@ module.exports = SetVarMainTemplatePlugin; 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; - } +const JsonParser = __webpack_require__(5807); +const JsonGenerator = __webpack_require__(72806); - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ +class JsonModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap( - "SingleEntryPlugin", + "JsonModulesPlugin", (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); + normalModuleFactory.hooks.createParser + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonParser(); + }); + normalModuleFactory.hooks.createGenerator + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonGenerator(); + }); } ); } - - /** - * @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; +module.exports = JsonModulesPlugin; /***/ }), -/***/ 12496: -/***/ (function(__unused_webpack_module, exports) { +/***/ 5807: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const SizeFormatHelpers = exports; +const parseJson = __webpack_require__(48335); +const JsonExportsDependency = __webpack_require__(54396); -SizeFormatHelpers.formatSize = size => { - if (typeof size !== "number" || Number.isNaN(size) === true) { - return "unknown size"; +class JsonParser { + constructor(options) { + this.options = options; } - if (size <= 0) { - return "0 bytes"; + 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; } +} - const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; - const index = Math.floor(Math.log(size) / Math.log(1024)); - - return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ - abbreviations[index] - }`; -}; +module.exports = JsonParser; /***/ }), -/***/ 24113: +/***/ 30735: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87004,54 +81626,95 @@ SizeFormatHelpers.formatSize = size => { */ -const ModuleFilenameHelpers = __webpack_require__(71474); +const path = __webpack_require__(85622); +const asyncLib = __webpack_require__(36386); +const SingleEntryDependency = __webpack_require__(84828); -class SourceMapDevToolModuleOptionsPlugin { +class LibManifestPlugin { 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; + 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; /***/ }), -/***/ 11851: +/***/ 65237: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87061,423 +81724,289 @@ module.exports = SourceMapDevToolModuleOptionsPlugin; */ -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); +const SetVarMainTemplatePlugin = __webpack_require__(37098); -/** @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("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ /** @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[]} accessor the accessor to convert to path + * @returns {string} the path */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; /** - * @param {string} name file path - * @returns {string} file name + * @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 basename = name => { - if (!name.includes("/")) return name; - return name.substr(name.lastIndexOf("/") + 1); +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); }; -/** - * @type {WeakMap} - */ -const assetsCache = new WeakMap(); +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; + } -/** - * 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 + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - if (asset.sourceAndMap) { - const sourceAndMap = asset.sourceAndMap(options); - sourceMap = sourceAndMap.map; - source = sourceAndMap.source; - } else { - sourceMap = asset.map(options); - source = asset.source(); + 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`); + } + }); } - 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 - }; -}; +module.exports = LibraryTemplatePlugin; -class SourceMapDevToolPlugin { + +/***/ }), + +/***/ 48775: +/***/ (function(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 {SourceMapDevToolPluginOptions} [options] options object - * @throws {Error} throws error, if got more than 1 arguments + * @param {LoaderOptionsPluginOptions} options options object */ 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"); + validateOptions(schema, options || {}, "Loader Options 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} */ + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; + } 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 - }); + 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]; } } + } + ); + }); + } +} - 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; - } +module.exports = LoaderOptionsPlugin; - 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 - ) - ); - } - } +/***/ 95154: +/***/ (function(module) { - tasks.push(task); - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; - } +class LoaderTargetPlugin { + constructor(target) { + this.target = target; + } - // 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); + apply(compiler) { + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; } ); }); } } -module.exports = SourceMapDevToolPlugin; +module.exports = LoaderTargetPlugin; /***/ }), -/***/ 99977: +/***/ 43626: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87487,2328 +82016,1558 @@ module.exports = SourceMapDevToolPlugin; */ -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 { + ConcatSource, + OriginalSource, + PrefixSource, + RawSource +} = __webpack_require__(53665); +const { + Tapable, + SyncWaterfallHook, + SyncHook, + SyncBailHook +} = __webpack_require__(56758); +const Template = __webpack_require__(96066); -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; -}; +/** @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} */ -class Stats { - constructor(compilation) { - this.compilation = compilation; - this.hash = compilation.hash; - this.startTime = undefined; - this.endTime = undefined; - } +/** + * @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 + */ - static filterWarnings(warnings, warningsFilter) { - // we dont have anything to filter so all warnings can be shown - if (!warningsFilter) { - return warnings; - } +// 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 - // 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); - } +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"]), - if (filter instanceof RegExp) { - return warning => filter.test(warning); + // 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)});` + ); } - - if (typeof filter === "function") { - return filter; + 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; } - - throw new Error( - `Can only filter warnings with Strings or RegExps. (Given: ${filter})` - ); + ); + this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// The module cache", + "var installedModules = {};" + ]); }); - return warnings.filter(warning => { - return !normalizedWarningsFilters.some(check => check(warning)); + 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;" + ]); }); - } - - 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()) + 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;`); - // remove a prefixed "!" that can be specified to reverse sort order - normalizeFieldKey(field) { - if (field[0] === "!") { - return field.substr(1); - } - return field; - } + buf.push(""); + buf.push("// expose the module cache"); + buf.push(`${this.requireFn}.c = installedModules;`); - // if a field is prefixed by a "!" reverse sort order - sortOrderRegular(field) { - if (field[0] === "!") { - return false; - } - return true; - } + 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("};"); - toJson(options, forToString) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; - } + 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("};"); - const optionOrLocalFallback = (v, def) => - v !== undefined ? v : options.all !== undefined ? options.all : def; + 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("};"); - 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; - } - }; + 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("};"); - 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 + 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 + ) ); - const showProvidedExports = optionOrLocalFallback( - options.providedExports, - !forToString + 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)) ); - const showOptimizationBailout = optionOrLocalFallback( - options.optimizationBailout, - !forToString + buf.push(""); + buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); + const afterStartupCode = Template.asString( + this.hooks.afterStartup.call("", chunk, hash) ); - 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 + 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 ); - const showWarnings = optionOrLocalFallback(options.warnings, true); - const warningsFilter = optionsOrFallback(options.warningsFilter, null); - const showPublicPath = optionOrLocalFallback( - options.publicPath, - !forToString + let source = this.hooks.render.call( + new OriginalSource( + Template.prefix(buf, " \t") + "\n", + "webpack/bootstrap" + ), + chunk, + hash, + moduleTemplate, + dependencyTemplates ); - const showLogging = optionOrLocalFallback( - options.logging, - forToString ? "info" : true + 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 ); - const showLoggingTrace = optionOrLocalFallback( - options.loggingTrace, - !forToString + } + + /** + * + * @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 ); - 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 + /** + * + * @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 ); - const sortModules = optionsOrFallback(options.modulesSort, "id"); - const sortChunks = optionsOrFallback(options.chunksSort, "id"); - const sortAssets = optionsOrFallback(options.assetsSort, ""); - const showOutputPath = optionOrLocalFallback( - options.outputPath, - !forToString + } + + /** + * + * @param {object} options get public path options + * @returns {string} hook call + */ + getPublicPath(options) { + return this.hooks.assetPath.call( + this.outputOptions.publicPath || "", + options ); + } - if (!showCachedModules) { - excludeModules.push((ident, module) => !module.built); - } + getAssetPath(path, options) { + return this.hooks.assetPath.call(path, options); + } - 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; - }; - }; + 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 }; + } - 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; - }; - }; + /** + * 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); + } - 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; - }; + /** + * 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); + } + } - 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); + useChunkHash(chunk) { + const paths = this.hooks.globalHashPaths.call([]); + return !this.hooks.globalHash.call(chunk, paths); + } +}; - // 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; - }; +/***/ 50332: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const obj = { - errors: compilation.errors.map(formatError), - warnings: Stats.filterWarnings( - compilation.warnings.map(formatError), - warningsFilter - ) - }; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +module.exports = __webpack_require__(32327); - //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; +/***/ }), + +/***/ 75993: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const util = __webpack_require__(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; + } - if (showHash) obj.hash = this.hash; - if (showTimings && this.startTime && this.endTime) { - obj.time = this.endTime - this.startTime; + isInChunk(chunk) { + return this._chunks.has(chunk); + } + + isEntryModule() { + for (const chunk of this._chunks) { + if (chunk.entryModule === this) return true; } + return false; + } - if (showBuiltAt && this.endTime) { - obj.builtAt = this.endTime; + 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; } + } - if (showEnv && options._env) { - obj.env = options._env; + 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; + } - if (compilation.needAdditionalPass) { - obj.needAdditionalPass = true; + hasReasonForChunk(chunk) { + if (this._rewriteChunkInReasons) { + for (const operation of this._rewriteChunkInReasons) { + this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + } + this._rewriteChunkInReasons = undefined; } - if (showPublicPath) { - obj.publicPath = this.compilation.mainTemplate.getPublicPath({ - hash: this.compilation.hash - }); + for (let i = 0; i < this.reasons.length; i++) { + if (this.reasons[i].hasChunk(chunk)) return true; } - if (showOutputPath) { - obj.outputPath = this.compilation.mainTemplate.outputOptions.path; + 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 = []; } - 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) - }; + this._rewriteChunkInReasons.push({ + oldChunk, + newChunks + }); + } - if (showPerformance) { - obj.isOverSizeLimit = source.isOverSizeLimit; - } + _doRewriteChunkInReasons(oldChunk, newChunks) { + for (let i = 0; i < this.reasons.length; i++) { + this.reasons[i].rewriteChunks(oldChunk, newChunks); + } + } - assetsByFile[name] = obj; - return obj; - }) - .filter(createAssetFilter()); - obj.filteredAssets = compilationAssets.length - obj.assets.length; + /** + * @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; - 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; - } - } - } - } + // 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); } - obj.assets.sort(sortByField(sortAssets, obj.assets)); } + return exportName; + } - 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; - } - } + isProvided(exportName) { + if (!Array.isArray(this.buildMeta.providedExports)) return null; + return this.buildMeta.providedExports.includes(exportName); + } - return obj; - }; + toString() { + return `Module[${this.id || this.debugId}]`; + } - if (showEntrypoints) { - obj.entrypoints = fnChunkGroup(compilation.entrypoints); - } + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } - if (showChunkGroups) { - obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); + /** + * @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(); } + } - 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; - }); - } + unbuild() { + this.dependencies.length = 0; + this.blocks.length = 0; + this.variables.length = 0; + this.buildMeta = undefined; + this.buildInfo = undefined; + this.disconnect(); + } - return obj; + get arguments() { + throw new Error("Module.arguments was removed, there is no replacement."); } - toString(options) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; - } + set arguments(value) { + throw new Error("Module.arguments was removed, there is no replacement."); + } +} - const useColors = optionsOrFallback(options.colors, false); +// 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" + ) +}); - const obj = this.toJson(options, true); +// 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" + ) +}); - return Stats.jsonToString(obj, useColors); +// 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"); } +}); - static jsonToString(obj, useColors) { - const buf = []; +// 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" + ) +}); - 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" - }; +/** @type {function(): string} */ +Module.prototype.identifier = null; - 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) - } - ); +/** @type {function(RequestShortener): string} */ +Module.prototype.readableIdentifier = null; - 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`); - }; +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; - const newline = () => buf.push("\n"); +module.exports = Module; - 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 || " "); +/***/ }), + +/***/ 12072: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const WebpackError = __webpack_require__(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; } } - newline(); + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; } - }; + } else { + message = err; + } - const getAssetColor = (asset, defaultColor) => { - if (asset.isOverSizeLimit) { - return colors.yellow; - } + super(message); - return defaultColor; - }; + this.name = "ModuleBuildError"; + this.details = details; + this.module = module; + this.error = err; - 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; + Error.captureStackTrace(this, this.constructor); + } +} - try { - builtAtDate.toLocaleTimeString(); - } catch (err) { - // Force UTC if runtime timezone is unsupported - timeZone = "UTC"; - } +module.exports = ModuleBuildError; - 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(); - } - }; +/***/ 14953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (obj.entrypoints) { - processChunkGroups(obj.entrypoints, "Entrypoint"); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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 WebpackError = __webpack_require__(97391); - 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"}]` - ); - } - }; +/** @typedef {import("./Module")} Module */ - 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 + "| "); - } - }; +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); - 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(); - } - } - }; + 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; - 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, " "); - } - } + Error.captureStackTrace(this, this.constructor); + } +} - 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; +module.exports = ModuleDependencyError; /***/ }), -/***/ 97365: +/***/ 59136: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Joel Denning @joeldenning - */ - + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const { ConcatSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); +const WebpackError = __webpack_require__(97391); -/** @typedef {import("./Compilation")} Compilation */ +module.exports = class ModuleDependencyWarning extends WebpackError { + constructor(module, err, loc) { + super(err.message); -/** - * @typedef {Object} SystemMainTemplatePluginOptions - * @param {string=} name the library name - */ + 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; -class SystemMainTemplatePlugin { - /** - * @param {SystemMainTemplatePluginOptions} options the plugin options - */ - constructor(options) { - this.name = options.name; + Error.captureStackTrace(this, this.constructor); } +}; - /** - * @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}`)}__` - ); +/***/ 82528: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Declaring variables for the internal variable names for the webpack externals - const externalVarDeclarations = - externalWebpackNames.length > 0 - ? `var ${externalWebpackNames.join(", ")};` - : ""; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 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([");"]), "}"]), - "};" - ]), - "})" - ]) - ); - }; +const WebpackError = __webpack_require__(97391); +const { cleanUp } = __webpack_require__(80140); - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "SystemMainTemplatePlugin", - onRenderWithEntry - ); +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; - 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); - } - }); + Error.captureStackTrace(this, this.constructor); } } -module.exports = SystemMainTemplatePlugin; +module.exports = ModuleError; /***/ }), -/***/ 96066: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 71474: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -/** @typedef {import("./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; +const createHash = __webpack_require__(15660); -/** @typedef {import("webpack-sources").Source} Source */ +const ModuleFilenameHelpers = exports; -/** - * @typedef {Object} HasId - * @property {number | string} id - */ +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; -/** - * @typedef {function(Module, number): boolean} ModuleFilterPredicate - */ +const getAfter = (str, token) => { + const idx = str.indexOf(token); + return idx < 0 ? "" : str.substr(idx); +}; -/** - * @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; +const getBefore = (str, token) => { + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.substr(0, idx); }; -class Template { - /** - * - * @param {Function} fn a runtime function (.runtime.js) "template" - * @returns {string} the updated and normalized function string - */ - static getFunctionContent(fn) { - return fn - .toString() - .replace(FUNCTION_CONTENT_REGEX, "") - .replace(INDENT_MULTILINE_REGEX, "") - .replace(LINE_SEPARATOR_REGEX, "\n"); - } +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); +}; - /** - * @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, "* /")} */`; +const asRegExp = test => { + if (typeof test === "string") { + test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); } + return test; +}; - /** - * - * @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, "* /")} */`; - } +ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { + const opts = Object.assign( + { + namespace: "", + moduleFilenameTemplate: "" + }, + typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + } + ); - /** - * @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, ""); + 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); +}; - // 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 - ); +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; } + }); +}; - // use multiple letters - return ( - Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + - Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) - ); +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); } +}; - /** - * - * @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"); +ModuleFilenameHelpers.matchObject = (obj, str) => { + if (obj.test) { + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; } } - - /** - * - * @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"); + if (obj.include) { + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } } - - /** - * - * @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"); + if (obj.exclude) { + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; } - return str; } + return true; +}; - /** - * @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; +/***/ }), + +/***/ 71638: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const WebpackError = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const WebpackError = __webpack_require__(97391); + +/** @typedef {import("./Module")} Module */ +class ModuleParseError extends WebpackError { /** - * @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 + * @param {Module} module the errored module + * @param {string} source source code + * @param {Error&any} err the parse error + * @param {string[]} loaders the loaders used */ - 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; + 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 ( - modules.length === 0 && - (!removedModules || removedModules.length === 0) + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" ) { - 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(")"); + 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 { - // 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}}`); + message += "\n" + err.stack; } - return source; + + super(message); + + this.name = "ModuleParseError"; + this.module = module; + this.loc = loc; + this.error = err; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = Template; +module.exports = ModuleParseError; /***/ }), -/***/ 76032: +/***/ 44576: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Jason Anderson @diurnalist + Author Tobias Koppers @sokra */ -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; +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency")} Dependency */ -// 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"); +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; + } -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; -}; + 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; + } -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}` - ); + 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(); } - return ""; - } else { - return `${escapePathVariables(value)}`; } - }; - return fn; -}; + if (this._chunks.has(oldChunk)) { + this._chunks.delete(oldChunk); + for (let i = 0; i < newChunks.length; i++) { + this._chunks.add(newChunks[i]); + } + } + } +} -const escapePathVariables = value => { - return typeof value === "string" - ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, "[\\$1\\]") - : value; -}; +module.exports = ModuleReason; -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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 75100: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -89817,310 +83576,98 @@ module.exports = TemplatedPathPlugin; */ -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 - */ +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); -/** - * @typedef {Object} UmdMainTemplatePluginOption - * @property {boolean=} optionalAmdExternalAsGlobal - * @property {boolean} namedDefine - * @property {string | AuxiliaryCommentObject} auxiliaryComment - */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ -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; +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 {Compilation} compilation the compilation instance - * @returns {void} + * @param {Module} module the module + * @param {TODO} dependencyTemplates templates for dependencies + * @param {TODO} options render options + * @returns {Source} the source */ - 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})" + render(module, dependencyTemplates, options) { + try { + const moduleSource = module.source( + dependencyTemplates, + this.runtimeTemplate, + this.type ); - }; - - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "UmdMainTemplatePlugin", - onRenderWithEntry + 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; } - - 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; + updateHash(hash) { + hash.update("1"); + this.hooks.hash.call(hash); + } +}; /***/ }), -/***/ 99953: +/***/ 6372: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90131,34 +83678,40 @@ module.exports = UmdMainTemplatePlugin; const WebpackError = __webpack_require__(97391); +const { cleanUp } = __webpack_require__(80140); -/** @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) { +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 = "UnsupportedFeatureWarning"; + this.name = "ModuleWarning"; this.module = module; - this.loc = loc; - this.hideStack = true; + this.warning = warning; + this.details = + warning && typeof warning === "object" && warning.stack + ? cleanUp(warning.stack, this.message) + : undefined; Error.captureStackTrace(this, this.constructor); } } -module.exports = UnsupportedFeatureWarning; +module.exports = ModuleWarning; /***/ }), -/***/ 73554: +/***/ 10238: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90168,129 +83721,295 @@ module.exports = UnsupportedFeatureWarning; */ -const ConstDependency = __webpack_require__(71101); - -/** @typedef {import("./Compiler")} Compiler */ +const { Tapable, SyncHook, MultiHook } = __webpack_require__(56758); +const asyncLib = __webpack_require__(36386); +const MultiWatching = __webpack_require__(66624); +const MultiStats = __webpack_require__(55144); +const ConcurrentCompilationError = __webpack_require__(18933); -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 = 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; } -} -module.exports = UseStrictPlugin; + 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"); + } -/***/ 40269: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } + } + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } + } -const CaseSensitiveModulesWarning = __webpack_require__(8335); + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); + } -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]); - } + 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 + }); } - for (const pair of moduleWithoutCase) { - const array = pair[1]; - if (array.length > 1) { - compilation.warnings.push(new CaseSensitiveModulesWarning(array)); - } + } + } + } + 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; } -} -module.exports = WarnCaseSensitiveModulesPlugin; + 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 + } + ); + } -/***/ 71245: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return new MultiWatching(watchings, this); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + const finalCallback = (err, stats) => { + this.running = false; -const NoModeWarning = __webpack_require__(45759); + if (callback !== undefined) { + return callback(err, stats); + } + }; -class WarnNoModeSetPlugin { - apply(compiler) { - compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { - compilation.warnings.push(new NoModeWarning()); - }); + 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)); + } + ); + } } -} -module.exports = WarnNoModeSetPlugin; + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); + } + } + } +}; /***/ }), -/***/ 88015: +/***/ 98046: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90300,111 +84019,85 @@ module.exports = WarnNoModeSetPlugin; */ -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(97009); +const MultiEntryDependency = __webpack_require__(7791); +const SingleEntryDependency = __webpack_require__(84828); +const MultiModuleFactory = __webpack_require__(24005); -/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ -class IgnoringWatchFileSystem { - constructor(wfs, paths) { - this.wfs = wfs; - this.paths = paths; +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; } - 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); - } + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MultiEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); - callback( - err, - filesModified, - dirsModified, - missingModified, - fileTimestamps, - dirTimestamps, - removedFiles + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory ); - }, - callbackUndelayed + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } ); - 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; + compiler.hooks.make.tapAsync( + "MultiEntryPlugin", + (compilation, callback) => { + const { context, entries, name } = this; + + const dep = MultiEntryPlugin.createDependency(entries, name); + compilation.addEntry(context, dep, name, callback); } - }; + ); } -} -class WatchIgnorePlugin { /** - * @param {WatchIgnorePluginOptions} paths list of paths + * @param {string[]} entries each entry path string + * @param {string} name name of the entry + * @returns {MultiEntryDependency} returns a constructed Dependency */ - 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 - ); - }); + 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 = WatchIgnorePlugin; +module.exports = MultiEntryPlugin; /***/ }), -/***/ 29580: +/***/ 4198: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90414,255 +84107,318 @@ module.exports = WatchIgnorePlugin; */ -const Stats = __webpack_require__(99977); +const Module = __webpack_require__(75993); +const Template = __webpack_require__(96066); +const { RawSource } = __webpack_require__(53665); -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(); +/** @typedef {import("./util/createHash").Hash} Hash */ - if (this.compiler.hooks.shouldEmit.call(compilation) === false) { - return this._done(null, compilation); - } +class MultiModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); - 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); + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this._identifier = `multi ${this.dependencies + .map(d => d.request) + .join(" ")}`; + } - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; + identifier() { + return this._identifier; + } - 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); + readableIdentifier(requestShortener) { + return `multi ${this.dependencies + .map(d => requestShortener.shorten(d.request)) + .join(" ")}`; + } - 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); - }); + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); } - _getStats(compilation) { - const stats = new Stats(compilation); - stats.startTime = this.startTime; - stats.endTime = Date.now(); - return stats; + needRebuild() { + return false; } - _done(err, compilation) { - this.running = false; - if (this.invalid) return this._go(); + size() { + return 16 + this.dependencies.length * 12; + } - 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; - }); + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("multi module"); + hash.update(this.name || ""); + super.updateHash(hash); } - 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); + 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 = "); } - this.compiler.fileTimestamps = fileTimestamps; - this.compiler.contextTimestamps = contextTimestamps; - this.compiler.removedFiles = removedFiles; - if (!this.suspended) { - this._invalidate(); + str.push("__webpack_require__("); + if (runtimeTemplate.outputOptions.pathinfo) { + str.push(Template.toComment(dep.request)); } - }, - (fileName, changeTime) => { - this.compiler.hooks.invalid.call(fileName, changeTime); + 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: +/***/ (function(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__(56758); +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) ); } +}; - invalidate(callback) { - if (callback) { - this.callbacks.push(callback); + +/***/ }), + +/***/ 55144: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Stats = __webpack_require__(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 = {}; } - if (this.watcher) { - this.compiler.fileTimestamps = this.watcher.getFileTimestamps(); - this.compiler.contextTimestamps = this.watcher.getContextTimestamps(); + 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; + } } - return this._invalidate(); + 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; } - _invalidate() { - if (this.watcher) { - this.pausedWatcher = this.watcher; - this.watcher.pause(); - this.watcher = null; + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; } - if (this.running) { - this.invalid = true; - return false; - } else { - this._go(); + const useColors = optionOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } +} + +module.exports = MultiStats; + + +/***/ }), + +/***/ 66624: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const asyncLib = __webpack_require__(36386); + +class MultiWatching { + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; + } + + invalidate() { + for (const watching of this.watchings) { + watching.invalidate(); } } suspend() { - this.suspended = true; - this.invalid = false; + for (const watching of this.watchings) { + watching.suspend(); + } } resume() { - if (this.suspended) { - this.suspended = false; - this._invalidate(); + for (const watching of this.watchings) { + watching.resume(); } } 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(); - } + 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 = Watching; +module.exports = MultiWatching; /***/ }), -/***/ 97391: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 70419: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Jarid Margolin @jaridmargolin + Author Tobias Koppers @sokra */ -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; +class NamedChunksPlugin { + static defaultNameResolver(chunk) { + return chunk.name || null; + } - Error.captureStackTrace(this, this.constructor); + constructor(nameResolver) { + this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; } - [inspect]() { - return this.stack + (this.details ? `\n${this.details}` : ""); + 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 = WebpackError; +module.exports = NamedChunksPlugin; /***/ }), -/***/ 2779: +/***/ 86707: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90672,551 +84428,122 @@ module.exports = WebpackError; */ -const OptionsApply = __webpack_require__(4428); +const createHash = __webpack_require__(15660); +const RequestShortener = __webpack_require__(54254); -const JavascriptModulesPlugin = __webpack_require__(10339); -const JsonModulesPlugin = __webpack_require__(2859); -const WebAssemblyModulesPlugin = __webpack_require__(99510); +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); +}; -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); +class NamedModulesPlugin { + constructor(options) { + this.options = options || {}; + } -const EntryOptionPlugin = __webpack_require__(14604); -const RecordIdsPlugin = __webpack_require__(40355); + 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; -const APIPlugin = __webpack_require__(71118); -const ConstPlugin = __webpack_require__(84072); -const CommonJsStuffPlugin = __webpack_require__(85736); -const CompatibilityPlugin = __webpack_require__(85918); + for (const module of modules) { + if (module.id === null && module.libIdent) { + module.id = module.libIdent({ context }); + } -const TemplatedPathPlugin = __webpack_require__(76032); -const WarnCaseSensitiveModulesPlugin = __webpack_require__(40269); -const UseStrictPlugin = __webpack_require__(73554); + if (module.id !== null) { + const namedModule = namedModules.get(module.id); + if (namedModule !== undefined) { + namedModule.push(module); + } else { + namedModules.set(module.id, [module]); + } + } + } -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); + 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()) + )}`; + } + } + } + }); + }); + } +} -const { cachedCleverMerge } = __webpack_require__(67916); +module.exports = NamedModulesPlugin; -/** @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 + "'."); - } +/***/ 22615: +/***/ (function(module) { - 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); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); +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; + }); + }); + } +} - new EntryOptionPlugin().apply(compiler); - compiler.hooks.entryOption.call(options.context, options.entry); +module.exports = NoEmitOnErrorsPlugin; - 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); - } - } - } +/***/ 45759: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (options.performance) { - const SizeLimitsPlugin = __webpack_require__(68310); - new SizeLimitsPlugin(options.performance).apply(compiler); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - new TemplatedPathPlugin().apply(compiler); - new RecordIdsPlugin({ - portableIds: options.optimization.portableRecords - }).apply(compiler); +const WebpackError = __webpack_require__(97391); - new WarnCaseSensitiveModulesPlugin().apply(compiler); +module.exports = class NoModeWarning extends WebpackError { + constructor(modules) { + super(); - if (options.cache) { - const CachePlugin = __webpack_require__(6465); - new CachePlugin( - typeof options.cache === "object" ? options.cache : null - ).apply(compiler); - } + 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/"; - 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; + Error.captureStackTrace(this, this.constructor); } -} - -module.exports = WebpackOptionsApply; +}; /***/ }), -/***/ 60016: +/***/ 28386: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -91227,1515 +84554,1307 @@ module.exports = WebpackOptionsApply; const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); -const OptionsDefaulter = __webpack_require__(3414); -const Template = __webpack_require__(96066); +const NullFactory = __webpack_require__(40438); -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); +class NodeStuffPlugin { + constructor(options) { + this.options = options; } - 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); - } - }); + 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() + ); - 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); + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; - 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"); + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } - 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 - ); + const setConstant = (expressionName, value) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(value) + ); + return true; + }); + }; - 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}` + 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." + ) + ); }; - } - 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"]; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeStuffPlugin", handler); } - }); - 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; +module.exports = NodeStuffPlugin; /***/ }), -/***/ 285: +/***/ 25963: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Gajus Kuizinas @gajus + 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 webpackOptionsSchema = __webpack_require__(37863); +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; -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; +/** @typedef {import("./util/createHash").Hash} Hash */ + +const asString = buf => { + if (Buffer.isBuffer(buf)) { + return buf.toString("utf-8"); } - return schemaPart; + return buf; }; -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}`; +const asBuffer = str => { + if (!Buffer.isBuffer(str)) { + return Buffer.from(str, "utf-8"); } - return schemaText; + return str; }; -const getSchemaPartDescription = schemaPart => { - while (schemaPart.$ref) { - schemaPart = getSchemaPart(schemaPart.$ref); - } - if (schemaPart.description) { - return `\n-> ${schemaPart.description}`; +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); } - 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 -}; +/** + * @typedef {Object} CachedSourceEntry + * @property {TODO} source the generated source + * @property {string} hash the hash value + */ -const filterMax = (array, fn) => { - const max = array.reduce((max, item) => Math.max(max, fn(item)), 0); - return array.filter(item => fn(item) === max); -}; +class NormalModule extends Module { + constructor({ + type, + request, + userRequest, + rawRequest, + loaders, + resource, + matchResource, + parser, + generator, + resolveOptions + }) { + super(type, getContext(resource)); -const filterChildren = children => { - children = filterMax(children, err => - err.dataPath ? err.dataPath.length : 0 - ); - children = filterMax(children, err => SPECIFICITY[err.keyword] || 2); - return children; -}; + // 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; -const indent = (str, prefix, firstLine) => { - if (firstLine) { - return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); - } else { - return str.replace(/\n(?!$)/g, `\n${prefix}`); + // 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 = {}; } -}; -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") - ); + identifier() { + return this.request; + } - this.name = "WebpackOptionsValidationError"; - this.validationErrors = validationErrors; + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); + } - Error.captureStackTrace(this, this.constructor); + libIdent(options) { + return contextify(options.context, this.userRequest); } - static formatSchema(schema, prevSchemas) { - prevSchemas = prevSchemas || []; + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; + } - const formatInnerSchema = (innerSchema, addSelf) => { - if (!addSelf) { - return WebpackOptionsValidationError.formatSchema( - innerSchema, - prevSchemas - ); - } - if (prevSchemas.includes(innerSchema)) { - return "(recursive)"; - } - return WebpackOptionsValidationError.formatSchema( - innerSchema, - prevSchemas.concat(schema) - ); - }; + 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; + } - 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"; + createSourceForAsset(name, content, sourceMap) { + if (!sourceMap) { + return new RawSource(content); } - if (schema.type === "number") { - return "number"; + + if (typeof sourceMap === "string") { + return new OriginalSource(content, sourceMap); } - 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; + + 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() }) - .concat(schema.additionalProperties ? ["…"] : []) - .join(", ")} }`; - } - if (schema.additionalProperties) { - return `object { : ${formatInnerSchema( - schema.additionalProperties - )} }`; - } - return "object"; - } - if (schema.type === "array") { - return `[${formatInnerSchema(schema.items)}]`; - } + ); + }, + 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 + }; - switch (schema.instanceof) { - case "Function": - return "function"; - case "RegExp": - return "RegExp"; + compilation.hooks.normalModuleLoader.call(loaderContext, this); + if (options.loader) { + Object.assign(loaderContext, options.loader); } - if (schema.enum) { - return schema.enum.map(item => JSON.stringify(item)).join(" | "); + 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; + } - if (schema.$ref) { - return formatInnerSchema(getSchemaPart(schema.$ref), true); + createSource(source, resourceBuffer, sourceMap) { + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(source); } - if (schema.allOf) { - return schema.allOf.map(formatInnerSchema).join(" & "); + + // 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 (schema.oneOf) { - return schema.oneOf.map(formatInnerSchema).join(" | "); + + if (this.useSourceMap && sourceMap) { + return new SourceMapSource(source, identifier, sourceMap); } - if (schema.anyOf) { - return schema.anyOf.map(formatInnerSchema).join(" | "); + + 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 JSON.stringify(schema, null, 2); + + return new OriginalSource(source, identifier); } - 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 + 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 ); - return WebpackOptionsValidationError.formatValidationError( - Object.assign({}, lastChild, { - children: remainingChildren, - parentSchema: Object.assign( - {}, - err.parentSchema, - lastChild.parentSchema + } + + 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 children = filterChildren(err.children); - if (children.length === 1) { - return WebpackOptionsValidationError.formatValidationError( - children[0] + + 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); } - return ( - `${dataPath} should be one of these:\n${getSchemaPartText( - err.parentSchema - )}\n` + - `Details:\n${children - .map( - err => - " * " + - indent( - WebpackOptionsValidationError.formatValidationError(err), - " ", - false - ) - ) - .join("\n")}` + + 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(); } - 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." - ); + ); + } + + 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; } - return baseMessage; - } else { - return `${dataPath} ${err.message} (${JSON.stringify( - err, - null, - 2 - )}).\n${getSchemaPartText(err.parentSchema)}`; } + // no match found, so this module !should! be parsed + return false; } -} -module.exports = WebpackOptionsValidationError; + _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(); -/***/ 52337: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // 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(); + }; -const AsyncDependencyToInitialChunkError = __webpack_require__(67089); -const GraphHelpers = __webpack_require__(32973); + 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); + } + }); + } -/** @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 */ + getHashDigest(dependencyTemplates) { + // TODO webpack 5 refactor + let dtHash = dependencyTemplates.get("hash"); + return `${this.hash}-${dtHash}`; + } -/** - * @typedef {Object} QueueItem - * @property {number} action - * @property {DependenciesBlock} block - * @property {Module} module - * @property {Chunk} chunk - * @property {ChunkGroup} chunkGroup - */ + 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; + } -/** - * @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 - */ + const source = this.generator.generate( + this, + dependencyTemplates, + runtimeTemplate, + type + ); -/** - * @typedef {Object} ChunkGroupDep - * @property {AsyncDependenciesBlock} block referencing block - * @property {ChunkGroup} chunkGroup referenced chunk group - */ + const cachedSource = new CachedSource(source); + this._cachedSources.set(type, { + source: cachedSource, + hash: hashDigest + }); + return cachedSource; + } -/** - * @template T - * @param {Set} a first set - * @param {Set} b second set - * @returns {number} cmp - */ -const bySetSize = (a, b) => { - return b.size - a.size; -}; + originalSource() { + return this._source; + } -/** - * 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(); + needRebuild(fileTimestamps, contextTimestamps) { + // always try to rebuild in case of an error + if (this.error) return true; - /** - * @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; + // 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; } - // We skip weak Dependencies - if (ref.weak) { - return; + 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; + } - blockInfoModules.add(refModule); - }; + size() { + if (this._sourceSize === null) { + this._sourceSize = this._source ? this._source.size() : -1; + } + return this._sourceSize; + } /** - * @param {AsyncDependenciesBlock} b blocks to prepare + * @param {Hash} hash the hash used to track dependencies * @returns {void} */ - const iteratorBlockPrepare = b => { - blockInfoBlocks.push(b); - blockQueue.push(b); - }; + updateHash(hash) { + hash.update(this._buildHash); + super.updateHash(hash); + } +} - /** @type {Module} */ - let currentModule; - /** @type {DependenciesBlock} */ - let block; - /** @type {DependenciesBlock[]} */ - let blockQueue; - /** @type {Set} */ - let blockInfoModules; - /** @type {AsyncDependenciesBlock[]} */ - let blockInfoBlocks; +module.exports = NormalModule; - 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); - } +/***/ 22298: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (block.blocks) { - for (const b of block.blocks) iteratorBlockPrepare(b); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - const blockInfo = { - modules: blockInfoModules, - blocks: blockInfoBlocks - }; - blockInfoMap.set(block, blockInfo); - } - } - return blockInfoMap; -}; +const path = __webpack_require__(85622); +const asyncLib = __webpack_require__(36386); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = __webpack_require__(56758); +const NormalModule = __webpack_require__(25963); +const RawModule = __webpack_require__(82353); +const RuleSet = __webpack_require__(84247); +const { cachedCleverMerge } = __webpack_require__(67916); -/** - * - * @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; +const EMPTY_RESOLVE_OPTIONS = {}; - logger.time("prepare"); - const blockInfoMap = extraceBlockInfoMap(compilation); +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; - /** @type {Map} */ - const chunkGroupCounters = new Map(); - for (const chunkGroup of inputChunkGroups) { - chunkGroupCounters.set(chunkGroup, { - index: 0, - index2: 0 - }); +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); +}; - let nextFreeModuleIndex = 0; - let nextFreeModuleIndex2 = 0; - - /** @type {Map} */ - const blockChunkGroups = new Map(); +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 ADD_AND_ENTER_MODULE = 0; - const ENTER_MODULE = 1; - const PROCESS_BLOCK = 2; - const LEAVE_MODULE = 3; +const dependencyCache = new WeakMap(); - /** - * @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); +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; } - } 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 }); - }; + 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); - // 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; - } + // Ignored + if (!resolver) return callback(); - 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++ - ); - } - } + resolver(result, (err, data) => { + if (err) return callback(err); - if (module.index === null) { - module.index = nextFreeModuleIndex++; - } + // Ignored + if (!data) return callback(); - queue.push({ - action: LEAVE_MODULE, - block, - module, - chunk, - chunkGroup - }); - } - // fallthrough - case PROCESS_BLOCK: { - // get prepared block info - const blockInfo = blockInfoMap.get(block); + // direct module + if (typeof data.source === "function") return callback(null, data); - // 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]); - } + this.hooks.afterResolve.callAsync(data, (err, result) => { + if (err) return callback(err); - // Traverse all Blocks - for (const block of blockInfo.blocks) iteratorBlock(block); + // Ignored + if (!result) return callback(); - 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++ - ); + let createdModule = this.hooks.createModule.call(result); + if (!createdModule) { + if (!result.request) { + return callback(new Error("Empty dependency (no request)")); } - } - if (module.index2 === null) { - module.index2 = nextFreeModuleIndex2++; + createdModule = new NormalModule(result); } - break; - } - } - } - logger.timeEnd("visiting"); - while (queueConnect.size > 0) { - logger.time("calculating available modules"); + createdModule = this.hooks.module.call(createdModule, result); - // 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; + return callback(null, createdModule); + }); + }); + }); + this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { + const contextInfo = data.contextInfo; + const context = data.context; + const request = data.request; - // 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); - } - } + const loaderResolver = this.getResolver("loader"); + const normalResolver = this.getResolver("normal", data.resolveOptions); - // 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); + 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 + ); } - 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; - } + 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); - changed = true; - break; - } - } - } + asyncLib.parallel( + [ + callback => + this.resolveRequestArray( + contextInfo, + context, + elements, + loaderResolver, + callback + ), + callback => { + if (resource === "" || resource[0] === "?") { + return callback(null, { + resource + }); } - } - availableModulesToBeMerged.length = 0; - if (!changed) continue; - // 2. Reconsider skipped items - for (const queueItem of info.skippedItems) { - queue.push(queueItem); + normalResolver.resolve( + contextInfo, + context, + resource, + {}, + (err, resource, resourceResolveData) => { + if (err) return callback(err); + callback(null, { + resourceResolveData, + resource + }); + } + ); } - info.skippedItems.length = 0; + ], + (err, results) => { + if (err) return callback(err); + let loaders = results[0]; + const resourceResolveData = results[1].resourceResolveData; + resource = results[1].resource; - // 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); + // 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; } - connectList.add(c); } + } catch (e) { + return callback(e); } - } - 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; - } - } -}; + if (resource === false) { + // ignored + return callback( + null, + new RawModule( + "/* (ignored) */", + `ignored ${context} ${request}`, + `${request} (ignored)` + ) + ); + } -/** - * - * @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; + const userRequest = + (matchResource !== undefined ? `${matchResource}!=!` : "") + + loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"); - /** - * 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; - }; + let resourcePath = + matchResource !== undefined ? matchResource : resource; + let resourceQuery = ""; + const queryIndex = resourcePath.indexOf("?"); + if (queryIndex >= 0) { + resourceQuery = resourcePath.substr(queryIndex); + resourcePath = resourcePath.substr(0, queryIndex); + } - // 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; - }; + 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 + }); + }); + } + ); + } + ); + }); + } - // For all deps, check if chunk groups need to be connected - for (const [chunkGroup, deps] of chunkDependencies) { - if (deps.length === 0) continue; + 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); - // 1. Get info from chunk group info map - const info = chunkGroupInfoMap.get(chunkGroup); - resultingAvailableModules = info.resultingAvailableModules; + // Ignored + if (!result) return callback(); - // 2. Foreach edge - for (let i = 0; i < deps.length; i++) { - const dep = deps[i]; + const factory = this.hooks.factory.call(null); - // Filter inline, rather than creating a new array from `.filter()` - // TODO check if inlining filterFn makes sense here - if (!filterFn(dep)) { - continue; + // 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); + }); } - const depChunkGroup = dep.chunkGroup; - const depBlock = dep.block; + ); + } - // 5. Connect block with chunk - GraphHelpers.connectDependenciesBlockAndChunkGroup( - depBlock, - depChunkGroup - ); + 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); - // 6. Connect chunk with parent - GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); + 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)); } -}; -/** - * 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"); + 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]); } - chunkGroup.remove("unconnected"); } + if (ident in this.generatorCache) { + return this.generatorCache[ident]; + } + return (this.generatorCache[ident] = this.createGenerator( + type, + generatorOptions + )); } -}; -/** - * 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 + 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; + } - /** @type {Map} */ - const chunkDependencies = new Map(); + getResolver(type, resolveOptions) { + return this.resolverFactory.get( + type, + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + } +} - /** @type {Set} */ - const allCreatedChunkGroups = new Set(); +module.exports = NormalModuleFactory; - /** @type {Map} */ - const chunkGroupInfoMap = new Map(); - /** @type {Set} */ - const blocksWithNestedBlocks = new Set(); +/***/ }), - // PART ONE +/***/ 73253: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - visitModules( - compilation, - inputChunkGroups, - chunkGroupInfoMap, - chunkDependencies, - blocksWithNestedBlocks, - allCreatedChunkGroups - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // PART TWO - connectChunkGroups( - blocksWithNestedBlocks, - chunkDependencies, - chunkGroupInfoMap - ); +const path = __webpack_require__(85622); - // Cleaup work +class NormalModuleReplacementPlugin { + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } - cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); -}; + 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 = buildChunkGraph; +module.exports = NormalModuleReplacementPlugin; /***/ }), -/***/ 22562: +/***/ 40438: /***/ (function(module) { "use strict"; @@ -92745,2756 +85864,2647 @@ module.exports = buildChunkGraph; */ -/** @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; - } +class NullFactory { + create(data, callback) { + return callback(); } -}; +} +module.exports = NullFactory; /***/ }), -/***/ 72890: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -const fs = __webpack_require__(35747); -const path = __webpack_require__(85622); -const mkdirp = __webpack_require__(50998); -const { Tracer } = __webpack_require__(92430); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(49049); +/***/ 4428: +/***/ (function(module) { -/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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 OptionsApply { + process(options, compiler) {} } +module.exports = OptionsApply; -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") - ]); - } +/***/ 3414: +/***/ (function(module) { - 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(); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - destroy() { - if (this.hasSession()) { - this.session.disconnect(); - } - return Promise.resolve(); +/** + * 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()]; +}; - stopProfiling() { - return this.sendCommand("Profiler.stop"); +/** + * 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; +}; /** - * 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 + * @typedef {'call' | 'make' | 'append'} ConfigType */ - /** - * @param {string} outputPath The location where to write the log. - * @returns {Trace} The trace object + * @typedef {(options: object) => any} MakeConfigHandler + */ +/** + * @typedef {(value: any, options: object) => any} CallConfigHandler + */ +/** + * @typedef {any[]} AppendConfigValues */ -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; +class OptionsDefaulter { + constructor() { + /** + * Stores default options settings or functions for computing them + */ + this.defaults = {}; + /** + * Stores configuration for options + * @type {{[key: string]: ConfigType}} + */ + this.config = {}; + } - 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: "" + /** + * 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]); } - ] - } - } - }); - - trace.instantEvent({ - name: "TracingStartedInBrowser", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1" + 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 { - 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"; + return options; + } -class ProfilingPlugin { /** - * @param {ProfilingPluginOptions=} opts options object + * 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} */ - constructor(opts) { - validateOptions(schema, opts || {}, "Profiling plugin"); - opts = opts || {}; - this.outputPath = opts.outputPath || "events.json"; + set(name, config, def) { + if (def !== undefined) { + this.defaults[name] = def; + this.config[name] = config; + } else { + this.defaults[name] = config; + delete this.config[name]; + } } +} - 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); - } - ); +module.exports = OptionsDefaulter; - // 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" - } - }); +/***/ 70558: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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" - } - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); - }); - } - ); - } -} +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API -const interceptTemplateInstancesFrom = (compilation, tracer) => { - const { - mainTemplate, - chunkTemplate, - hotUpdateChunkTemplate, - moduleTemplates - } = compilation; +const acorn = __webpack_require__(77087); +const { Tapable, SyncBailHook, HookMap } = __webpack_require__(56758); +const util = __webpack_require__(31669); +const vm = __webpack_require__(92184); +const BasicEvaluatedExpression = __webpack_require__(96770); +const StackedSetMap = __webpack_require__(92251); - const { javascript, webassembly } = moduleTemplates; +const acornParser = acorn.Parser; - [ - { - 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 joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; }; -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 defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: 11, + sourceType: "module", + onComment: null }; -const interceptAllParserHooks = (moduleFactory, tracer) => { - const moduleTypes = [ - "javascript/auto", - "javascript/dynamic", - "javascript/esm", - "json", - "webassembly/experimental" - ]; +// regexp to match at least one "magic comment" +const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); - moduleTypes.forEach(moduleType => { - moduleFactory.hooks.parser - .for(moduleType) - .tap("ProfilingPlugin", (parser, parserOpts) => { - interceptAllHooksFor(parser, tracer, "Parser"); - }); - }); +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null }; -const makeInterceptorFor = (instance, tracer) => hookName => ({ - register: ({ name, type, context, fn }) => { - const newFn = makeNewProfiledTapFn(hookName, tracer, { - name, - type, - fn - }); - return { - name, - type, - context, - fn: newFn +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"]) }; - } -}); - -// 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: -/***/ (function(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__))` - ] + 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 (.+)$/ }; - } - - 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: -/***/ (function(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); + 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; } - }); - 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; + }); + this.options = options; + this.sourceType = sourceType; + this.scope = undefined; + this.state = undefined; + this.comments = undefined; + this.initializeEvaluating(); } - 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; - } + 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); } - } - 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; - }); + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); } - } 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; - }); + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); } - } - 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); + }); + 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); } - } 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: -/***/ (function(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) + }); + 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 ); - parser.hooks.evaluateTypeof - .for("require.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToString(typeof amdOptions) + } 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 ); - parser.hooks.evaluateIdentifier - .for("define.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToIdentifier("define.amd", true) + } 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 ); - parser.hooks.evaluateIdentifier - .for("require.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToIdentifier("require.amd", true) + } 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 ); - parser.hooks.typeof - .for("define") - .tap( - "AMDPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) + } 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) ); - 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 + } 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] + ) ); - 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") - ) + } + } 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 + ) ); - 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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const Dependency = __webpack_require__(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); + } 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; + } }); - 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 + 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); }); - } - } -}; - -module.exports = AMDRequireArrayDependency; - - -/***/ }), - -/***/ 99890: -/***/ (function(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; + ["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]; -/***/ 32894: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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 -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 AsyncDependenciesBlock = __webpack_require__(22814); -const AMDRequireDependency = __webpack_require__(73985); + const part = new BasicEvaluatedExpression() + .setString(quasi) + .setRange(quasiExpr.range) + .setExpression(quasiExpr); + quasis.push(part); + parts.push(part); + } + return { + quasis, + parts + }; + }; -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); - } + 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); + }); - newRequireDependency() { - return new AMDRequireDependency(this); - } -}; + 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; -/***/ 9994: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setRange(newRange); + } -"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); - } + 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); } - ); - 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); + }); + 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 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); + 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 { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); + res.setOptions([consequent]); } - deps.push(dep); + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); } - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + 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; } } - 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); + + 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); } } - 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; + this.scope.topLevelScope = wasTopLevel; } } - 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(" "); + walkMethodDefinition(methodDefinition) { + if (methodDefinition.computed && methodDefinition.key) { + this.walkExpression(methodDefinition.key); + } + if (methodDefinition.value) { + this.walkExpression(methodDefinition.value); } } - processItemForRequestString(param) { - if (param.isConditional()) { - const result = param.options.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join("|"); - } else if (param.isString()) { - return param.string; + // 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); } } - 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; + // 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); } + } - 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; + // 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); } + } - 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; + 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; } } - 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); + 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; + } } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); + + 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; + } } -} -module.exports = AMDRequireDependenciesBlockParserPlugin; + // Real Statements + prewalkBlockStatement(statement) { + this.prewalkStatements(statement.body); + } -/***/ }), + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + this.blockPrewalkStatements(body); + this.walkStatements(body); + }); + } -/***/ 73985: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + prewalkIfStatement(statement) { + this.prewalkStatement(statement.consequent); + if (statement.alternate) { + this.prewalkStatement(statement.alternate); + } + } -const NullDependency = __webpack_require__(5088); - -class AMDRequireDependency extends NullDependency { - constructor(block) { - super(); - this.block = block; + 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); + } + } } -} -AMDRequireDependency.Template = class AMDRequireDependencyTemplate { - apply(dep, source, runtime) { - const depBlock = dep.block; - const promise = runtime.blockPromise({ - block: depBlock, - message: "AMD require" - }); + prewalkLabeledStatement(statement) { + this.prewalkStatement(statement.body); + } - // 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; + 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); + } - // 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; - } + prewalkWithStatement(statement) { + this.prewalkStatement(statement.body); + } - // 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)" : "" - })`; + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkStatement(statement.body); + } - 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; - } + prewalkSwitchStatement(statement) { + this.prewalkSwitchCases(statement.cases); + } - // 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 - ); - } + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); } -}; -module.exports = AMDRequireDependency; + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); + } + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } -/***/ }), + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } -/***/ 34345: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + prewalkTryStatement(statement) { + this.prewalkStatement(statement.block); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); + } -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); + prewalkWhileStatement(statement) { + this.prewalkStatement(statement.body); + } -class AMDRequireItemDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkStatement(statement.body); } - get type() { - return "amd require"; + prewalkDoWhileStatement(statement) { + this.prewalkStatement(statement.body); } -} -AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + walkDoWhileStatement(statement) { + this.walkStatement(statement.body); + this.walkExpression(statement.test); + } -module.exports = AMDRequireItemDependency; + 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); + } -/***/ 85358: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } + }); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + prewalkForOfStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.prewalkVariableDeclaration(statement.left); + } + this.prewalkStatement(statement.body); + } -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); + 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); + } + }); + } -const NullFactory = __webpack_require__(40438); + // Declarations + prewalkFunctionDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); + } + } -const RequireResolveDependencyParserPlugin = __webpack_require__(68349); -const CommonJsRequireDependencyParserPlugin = __webpack_require__(37278); + 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; + } -const ParserHelpers = __webpack_require__(23999); + 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; + } + } + } -class CommonJsPlugin { - constructor(options) { - this.options = options; + 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; + } } - 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() - ); + blockPrewalkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.blockPrewalkStatement(statement.declaration); + } + } - compilation.dependencyFactories.set( - CommonJsRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireContextDependency, - new CommonJsRequireContextDependency.Template() - ); + 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; + } + } + } + } + } - compilation.dependencyFactories.set( - RequireResolveDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveDependency, - new RequireResolveDependency.Template() - ); + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } + } - compilation.dependencyFactories.set( - RequireResolveContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveContextDependency, - new RequireResolveContextDependency.Template() - ); + blockPrewalkExportDefaultDeclaration(statement) { + if (statement.declaration.type === "ClassDeclaration") { + this.blockPrewalkClassDeclaration(statement.declaration); + } + } - compilation.dependencyFactories.set( - RequireResolveHeaderDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - RequireResolveHeaderDependency, - new RequireResolveHeaderDependency.Template() - ); + 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" + ); + } + } - compilation.dependencyFactories.set( - RequireHeaderDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - RequireHeaderDependency, - new RequireHeaderDependency.Template() + 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" ); + } + } + } - const handler = (parser, parserOptions) => { - if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) - return; + prewalkExportAllDeclaration(statement) { + const source = statement.source.value; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); + } - 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) - ); - } + prewalkVariableDeclaration(statement) { + if (statement.kind !== "var") return; + this._prewalkVariableDeclaration(statement, this.hooks.varDeclarationVar); + } - 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")); + blockPrewalkVariableDeclaration(statement) { + if (statement.kind === "var") return; + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : this.hooks.varDeclarationLet; + this._prewalkVariableDeclaration(statement, hookMap); + } - new CommonJsRequireDependencyParserPlugin(options).apply(parser); - new RequireResolveDependencyParserPlugin(options).apply(parser); - }; + _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; + } + } + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CommonJsPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CommonJsPlugin", handler); + 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; + } } - ); + } } -} -module.exports = CommonJsPlugin; + 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); + } -/***/ 26791: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + prewalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.prewalkStatements(switchCase.consequent); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; -const ContextDependency = __webpack_require__(11583); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + this.walkStatements(switchCase.consequent); + } + } -class CommonJsRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - this.range = range; - this.valueRange = valueRange; + 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); + }); } - get type() { - return "cjs require context"; + 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; + } } -} -CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } -module.exports = CommonJsRequireContextDependency; + 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); + } -/***/ 37504: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + } + } -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsId = __webpack_require__(63708); + walkAwaitExpression(expression) { + this.walkExpression(expression.argument); + } -class CommonJsRequireDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } } - get type() { - return "cjs require"; + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } } -} -CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + 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; + } + } + } -module.exports = CommonJsRequireDependency; + 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; + } -/***/ 37278: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + } + }); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkSequenceExpression(expression) { + if (expression.expressions) this.walkExpressions(expression.expressions); + } + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } -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); + 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); + } -class CommonJsRequireDependencyParserPlugin { - constructor(options) { - this.options = options; + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); } - apply(parser) { - const options = this.options; + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); + } - 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; + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else { + if (result) { + this.walkExpression(expression.right); } - }; - 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; + 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 ( - 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; + } + if (expression.left.type === "Identifier") { + const assignedHook = this.hooks.assigned.get(expression.left.name); + if (assignedHook === undefined || !assignedHook.call(expression)) { + this.walkExpression(expression.right); } - }; - 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)); + 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); + }); } -} -module.exports = CommonJsRequireDependencyParserPlugin; - - -/***/ }), -/***/ 71101: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + } -const NullDependency = __webpack_require__(5088); + 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; + } + } + } -class ConstDependency extends NullDependency { - constructor(expression, range, requireWebpackRequire) { - super(); - this.expression = expression; - this.range = range; - this.requireWebpackRequire = requireWebpackRequire; + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } } - updateHash(hash) { - hash.update(this.range + ""); - hash.update(this.expression + ""); + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } } -} -ConstDependency.Template = class ConstDependencyTemplate { - apply(dep, source) { - if (typeof dep.range === "number") { - source.insert(dep.range, dep.expression); - return; + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); } - - source.replace(dep.range[0], dep.range[1] - 1, dep.expression); } -}; -module.exports = ConstDependency; + 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]); -/***/ 11583: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Add function name in scope for recursive calls + if (functionExpression.id) { + scopeParams.push(functionExpression.id.name); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + } -const Dependency = __webpack_require__(57282); -const CriticalDependencyWarning = __webpack_require__(54983); + 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; -const regExpToString = r => (r ? r + "" : ""); + 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; + } + } + } -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; + if (expression.callee) this.walkExpression(expression.callee); + if (expression.arguments) this.walkExpressions(expression.arguments); } } - 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)}` - ); + 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); } - getWarnings() { - let warnings = super.getWarnings() || []; - if (this.critical) { - warnings.push(new CriticalDependencyWarning(this.critical)); + walkThisExpression(expression) { + const expressionHook = this.hooks.expression.get("this"); + if (expressionHook !== undefined) { + expressionHook.call(expression); } - if (this.hadGlobalOrStickyRegExp) { - warnings.push( - new CriticalDependencyWarning( - "Contexts can't use RegExps with the 'g' or 'y' flags." - ) + } + + 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; + } } - 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" - ); - } -}); + /** + * @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() + }; -module.exports = ContextDependency; + this.scope.renames.set("this", null); + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); -/***/ }), + fn(); -/***/ 5594: -/***/ (function(__unused_webpack_module, exports) { + this.scope = oldScope; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); + } -const ContextDependencyHelpers = exports; + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quotemeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; + fn(); -const splitContextFromPrefix = prefix => { - const idx = prefix.lastIndexOf("/"); - let context = "."; - if (idx >= 0) { - context = prefix.substr(0, idx); - prefix = `.${prefix.substr(idx)}`; + this.scope = oldScope; } - 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 - }; -}; + 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() + }; -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 - : ""; + fn(); - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { postfix, query } = splitQueryFromPostfix(postfixRaw); + this.scope = oldScope; + } - // 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(""); + // TODO webpack 5: remove this methods + // only for backward-compat + detectStrictMode(statements) { + this.detectMode(statements); + } - // 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) - }); + 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 (postfixRange) { - replaces.push({ - range: postfixRange, - value: JSON.stringify(postfix) - }); + if (isLiteral && statements[0].expression.value === "use asm") { + this.scope.isAsmJs = true; } - 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); + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); } } + } - 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); + 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; } - - return dep; } -}; + enterIdentifier(pattern, onIdent) { + onIdent(pattern.name, pattern); + } -/***/ }), - -/***/ 6174: -/***/ (function(module) { + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); + } -class ContextDependencyTemplateAsId { - apply(dep, source, runtime) { - const moduleExports = runtime.moduleExports({ - module: dep.module, - request: dep.request - }); + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } - 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); + 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; } - 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); + } catch (e) { + console.warn(e); + // ignore error } + return new BasicEvaluatedExpression() + .setRange(expression.range) + .setExpression(expression); } -} -module.exports = ContextDependencyTemplateAsId; + 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" + ); + } -/***/ }), - -/***/ 54380: -/***/ (function(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); + 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 + }; } } - 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); + 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 + }; } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; } -} -module.exports = ContextDependencyTemplateAsRequireCall; - - -/***/ }), -/***/ 89079: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const ModuleDependency = __webpack_require__(90865); + 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 + }); + } -class ContextElementDependency extends ModuleDependency { - constructor(request, userRequest) { - super(request); - if (userRequest) { - this.userRequest = userRequest; + 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; } - get type() { - return "context element"; + 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); } -} - -module.exports = ContextElementDependency; - - -/***/ }), - -/***/ 54983: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); - -class CriticalDependencyWarning extends WebpackError { - constructor(message) { - super(); - this.name = "CriticalDependencyWarning"; - this.message = "Critical dependency: " + message; - - Error.captureStackTrace(this, this.constructor); + getComments(range) { + return this.comments.filter( + comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] + ); } -} - -module.exports = CriticalDependencyWarning; - -/***/ }), - -/***/ 53104: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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 }; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 + ); -const DependencyReference = __webpack_require__(71722); -const NullDependency = __webpack_require__(5088); + if (type === "auto") { + parserOptions.sourceType = "module"; + } else if (parserOptions.sourceType === "script") { + parserOptions.allowReturnOutsideFunction = true; + } -class DelegatedExportsDependency extends NullDependency { - constructor(originModule, exports) { - super(); - this.originModule = originModule; - this.exports = exports; - } + let ast; + let error; + let threw = false; + try { + ast = acornParser.parse(code, parserOptions); + } catch (e) { + error = e; + threw = true; + } - get type() { - return "delegated exports"; - } + 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; + } + } - getReference() { - return new DependencyReference(this.originModule, true, false); - } + if (threw) { + throw error; + } - getExports() { - return { - exports: this.exports, - dependencies: undefined - }; + return ast; } } -module.exports = DelegatedExportsDependency; +// 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; /***/ }), -/***/ 25930: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 23999: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -95502,96 +88512,109 @@ module.exports = DelegatedExportsDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); +const path = __webpack_require__(85622); -class DelegatedSourceDependency extends ModuleDependency { - constructor(request) { - super(request); - } +const BasicEvaluatedExpression = __webpack_require__(96770); +const ConstDependency = __webpack_require__(71101); +const UnsupportedFeatureWarning = __webpack_require__(99953); - get type() { - return "delegated source"; - } -} +const ParserHelpers = exports; -module.exports = DelegatedSourceDependency; +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; + }; +}; -/***/ 71722: -/***/ (function(module) { +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; + }; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ +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); + }; +}; -/** @typedef {import("../Module")} Module */ +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; + }; +}; -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; - } +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; + }; +}; - /** - * @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; - }); - } -} +ParserHelpers.skipTraversal = function skipTraversal() { + return true; +}; -module.exports = DependencyReference; +ParserHelpers.approve = function approve() { + return true; +}; /***/ }), -/***/ 66279: +/***/ 27850: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95600,26 +88623,43 @@ module.exports = DependencyReference; Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(57282); +const PrefetchDependency = __webpack_require__(14237); -class DllEntryDependency extends Dependency { - constructor(dependencies, name) { - super(); - this.dependencies = dependencies; - this.name = name; +class PrefetchPlugin { + constructor(context, request) { + if (!request) { + this.request = context; + } else { + this.context = context; + this.request = request; + } } - get type() { - return "dll entry"; + 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 = DllEntryDependency; +module.exports = PrefetchPlugin; /***/ }), -/***/ 75159: +/***/ 63123: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95629,123 +88669,312 @@ module.exports = DllEntryDependency; */ -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; - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(26336); - get type() { - return "accepted harmony modules"; - } -} +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ -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(""); +const createDefaultHandler = (profile, logger) => { + let lastState; + let lastStateTime; - if (dep.hasCallback) { - source.insert( - dep.range[0], - `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` - ); - source.insert( - dep.range[1], - ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" - ); - return; + 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(); + }; - source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); - } + return defaultHandler; }; -module.exports = HarmonyAcceptDependency; - - -/***/ }), - -/***/ 66136: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +class ProgressPlugin { + /** + * @param {ProgressPluginArgument} options options + */ + constructor(options) { + if (typeof options === "function") { + options = { + handler: options + }; + } -const HarmonyImportDependency = __webpack_require__(81599); + options = options || {}; + validateOptions(schema, options, "Progress Plugin"); + options = Object.assign({}, ProgressPlugin.defaultOptions, options); -class HarmonyAcceptImportDependency extends HarmonyImportDependency { - constructor(request, originModule, parserScope) { - super(request, originModule, NaN, parserScope); - this.weak = true; + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showActiveModules = options.activeModules; } - get type() { - return "harmony accept"; - } -} + 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 = ""; -HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { - apply(dep, source, runtime) {} -}; + const update = () => { + const percentByModules = + doneModules / Math.max(lastModulesCount, moduleCount); + const percentByEntries = + doneEntries / Math.max(lastEntriesCount, entriesCount); -module.exports = HarmonyAcceptImportDependency; + 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(); + }; -/***/ 1533: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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(); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const entryDone = (entry, name) => { + doneEntries++; + update(); + }; -const NullDependency = __webpack_require__(5088); + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = moduleCount; + lastEntriesCount = entriesCount; + moduleCount = entriesCount = 0; + doneModules = doneEntries = 0; + handler(0, "compiling"); -class HarmonyCompatibilityDependency extends NullDependency { - constructor(originModule) { - super(); - this.originModule = originModule; - } + compilation.hooks.buildModule.tap("ProgressPlugin", moduleAdd); + compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); + compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); - get type() { - return "harmony export header"; - } -} + compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); + compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); + compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); -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 + 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, ""); }); - source.insert(-10, content); } } +} + +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 500, + modules: true, + activeModules: true, + // TODO webpack 5 default this to true + entries: false }; -module.exports = HarmonyCompatibilityDependency; +module.exports = ProgressPlugin; /***/ }), -/***/ 59310: +/***/ 72861: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95755,101 +88984,91 @@ module.exports = HarmonyCompatibilityDependency; */ -const HarmonyCompatibilityDependency = __webpack_require__(1533); -const HarmonyInitDependency = __webpack_require__(27204); +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); -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" +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() ); - 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 + 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; + }); + }); }; - 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; - } - }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ProvidePlugin", handler); - const nullInHarmony = () => { - const module = parser.state.module; - if (module && module.buildMeta && module.buildMeta.exportsType) { - return null; + // Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032 } - }; - - 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); - } + ); } -}; +} +module.exports = ProvidePlugin; /***/ }), -/***/ 49180: +/***/ 82353: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95859,225 +89078,61 @@ module.exports = class HarmonyDetectionParserPlugin { */ -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); +const Module = __webpack_require__(75993); +const { OriginalSource, RawSource } = __webpack_require__(53665); -module.exports = class HarmonyExportDependencyParserPlugin { - constructor(moduleOptions) { - this.strictExportPresence = moduleOptions.strictExportPresence; +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; } - 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; - } - ); + identifier() { + return this.identifierStr; } -}; - - -/***/ }), -/***/ 84245: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + size() { + return this.sourceStr.length; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); + } -const NullDependency = __webpack_require__(5088); + needRebuild() { + return false; + } -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 + build(options, compilations, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + cacheable: true }; + callback(); } -} - -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() { + if (this.useSourceMap) { + return new OriginalSource(this.sourceStr, this.identifier()); + } else { + return new RawSource(this.sourceStr); } - - 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 = "; + updateHash(hash) { + hash.update(this.sourceStr); + super.updateHash(hash); } }; -module.exports = HarmonyExportExpressionDependency; - /***/ }), -/***/ 21320: +/***/ 40355: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96086,36 +89141,261 @@ module.exports = HarmonyExportExpressionDependency; Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); -class HarmonyExportHeaderDependency extends NullDependency { - constructor(range, rangeStatement) { - super(); - this.range = range; - this.rangeStatement = rangeStatement; +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 || {}; } - get type() { - return "harmony export header"; + /** + * @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; -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); + +/***/ }), + +/***/ 15377: +/***/ (function(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); } }; -module.exports = HarmonyExportHeaderDependency; - /***/ }), -/***/ 22864: +/***/ 54254: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96125,843 +89405,819 @@ module.exports = HarmonyExportHeaderDependency; */ -const DependencyReference = __webpack_require__(71722); -const HarmonyImportDependency = __webpack_require__(81599); -const Template = __webpack_require__(96066); -const HarmonyLinkingError = __webpack_require__(30327); +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 = /!=!/; -/** @typedef {import("../Module")} Module */ +const normalizeBackSlashDirection = request => { + return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); +}; -/** @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 */ +const createRegExpForPath = path => { + const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); + return new RegExp(`(^|!)${regexpTypePartial}`, "g"); +}; -/** @type {Map} */ -const EMPTY_MAP = new Map(); +class RequestShortener { + constructor(directory) { + directory = normalizeBackSlashDirection(directory); + if (SEPARATOR_REGEXP.test(directory)) { + directory = directory.substr(0, directory.length - 1); + } -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; - } -} + if (directory) { + this.currentDirectoryRegExp = createRegExpForPath(directory); + } -const EMPTY_STAR_MODE = new ExportMode("empty-star"); + 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}/`); + } -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; - } + 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); + } - get type() { - return "harmony export imported specifier"; + this.cache = new Map(); } - get _id() { - return this.redirectedId || this.id; + 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; } +} - getMode(ignoreUnused) { - const name = this.name; - const id = this._id; - const used = this.originModule.isUsed(name); - const importedModule = this._module; +module.exports = RequestShortener; - 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; - } - } +/***/ 88226: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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]) +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; - if (map.size === 0) { - return EMPTY_STAR_MODE; - } + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); - const mode = new ExportMode("safe-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; + 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); } + ); + } +}; - 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; - } +/***/ 50588: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const mode = new ExportMode("checked-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - 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]) - ); +const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(56758); +const Factory = __webpack_require__(87450).ResolverFactory; +const { cachedCleverMerge } = __webpack_require__(67916); - if (map.size === 0) { - return EMPTY_STAR_MODE; +/** @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(); + } - const mode = new ExportMode("safe-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; - } + 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; + } - const mode = new ExportMode("dynamic-reexport"); - mode.module = importedModule; - mode.ignored = new Set([ - "default", - ...this.activeExports, - ...activeFromOtherStarExports - ]); - return mode; + _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; } +}; - 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 - ); +/***/ 84247: +/***/ (function(module) { - 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 - ); +"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: [ + + ] +} - case "safe-reexport": - case "checked-reexport": - return new DependencyReference( - mode.module, - Array.from(mode.map.values()), - false, - this.sourceOrder - ); +: /regExp/ +: function(arg) {} +: "starting" +: [] // or +: { and: [] } +: { or: [] } +: { not: [] } +: { test: , include: , exclude: } - case "dynamic-reexport": - return new DependencyReference( - mode.module, - true, - false, - this.sourceOrder - ); - default: - throw new Error(`Unknown mode ${mode.type}`); - } - } +normalized: - _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); - } - } +{ + resource: function(), + resourceQuery: function(), + compiler: function(), + issuer: function(), + use: [ + { + loader: string, + options: string, + : } - return result; - } + ], + rules: [], + oneOf: [], + : , +} - 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] - }; +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; + }; +}; - if (importedModule.buildMeta.providedExports) { - return { - exports: true, - dependencies: undefined - }; +const andMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (!items[i](str)) return false; } + return true; + }; +}; - return { - exports: null, - dependencies: [importedModule] - }; +module.exports = class RuleSet { + constructor(rules) { + this.references = Object.create(null); + this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); } - getWarnings() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { + 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 []; } - return this._getErrors(); } - getErrors() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return this._getErrors(); + static normalizeRule(rule, refs, ident) { + if (typeof rule === "string") { + return { + use: [ + { + loader: rule + } + ] + }; } - return []; - } - - _getErrors() { - const importedModule = this._module; - if (!importedModule) { - return; + 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 + + ")" + ); } - 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)` + 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)); } - return; } - if (!this._id) { - return; + if (rule.resource) { + checkResourceSource("resource"); + try { + newRule.resource = RuleSet.normalizeCondition(rule.resource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); + } } - if (importedModule.isProvided(this._id) !== false) { - // It's provided or we are not sure - return; + if (rule.realResource) { + try { + newRule.realResource = RuleSet.normalizeCondition(rule.realResource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); + } } - // 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 ""; + if (rule.resourceQuery) { + try { + newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); + } } - 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; + if (rule.compiler) { + try { + newRule.compiler = RuleSet.normalizeCondition(rule.compiler); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); } } - 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 - ) - ); + if (rule.issuer) { + try { + newRule.issuer = RuleSet.normalizeCondition(rule.issuer); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + } + } - case "rexport-non-harmony-undefined": - return ( - "/* harmony reexport (non default export from non-harmony) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - "undefined", - "" + if (rule.loader && rule.loaders) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Provided loader and loaders for rule (use only one of them)" ) - ); + ) + ); + } - case "reexport-non-harmony-default-strict": - return ( - "/* harmony reexport (default from non-harmony) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - "" + 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)" ) - ); - - case "reexport-namespace-object": - return ( - "/* harmony reexport (module object) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - "" + ) + ); + } 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)" ) - ); + ) + ); + } - case "empty-star": - return "/* empty/unused harmony star reexport */"; + if (rule.use) { + checkUseSource("use"); + newRule.use = RuleSet.normalizeUse(rule.use, ident); + } - 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(""); + if (rule.rules) { + newRule.rules = RuleSet.normalizeRules( + rule.rules, + refs, + `${ident}-rules` + ); + } - 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(""); + if (rule.oneOf) { + newRule.oneOf = RuleSet.normalizeRules( + rule.oneOf, + refs, + `${ident}-oneOf` + ); + } - case "dynamic-reexport": { - const ignoredExports = mode.ignored; - let content = - "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + - importVar + - ") "; + 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]; + } - // 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') "; + if (Array.isArray(newRule.use)) { + for (const item of newRule.use) { + if (item.ident) { + refs[item.ident] = item.options; } - 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`; + return newRule; } - 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`; + static buildErrorMessage(condition, error) { + const conditionAsText = JSON.stringify( + condition, + (key, value) => { + return value === undefined ? "undefined" : value; + }, + 2 + ); + return error.message + " in " + conditionAsText; } - getReturnValue(name, valueKey) { - if (valueKey === null) { - return `${name}_default.a`; - } - if (valueKey === "") { - return name; + static normalizeUse(use, ident) { + if (typeof use === "function") { + return data => RuleSet.normalizeUse(use(data), ident); } - if (valueKey === false) { - return "/* unused export */ undefined"; + if (Array.isArray(use)) { + return use + .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) + .reduce((arr, items) => arr.concat(items), []); } - - return `${name}[${JSON.stringify(valueKey)}]`; - } -}; - - -/***/ }), - -/***/ 34834: -/***/ (function(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"; + return [RuleSet.normalizeUseItem(use, ident)]; } - getExports() { + static normalizeUseItemString(useItemString) { + const idx = useItemString.indexOf("?"); + if (idx >= 0) { + return { + loader: useItemString.substr(0, idx), + options: useItemString.substr(idx + 1) + }; + } return { - exports: [this.name], - dependencies: undefined + loader: useItemString, + options: 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`; + static normalizeUseItem(item, ident) { + if (typeof item === "string") { + return RuleSet.normalizeUseItemString(item); } - const exportsName = dep.originModule.exportsArgument; - - return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( - used - )}, function() { return ${dep.id}; });\n`; - } -}; - -module.exports = HarmonyExportSpecifierDependency; - + const newItem = {}; -/***/ }), + if (item.options && item.query) { + throw new Error("Provided options and query in use"); + } -/***/ 81599: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!item.loader) { + throw new Error("No loader specified"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 DependencyReference = __webpack_require__(71722); -const ModuleDependency = __webpack_require__(90865); -const Template = __webpack_require__(96066); + const keys = Object.keys(item).filter(function(key) { + return !["options", "query"].includes(key); + }); -class HarmonyImportDependency extends ModuleDependency { - constructor(request, originModule, sourceOrder, parserScope) { - super(request); - this.redirectedModule = undefined; - this.originModule = originModule; - this.sourceOrder = sourceOrder; - this.parserScope = parserScope; - } + for (const key of keys) { + newItem[key] = item[key]; + } - get _module() { - return this.redirectedModule || this.module; + return newItem; } - getReference() { - if (!this._module) return null; - return new DependencyReference( - this._module, - false, - this.weak, - this.sourceOrder - ); - } + 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 + + ")" + ); + } - 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 + 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); } - updateHash(hash) { - super.updateHash(hash); - const importedModule = this._module; - hash.update( - (importedModule && - (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + - "" + exec(data) { + const result = []; + this._run( + data, + { + rules: this.rules + }, + result ); - hash.update((importedModule && importedModule.id) + ""); + return result; } - disconnect() { - super.disconnect(); - this.redirectedModule = undefined; - } -} + _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; + } -module.exports = HarmonyImportDependency; + // 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] + }); + } -const importEmittedMap = new WeakMap(); + 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); + } -HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { - apply(dep, source, runtime) { - // no-op - } + if (rule.rules) { + for (let i = 0; i < rule.rules.length; i++) { + this._run(data, rule.rules[i], result); + } + } - getHarmonyInitOrder(dep) { - return dep.sourceOrder; - } + if (rule.oneOf) { + for (let i = 0; i < rule.oneOf.length; i++) { + if (this._run(data, rule.oneOf[i], result)) break; + } + } - 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); + return true; } - harmonyInit(dep, source, runtime, dependencyTemplates) { - let sourceInfo = importEmittedMap.get(source); - if (!sourceInfo) { - importEmittedMap.set( - source, - (sourceInfo = { - emittedImports: new Map() - }) - ); + findOptionsByIdent(ident) { + const options = this.references[ident]; + if (!options) { + throw new Error("Can't find options with ident '" + ident + "'"); } - 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); + return options; } }; /***/ }), -/***/ 99433: +/***/ 44006: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96971,437 +90227,341 @@ HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { */ -const { SyncBailHook } = __webpack_require__(56758); -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); +const Template = __webpack_require__(96066); -module.exports = class HarmonyImportDependencyParserPlugin { - constructor(moduleOptions) { - this.strictExportPresence = moduleOptions.strictExportPresence; - this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; +/** @typedef {import("./Module")} Module */ + +module.exports = class RuntimeTemplate { + constructor(outputOptions, requestShortener) { + this.outputOptions = outputOptions || {}; + this.requestShortener = requestShortener; } - 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" - ]); + /** + * 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 (!parser.hooks.hotAcceptWithoutCallback) { - parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ - "expression", - "requests" - ]); + if (!content) return ""; + if (this.outputOptions.pathinfo) { + return Template.toComment(content) + " "; + } else { + return Template.toNormalComment(content) + " "; } - 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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const HarmonyImportDependency = __webpack_require__(81599); + 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; }`; + } -class HarmonyImportSideEffectDependency extends HarmonyImportDependency { - constructor(request, originModule, sourceOrder, parserScope) { - super(request, originModule, sourceOrder, parserScope); + missingModule({ request }) { + return `!(${this.throwMissingModuleErrorFunction({ request })}())`; } - getReference() { - if (this._module && this._module.factoryMeta.sideEffectFree) return null; + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; + } - return super.getReference(); + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; } - get type() { - return "harmony side effect evaluation"; + 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)}`; } -} -HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { - getHarmonyInitOrder(dep) { - if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; - return super.getHarmonyInitOrder(dep); + moduleRaw({ module, request }) { + if (!module) { + return this.missingModule({ + request + }); + } + return `__webpack_require__(${this.moduleId({ module, request })})`; } -}; -module.exports = HarmonyImportSideEffectDependency; + 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)`; + } + } -/***/ }), - -/***/ 95966: -/***/ (function(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); + 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 + }); -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; - } + 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)`; + } + } - get type() { - return "harmony import specifier"; + return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`; } - get _id() { - return this.redirectedId || this.id; - } + /** + * + * @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 "; - getReference() { - if (!this._module) return null; - return new DependencyReference( - this._module, - this._id && !this.namespaceObjectAsContext ? [this._id] : true, - false, - this.sourceOrder - ); - } + const exportsType = module.buildMeta && module.buildMeta.exportsType; + let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; - getWarnings() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return []; + if (!exportsType && !originModule.buildMeta.strictHarmonyModule) { + content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; } - return this._getErrors(); - } - - getErrors() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return this._getErrors(); + 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 []; + return content; } - _getErrors() { - const importedModule = this._module; - if (!importedModule) { - return; + exportFromImport({ + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + importVar + }) { + if (!module) { + return this.missingModule({ + request + }); } + const exportsType = module.buildMeta && module.buildMeta.exportsType; - 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)` - ) - ]; + 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})`; + } } - return; } - if (!this._id) { - return; + if (exportsType === "named") { + if (exportName === "default") { + return importVar; + } else if (!exportName) { + return `${importVar}_namespace`; + } } - if (importedModule.isProvided(this._id) !== false) { - // It's provided or we are not sure - return; + 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; } - - // 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)) + "" + 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()})`; + } } - 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); + onError() { + return "__webpack_require__.oe"; } - 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; + defineEsModuleFlagStatement({ exportsArgument }) { + return `__webpack_require__.r(${exportsArgument});\n`; } }; -module.exports = HarmonyImportSpecifierDependency; - /***/ }), -/***/ 27204: +/***/ 37098: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97411,65 +90571,74 @@ module.exports = HarmonyImportSpecifierDependency; */ -const NullDependency = __webpack_require__(5088); +const { ConcatSource } = __webpack_require__(53665); -class HarmonyInitDependency extends NullDependency { - constructor(originModule) { - super(); - this.originModule = originModule; - } +/** @typedef {import("./Compilation")} Compilation */ - get type() { - return "harmony init"; +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; } -} -module.exports = HarmonyInitDependency; + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; -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 - }); - } + 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); } - } - - 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 + 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; /***/ }), -/***/ 66792: +/***/ 19070: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97478,183 +90647,101 @@ HarmonyInitDependency.Template = class HarmonyInitDependencyTemplate { 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 SingleEntryDependency = __webpack_require__(84828); -const HarmonyDetectionParserPlugin = __webpack_require__(59310); -const HarmonyImportDependencyParserPlugin = __webpack_require__(99433); -const HarmonyExportDependencyParserPlugin = __webpack_require__(49180); -const HarmonyTopLevelThisParserPlugin = __webpack_require__(58215); +/** @typedef {import("./Compiler")} Compiler */ -class HarmonyModulesPlugin { - constructor(options) { - this.options = options; +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( - "HarmonyModulesPlugin", + "SingleEntryPlugin", (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, + SingleEntryDependency, normalModuleFactory ); - compilation.dependencyTemplates.set( - HarmonyImportSideEffectDependency, - new HarmonyImportSideEffectDependency.Template() - ); + } + ); - compilation.dependencyFactories.set( - HarmonyImportSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSpecifierDependency, - new HarmonyImportSpecifierDependency.Template() - ); + compiler.hooks.make.tapAsync( + "SingleEntryPlugin", + (compilation, callback) => { + const { entry, name, context } = this; - 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); + 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 = HarmonyModulesPlugin; + +module.exports = SingleEntryPlugin; /***/ }), -/***/ 58215: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 12496: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Sean Larkin @thelarkinn */ -const ConstDependency = __webpack_require__(71101); +const SizeFormatHelpers = exports; -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); - } - }); +SizeFormatHelpers.formatSize = size => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; } -} -module.exports = HarmonyTopLevelThisParserPlugin; + 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] + }`; +}; /***/ }), -/***/ 20417: +/***/ 24113: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97663,29 +90750,55 @@ module.exports = HarmonyTopLevelThisParserPlugin; 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; +const ModuleFilenameHelpers = __webpack_require__(71474); + +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; } - get type() { - return `import() context ${this.options.mode}`; + 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 + ); + } + ); + } } } -ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - -module.exports = ImportContextDependency; +module.exports = SourceMapDevToolModuleOptionsPlugin; /***/ }), -/***/ 38875: +/***/ 11851: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97694,362 +90807,424 @@ module.exports = ImportContextDependency; 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); - } -}; +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); -/***/ 50883: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @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 */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {Array} [modules] + * @property {string} source + * @property {string} file + * @property {SourceMap} sourceMap + * @property {Chunk} chunk + */ -const ModuleDependency = __webpack_require__(90865); +/** + * @param {string} name file path + * @returns {string} file name + */ +const basename = name => { + if (!name.includes("/")) return name; + return name.substr(name.lastIndexOf("/") + 1); +}; -class ImportDependency extends ModuleDependency { - constructor(request, originModule, block) { - super(request); - this.originModule = originModule; - this.block = block; - } +/** + * @type {WeakMap} + */ +const assetsCache = new WeakMap(); - get type() { - return "import()"; +/** + * 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(); } -} - -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()" - }); + 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; + }); - source.replace(dep.block.range[0], dep.block.range[1] - 1, content); - } + return { + chunk, + file, + asset, + source, + sourceMap, + modules + }; }; -module.exports = ImportDependency; - - -/***/ }), - -/***/ 25552: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +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)" + ); + } -const ModuleDependency = __webpack_require__(90865); + if (!options) options = {}; -class ImportEagerDependency extends ModuleDependency { - constructor(request, originModule, range) { - super(request); - this.originModule = originModule; - this.range = range; - } + validateOptions(schema, options, "SourceMap DevTool Plugin"); - get type() { - return "import() eager"; + /** @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; } -} -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); - } -}; + /** + * 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; -module.exports = ImportEagerDependency; + 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 + : () => {}; -/***/ 93382: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const files = []; + for (const chunk of chunks) { + for (const file of chunk.files) { + if (matchObject(file)) { + files.push({ + file, + chunk + }); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 + ); -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); + if (task) { + const modules = task.modules; -class ImportParserPlugin { - constructor(options) { - this.options = options; - } + 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 + ) + ); + } + } - 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'." - ); - } + tasks.push(task); + } + }); - const param = parser.evaluateExpression(expr.arguments[0]); + reportProgress(0.5, "resolve sources"); + /** @type {Set} */ + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + /** @type {Set} */ + const conflictDetectionSet = new Set(); - let chunkName = null; - let mode = "lazy"; - let include = null; - let exclude = null; - const groupOptions = {}; + /** + * 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; + } + ); - 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 - ) - ); - } - } + // 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; + } - 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 - ) + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace: namespace + }, + requestShortener ); - } else { - // Do not instrument `import()` if `webpackIgnore` is `true` - if (importOptions.webpackIgnore) { - return false; + 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); } - } - 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 - ) + tasks.forEach((task, index) => { + reportProgress( + 0.5 + (0.5 * index) / tasks.length, + task.file, + "attach SourceMap" ); - } 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 - ) + 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) ); - } 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"; + 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); } - 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; +module.exports = SourceMapDevToolPlugin; /***/ }), -/***/ 58839: +/***/ 99977: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98059,914 +91234,2327 @@ module.exports = ImportParserPlugin; */ -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() - ); +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); - compilation.dependencyFactories.set( - ImportEagerDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportEagerDependency, - new ImportEagerDependency.Template() - ); +const optionsOrFallback = (...args) => { + let optionValues = []; + optionValues.push(...args); + return optionValues.find(optionValue => optionValue !== undefined); +}; - compilation.dependencyFactories.set( - ImportWeakDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportWeakDependency, - new ImportWeakDependency.Template() - ); +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; +}; - compilation.dependencyFactories.set( - ImportContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - ImportContextDependency, - new ImportContextDependency.Template() - ); +class Stats { + constructor(compilation) { + this.compilation = compilation; + this.hash = compilation.hash; + this.startTime = undefined; + this.endTime = undefined; + } - const handler = (parser, parserOptions) => { - if (parserOptions.import !== undefined && !parserOptions.import) - return; + static filterWarnings(warnings, warningsFilter) { + // we dont have anything to filter so all warnings can be shown + if (!warningsFilter) { + return warnings; + } - new ImportParserPlugin(options).apply(parser); - }; + // 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); + } - 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); + if (filter instanceof RegExp) { + return warning => filter.test(warning); } - ); - } -} -module.exports = ImportPlugin; + 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)); + }); + } -/***/ 86817: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + formatFilePath(filePath) { + const OPTIONS_REGEXP = /^(\s|\S)*!/; + return filePath.includes("!") + ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` + : `${filePath}`; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); + } -const ModuleDependency = __webpack_require__(90865); + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); + } -class ImportWeakDependency extends ModuleDependency { - constructor(request, originModule, range) { - super(request); - this.originModule = originModule; - this.range = range; - this.weak = true; + // remove a prefixed "!" that can be specified to reverse sort order + normalizeFieldKey(field) { + if (field[0] === "!") { + return field.substr(1); + } + return field; } - get type() { - return "import() weak"; + // if a field is prefixed by a "!" reverse sort order + sortOrderRegular(field) { + if (field[0] === "!") { + return false; + } + return true; } -} -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; + 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; + } + }; -/***/ 54396: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 + ); -const NullDependency = __webpack_require__(5088); + if (!showCachedModules) { + excludeModules.push((ident, module) => !module.built); + } -class JsonExportsDependency extends NullDependency { - constructor(exports) { - super(); - this.exports = exports; - } + 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; + }; + }; - get type() { - return "json exports"; - } + 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; + }; + }; - getExports() { - return { - exports: this.exports, - dependencies: undefined + 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; }; - } -} -module.exports = JsonExportsDependency; + 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); + }; + }; -/***/ 1129: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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; + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const obj = { + errors: compilation.errors.map(formatError), + warnings: Stats.filterWarnings( + compilation.warnings.map(formatError), + warningsFilter + ) + }; -const ModuleDependency = __webpack_require__(90865); + //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 + }); -class LoaderDependency extends ModuleDependency { - /** - * @param {string} request request string - */ - constructor(request) { - super(request); - } + if (showVersion) { + obj.version = __webpack_require__(71618)/* .version */ .i8; + } - get type() { - return "loader"; - } -} + if (showHash) obj.hash = this.hash; + if (showTimings && this.startTime && this.endTime) { + obj.time = this.endTime - this.startTime; + } -module.exports = LoaderDependency; + 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) + }; -/***/ 31559: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (showPerformance) { + obj.isOverSizeLimit = source.isOverSizeLimit; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 LoaderDependency = __webpack_require__(1129); -const NormalModule = __webpack_require__(25963); + 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; + } + } -/** @typedef {import("../Module")} Module */ + return obj; + }; -/** - * @callback LoadModuleCallback - * @param {Error=} err error object - * @param {string=} source source code - * @param {object=} map source map - * @param {Module=} module loaded module if successful - */ + if (showEntrypoints) { + obj.entrypoints = fnChunkGroup(compilation.entrypoints); + } -class LoaderPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "LoaderPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - LoaderDependency, - normalModuleFactory - ); - } - ); + if (showChunkGroups) { + obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); + } - 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); - } + 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 callback(null, source, map, dep.module); - }); + 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}`; } - ); - }); - } -} -module.exports = LoaderPlugin; - + 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; + } -/***/ 17356: -/***/ (function(module) { + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const useColors = optionsOrFallback(options.colors, false); + const obj = this.toJson(options, true); -class LocalModule { - constructor(module, name, idx) { - this.module = module; - this.name = name; - this.idx = idx; - this.used = false; + return Stats.jsonToString(obj, useColors); } - flagUsed() { - this.used = true; - } + static jsonToString(obj, useColors) { + const buf = []; - variableName() { - return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; - } -} -module.exports = LocalModule; + 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`); + }; -/***/ 56570: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const newline = () => buf.push("\n"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const getText = (arr, row, col) => { + return arr[row][col].value; + }; -const NullDependency = __webpack_require__(5088); + 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(); + } + }; -class LocalModuleDependency extends NullDependency { - constructor(localModule, range, callNew) { - super(); - localModule.flagUsed(); - this.localModule = localModule; - this.range = range; - this.callNew = callNew; - } -} + const getAssetColor = (asset, defaultColor) => { + if (asset.isOverSizeLimit) { + return colors.yellow; + } -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); - } -}; + return defaultColor; + }; -module.exports = LocalModuleDependency; - - -/***/ }), - -/***/ 39658: -/***/ (function(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); + if (obj.hash) { + colors.normal("Hash: "); + colors.bold(obj.hash); + newline(); } - } - - 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]; + if (obj.version) { + colors.normal("Version: webpack "); + colors.bold(obj.version); + newline(); } - } - return null; -}; - -module.exports = LocalModulesHelpers; - - -/***/ }), - -/***/ 90865: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const Dependency = __webpack_require__(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; - + 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"; + } -/***/ 63708: -/***/ (function(module) { + 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(); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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(); + } + }; -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; + 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; + } + } + } + } -/***/ 60441: -/***/ (function(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"}]` + ); + } + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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(); + } + } + }; -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; - + 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, ""); -/***/ 29018: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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(); + } + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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." + ); + } -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsId = __webpack_require__(63708); + while (buf[buf.length - 1] === "\n") { + buf.pop(); + } + return buf.join(""); + } -class ModuleHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; + 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 {}; + } } - get type() { - return "module.hot.accept"; + 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); } } -ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ModuleHotAcceptDependency; +module.exports = Stats; /***/ }), -/***/ 60482: +/***/ 97365: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Joel Denning @joeldenning + */ -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"; +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; } -} -ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; -module.exports = ModuleHotDeclineDependency; + 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 + ) + ); -/***/ 7791: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // The name of the variable provided by System for exporting + const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // An array of the internal variable names for the webpack externals + const externalWebpackNames = externals.map( + m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ); -/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ -const Dependency = __webpack_require__(57282); + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = + externalWebpackNames.length > 0 + ? `var ${externalWebpackNames.join(", ")};` + : ""; -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; - } + // 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") + ), + "]," + ]); - get type() { - return "multi entry"; + 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 = MultiEntryDependency; +module.exports = SystemMainTemplatePlugin; /***/ }), -/***/ 5088: +/***/ 96066: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ -const Dependency = __webpack_require__(57282); - -class NullDependency extends Dependency { - get type() { - return "null"; - } - - updateHash() {} -} - -NullDependency.Template = class NullDependencyTemplate { - apply() {} -}; - -module.exports = NullDependency; +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 */ -/***/ 14237: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} HasId + * @property {number | string} id + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {function(Module, number): boolean} ModuleFilterPredicate + */ -const ModuleDependency = __webpack_require__(90865); +/** + * @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 PrefetchDependency extends ModuleDependency { - constructor(request) { - super(request); +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"); } - get type() { - return "prefetch"; + /** + * @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, "* /")} */`; } -} - -module.exports = PrefetchDependency; - - -/***/ }), - -/***/ 79142: -/***/ (function(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; + /** + * + * @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, "* /")} */`; } - get type() { - return "require.context"; + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); } -} -RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + // 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); + } -module.exports = RequireContextDependency; + // 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"); + } + } -/***/ 10566: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * + * @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"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * + * @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 + */ -const RequireContextDependency = __webpack_require__(79142); + /** + * @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; + } -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; - } + /** + * @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; /***/ }), -/***/ 89042: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 76032: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jason Anderson @diurnalist */ -const RequireContextDependency = __webpack_require__(79142); -const ContextElementDependency = __webpack_require__(89079); +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; -const RequireContextDependencyParserPlugin = __webpack_require__(10566); +// 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"); -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"); +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); } - this.modulesDirectories = modulesDirectories; - this.extensions = extensions; - this.mainFiles = mainFiles; - } + const hash = replacer(match, hashLength, ...args); + return length ? hash.slice(0, length) : hash; + }; + return fn; +}; - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireContextPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireContextDependency, - new RequireContextDependency.Template() +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; +}; - compilation.dependencyFactories.set( - ContextElementDependency, - normalModuleFactory - ); +const escapePathVariables = value => { + return typeof value === "string" + ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, "[\\$1\\]") + : value; +}; - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireContext !== undefined && - !parserOptions.requireContext - ) - return; +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; - new RequireContextDependencyParserPlugin().apply(parser); - }; + if (typeof path === "function") { + path = path(data); + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireContextPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireContextPlugin", handler); + 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)` + ); + } - 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), []); - } - ); + 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]") + ); +}; - 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), []); - } - ); +class TemplatedPathPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { + const mainTemplate = compilation.mainTemplate; - 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; - }); + 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 = RequireContextPlugin; + +module.exports = TemplatedPathPlugin; /***/ }), -/***/ 49105: +/***/ 75374: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98975,229 +93563,311 @@ module.exports = RequireContextPlugin; 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); - } +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 */ -/***/ 24620: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} AuxiliaryCommentObject + * @property {string} root + * @property {string} commonjs + * @property {string} commonjs2 + * @property {string} amd + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @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; + } -const RequireEnsureDependenciesBlock = __webpack_require__(49105); -const RequireEnsureItemDependency = __webpack_require__(5511); -const getFunctionExpression = __webpack_require__(64197); + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; -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; + 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); } - // falls through - case 3: { - errorExpressionArg = expr.arguments[2]; - errorExpression = getFunctionExpression(errorExpressionArg); + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; + } - 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 - ); + const replaceKeys = str => { + return mainTemplate.getAssetPath(str, { + hash, + chunk + }); + }; - if (successExpression) { - parser.walkExpressions(successExpression.expressions); - } - if (errorExpression) { - parser.walkExpressions(errorExpression.expressions); - } + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) + ) + .join(", ") + )}]`; + }; - 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; + 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 (successExpression) { - if (successExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(successExpression.fn.body); - } else { - parser.walkExpression(successExpression.fn.body); - } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); } - 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); + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; } else { - parser.walkExpression(errorExpression.fn.body); + expr = `require(${JSON.stringify(request)})`; } - } else if (errorExpressionArg) { - parser.walkExpression(errorExpressionArg); - } - return true; - } - } - }); - } -}; - - -/***/ }), + if (m.optional) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; -/***/ 75830: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; -const NullDependency = __webpack_require__(5088); + 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"; + } -class RequireEnsureDependency extends NullDependency { - constructor(block) { - super(); - this.block = block; - } + const auxiliaryComment = this.auxiliaryComment; - get type() { - return "require.ensure"; - } -} + const getAuxilaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; -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, - ")" + 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})" ); - } else { - source.replace( - depBlock.expr.arguments[1].range[1], - depBlock.expr.range[1] - 1, - endBlock + }; + + 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 = RequireEnsureDependency; +module.exports = UmdMainTemplatePlugin; /***/ }), -/***/ 5511: +/***/ 99953: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99206,27 +93876,36 @@ module.exports = RequireEnsureDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -const NullDependency = __webpack_require__(5088); -class RequireEnsureItemDependency extends ModuleDependency { - constructor(request) { - super(request); - } +const WebpackError = __webpack_require__(97391); - get type() { - return "require.ensure item"; +/** @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); } } -RequireEnsureItemDependency.Template = NullDependency.Template; - -module.exports = RequireEnsureItemDependency; +module.exports = UnsupportedFeatureWarning; /***/ }), -/***/ 98655: +/***/ 73554: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99236,79 +93915,59 @@ module.exports = RequireEnsureItemDependency; */ -const RequireEnsureItemDependency = __webpack_require__(5511); -const RequireEnsureDependency = __webpack_require__(75830); - -const NullFactory = __webpack_require__(40438); - -const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(24620); +const ConstDependency = __webpack_require__(71101); -const ParserHelpers = __webpack_require__(23999); +/** @typedef {import("./Compiler")} Compiler */ -class RequireEnsurePlugin { +class UseStrictPlugin { + /** + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ apply(compiler) { compiler.hooks.compilation.tap( - "RequireEnsurePlugin", + "UseStrictPlugin", (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") - ) - ); + 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("RequireEnsurePlugin", handler); + .tap("UseStrictPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("RequireEnsurePlugin", handler); + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); } ); } } -module.exports = RequireEnsurePlugin; + +module.exports = UseStrictPlugin; /***/ }), -/***/ 22928: +/***/ 40269: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99317,32 +93976,43 @@ module.exports = RequireEnsurePlugin; 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__"); - } +const CaseSensitiveModulesWarning = __webpack_require__(8335); - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "require"); +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 = RequireHeaderDependency; +module.exports = WarnCaseSensitiveModulesPlugin; /***/ }), -/***/ 58045: +/***/ 71245: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99352,44 +94022,22 @@ module.exports = RequireHeaderDependency; */ -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); - } +const NoModeWarning = __webpack_require__(45759); - get type() { - return "require.include"; +class WarnNoModeSetPlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { + compilation.warnings.push(new NoModeWarning()); + }); } } -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; +module.exports = WarnNoModeSetPlugin; /***/ }), -/***/ 36330: +/***/ 88015: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99399,128 +94047,111 @@ module.exports = RequireIncludeDependency; */ -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; - }); - } -}; +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; + } -/***/ 16522: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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 + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const notIgnored = path => !ignored(path); + const ignoredFiles = files.filter(ignored); + const ignoredDirs = dirs.filter(ignored); -const RequireIncludeDependency = __webpack_require__(58045); -const RequireIncludeDependencyParserPlugin = __webpack_require__(36330); + 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); + } -const ParserHelpers = __webpack_require__(23999); + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } -class RequireIncludePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireIncludePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireIncludeDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireIncludeDependency, - new RequireIncludeDependency.Template() + callback( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps, + removedFiles ); + }, + callbackUndelayed + ); - 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); + 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; } - ); + }; } } -module.exports = RequireIncludePlugin; - - -/***/ }), -/***/ 83309: -/***/ (function(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; +class WatchIgnorePlugin { + /** + * @param {WatchIgnorePluginOptions} paths list of paths + */ + constructor(paths) { + validateOptions(schema, paths, "Watch Ignore Plugin"); + this.paths = paths; } - get type() { - return "amd require context"; + apply(compiler) { + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); + }); } } -RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; - -module.exports = RequireResolveContextDependency; +module.exports = WatchIgnorePlugin; /***/ }), -/***/ 43519: +/***/ 29580: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99529,315 +94160,256 @@ module.exports = RequireResolveContextDependency; 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; +const Stats = __webpack_require__(99977); -/***/ }), - -/***/ 68349: -/***/ (function(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 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); -class RequireResolveDependencyParserPlugin { - constructor(options) { - this.options = options; + this._go(); + }); } - apply(parser) { - const options = this.options; + _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(); - 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); + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); } - 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; + 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); -/***/ 69647: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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); + }); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + _getStats(compilation) { + const stats = new Stats(compilation); + stats.startTime = this.startTime; + stats.endTime = Date.now(); + return stats; + } -const NullDependency = __webpack_require__(5088); + _done(err, compilation) { + this.running = false; + if (this.invalid) return this._go(); -class RequireResolveHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); - this.range = range; + 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; + }); } -} -RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { - apply(dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + 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); + } + ); } - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + 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(); } -}; - -module.exports = RequireResolveHeaderDependency; - - -/***/ }), -/***/ 84828: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _invalidate() { + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.watcher.pause(); + this.watcher = null; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (this.running) { + this.invalid = true; + return false; + } else { + this._go(); + } + } -const ModuleDependency = __webpack_require__(90865); + suspend() { + this.suspended = true; + this.invalid = false; + } -class SingleEntryDependency extends ModuleDependency { - /** - * @param {string} request request path for entry - */ - constructor(request) { - super(request); + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } } - get type() { - return "single entry"; + 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 = SingleEntryDependency; +module.exports = Watching; /***/ }), -/***/ 68166: +/***/ 97391: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jarid Margolin @jaridmargolin */ -const 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 - ); - }); +const inspect = __webpack_require__(31669).inspect.custom; - parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { - if (shouldWarn) { - parser.state.module.warnings.push( - new SystemImportDeprecationWarning( - parser.state.module, - expr.loc - ) - ); - } +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); - return parser.hooks.importCall.call(expr); - }); - }; + this.details = undefined; + this.missing = undefined; + this.origin = undefined; + this.dependencies = undefined; + this.module = undefined; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("SystemPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("SystemPlugin", handler); - } - ); + Error.captureStackTrace(this, this.constructor); } -} - -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); + [inspect]() { + return this.stack + (this.details ? `\n${this.details}` : ""); } } -module.exports = SystemPlugin; +module.exports = WebpackError; /***/ }), -/***/ 15826: +/***/ 2779: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99846,222 +94418,553 @@ module.exports = SystemPlugin; 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; +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); -/***/ 18925: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const EntryOptionPlugin = __webpack_require__(14604); +const RecordIdsPlugin = __webpack_require__(40355); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +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 DependencyReference = __webpack_require__(71722); -const ModuleDependency = __webpack_require__(90865); +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); -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; - } +const { cachedCleverMerge } = __webpack_require__(67916); - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, [this.name], false); - } +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("./Compiler")} Compiler */ - get type() { - return "wasm export import"; +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); } -} - -module.exports = WebAssemblyExportImportedDependency; - -/***/ }), - -/***/ 52959: -/***/ (function(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 + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object */ - constructor(request, name, description, onlyDirectImport) { - super(request); - /** @type {string} */ - this.name = name; - /** @type {ModuleImportDescription} */ - this.description = description; - /** @type {false | string} */ - this.onlyDirectImport = onlyDirectImport; - } + 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; - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, [this.name], false); - } + 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 + "'."); + } - getErrors() { + 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 ( - this.onlyDirectImport && - this.module && - !this.module.type.startsWith("webassembly") + options.devtool && + (options.devtool.includes("sourcemap") || + options.devtool.includes("source-map")) ) { - return [ - new UnsupportedWebAssemblyFeatureError( - `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` - ) - ]; + 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); } - } - - get type() { - return "wasm import"; - } -} -module.exports = WebAssemblyImportDependency; + 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); -/***/ 75386: -/***/ (function(__unused_webpack_module, exports) { + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = __webpack_require__(71245); + new WarnNoModeSetPlugin().apply(compiler); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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); + } + } + } -const toErrorCode = err => - `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; + if (options.performance) { + const SizeLimitsPlugin = __webpack_require__(68310); + new SizeLimitsPlugin(options.performance).apply(compiler); + } -exports.module = request => - `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; + new TemplatedPathPlugin().apply(compiler); -exports.promise = request => { - const errorCode = toErrorCode(`Cannot find module '${request}'`); - return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; -}; + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); -exports.moduleCode = request => { - const errorCode = toErrorCode(`Cannot find module '${request}'`); - return `${errorCode} throw e;`; -}; + new WarnCaseSensitiveModulesPlugin().apply(compiler); + if (options.cache) { + const CachePlugin = __webpack_require__(6465); + new CachePlugin( + typeof options.cache === "object" ? options.cache : null + ).apply(compiler); + } -/***/ }), - -/***/ 64197: -/***/ (function(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 - }; + 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; } +} - // .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 - }; - } -}; +module.exports = WebpackOptionsApply; /***/ }), -/***/ 49: -/***/ (function(module) { +/***/ 60016: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -100070,609 +94973,784 @@ module.exports = expr => { */ +const path = __webpack_require__(85622); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ +const OptionsDefaulter = __webpack_require__(3414); +const Template = __webpack_require__(96066); -// 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 ""; +const isProductionLikeMode = options => { + return options.mode === "production" || !options.mode; }; -// 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 ""; +const isWebLikeTarget = options => { + return options.target === "web" || options.target === "webworker"; }; -module.exports = formatLocation; - - -/***/ }), - -/***/ 47194: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - - - -const LogType = Object.freeze({ - error: /** @type {"error"} */ ("error"), // message, c style arguments - warn: /** @type {"warn"} */ ("warn"), // message, c style arguments - info: /** @type {"info"} */ ("info"), // message, c style arguments - log: /** @type {"log"} */ ("log"), // message, c style arguments - debug: /** @type {"debug"} */ ("debug"), // message, c style arguments - - trace: /** @type {"trace"} */ ("trace"), // no arguments - - group: /** @type {"group"} */ ("group"), // [label] - groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] - groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] - - profile: /** @type {"profile"} */ ("profile"), // [profileName] - profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] - - time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] - - clear: /** @type {"clear"} */ ("clear"), // no arguments - status: /** @type {"status"} */ ("status") // message, arguments -}); - -exports.LogType = LogType; - -/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ - -const LOG_SYMBOL = Symbol("webpack logger raw log method"); -const TIMERS_SYMBOL = Symbol("webpack logger times"); - -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]); +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); } -} - -exports.Logger = WebpackLogger; - + return library || ""; +}; -/***/ }), +class WebpackOptionsDefaulter extends OptionsDefaulter { + constructor() { + super(); -/***/ 88838: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.set("entry", "./src"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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" + } + ]); -const { LogType } = __webpack_require__(47194); + this.set("output", "call", (value, options) => { + if (typeof value === "string") { + return { + filename: value + }; + } else if (typeof value !== "object") { + return {}; + } else { + return Object.assign({}, value); + } + }); -/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ -/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ -/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ + 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); -/** @typedef {function(string): boolean} FilterFunction */ + 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"); -/** - * @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 - */ + 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 + ); -/** - * @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, - "\\$&" - )}([\\\\/]|$|!|\\?)` + 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" ); - 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]; + 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 []; } - }; - 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; + }); + 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"]; } - 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; -}; + }); + 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; /***/ }), -/***/ 62299: -/***/ (function(module) { +/***/ 285: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ -/** - * @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; +const WebpackError = __webpack_require__(97391); +const webpackOptionsSchema = __webpack_require__(37863); - if (availableLength > 0 && args.length === 1) { - if (availableLength >= args[0].length) { - return args; - } else if (availableLength > 3) { - return ["..." + args[0].slice(-availableLength + 3)]; - } else { - return [args[0].slice(-availableLength)]; - } +const 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); } - - // 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 schemaPart = webpackOptionsSchema; + for (let i = 1; i < path.length; i++) { + const inner = schemaPart[path[i]]; + if (inner) schemaPart = inner; } + return schemaPart; +}; - 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--; - } +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; +}; - // 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 ""; - } - }); +const getSchemaPartDescription = schemaPart => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + if (schemaPart.description) { + return `\n-> ${schemaPart.description}`; + } + return ""; }; -module.exports = truncateArgs; +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; +}; -/***/ 45249: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const indent = (str, prefix, firstLine) => { + if (firstLine) { + return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); + } else { + return str.replace(/\n(?!$)/g, `\n${prefix}`); + } +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +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); + } -const { ConcatSource } = __webpack_require__(53665); + static formatSchema(schema, prevSchemas) { + prevSchemas = prevSchemas || []; -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 = ` + const formatInnerSchema = (innerSchema, addSelf) => { + if (!addSelf) { + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas ); - source.add(modules); - source.add(";"); - return source; } - ); - chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { - hash.update("node"); - hash.update("3"); - }); - } -} - -module.exports = NodeChunkTemplatePlugin; - - -/***/ }), - -/***/ 52520: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas.concat(schema) + ); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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"; + } -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); + if (schema.enum) { + return schema.enum.map(item => JSON.stringify(item)).join(" | "); + } -class NodeEnvironmentPlugin { - constructor(options) { - this.options = options || {}; + 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); } - 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(); - }); + 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 = NodeEnvironmentPlugin; + +module.exports = WebpackOptionsValidationError; /***/ }), -/***/ 95909: +/***/ 52337: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -100682,829 +95760,730 @@ module.exports = NodeEnvironmentPlugin; */ -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; +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 + */ -/***/ 33514: -/***/ (function(module) { +/** + * @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 + */ -/* - 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; +/** + * @typedef {Object} ChunkGroupDep + * @property {AsyncDependenciesBlock} block referencing block + * @property {ChunkGroup} chunkGroup referenced chunk group + */ -module.exports = function() { - // eslint-disable-next-line no-unused-vars - function hotDownloadUpdateChunk(chunkId) { - var chunk = require("./" + $hotChunkFilename$); - hotAddUpdateChunk(chunk.id, chunk.modules); - } +/** + * @template T + * @param {Set} a first set + * @param {Set} b second set + * @returns {number} cmp + */ +const bySetSize = (a, b) => { + return b.size - a.size; +}; - // eslint-disable-next-line no-unused-vars - function hotDownloadManifest() { - try { - var update = require("./" + $hotMainFilename$); - } catch (e) { - return Promise.resolve(); +/** + * 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; } - return Promise.resolve(update); - } - //eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; - } -}; + 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; -/***/ 51433: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + for (const module of compilation.modules) { + blockQueue = [module]; + currentModule = module; + while (blockQueue.length > 0) { + block = blockQueue.pop(); + blockInfoModules = new Set(); + blockInfoBlocks = []; -/* - 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; + if (block.variables) { + for (const variable of block.variables) { + for (const dep of variable.dependencies) iteratorDependency(dep); + } + } -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; + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); } - 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); - }); - }); - } + if (block.blocks) { + for (const b of block.blocks) iteratorBlockPrepare(b); + } - // eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; + const blockInfo = { + modules: blockInfoModules, + blocks: blockInfoBlocks + }; + blockInfoMap.set(block, blockInfo); + } } -}; - - -/***/ }), - -/***/ 78597: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return blockInfoMap; +}; -const Template = __webpack_require__(96066); +/** + * + * @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; -module.exports = class NodeMainTemplatePlugin { - constructor(asyncChunkLoading) { - this.asyncChunkLoading = asyncChunkLoading; - } + logger.time("prepare"); + const blockInfoMap = extraceBlockInfoMap(compilation); - 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"); + /** @type {Map} */ + const chunkGroupCounters = new Map(); + for (const chunkGroup of inputChunkGroups) { + chunkGroupCounters.set(chunkGroup, { + index: 0, + index2: 0 }); } -}; + let nextFreeModuleIndex = 0; + let nextFreeModuleIndex2 = 0; -/***/ }), - -/***/ 31836: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map} */ + const blockChunkGroups = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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; + }; -const fs = __webpack_require__(35747); -const path = __webpack_require__(85622); -const mkdirp = __webpack_require__(50998); + // 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 = []; -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); - } -} + logger.timeEnd("prepare"); -module.exports = NodeOutputFileSystem; + /** @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 + }); -/***/ 9128: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // 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); -const AliasPlugin = __webpack_require__(15005); -const ParserHelpers = __webpack_require__(23999); -const nodeLibsBrowser = __webpack_require__(27852); + // 4. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c + }); + }; -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; - } + // 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; + } - 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` - ); + 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; + } } - 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; - } - }; + // fallthrough + case ENTER_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex(module); + if (index === undefined) { + chunkGroup.setModuleIndex( + module, + chunkGroupCounters.get(chunkGroup).index++ + ); + } + } - 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 - ); - }); - }; + if (module.index === null) { + module.index = nextFreeModuleIndex++; + } - compiler.hooks.compilation.tap( - "NodeSourcePlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; + queue.push({ + action: LEAVE_MODULE, + block, + module, + chunk, + chunkGroup + }); + } + // fallthrough + case PROCESS_BLOCK: { + // get prepared block info + const blockInfo = blockInfoMap.get(block); - 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 - ); + // 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 + }); } - if (localOptions.process) { - const processType = localOptions.process; - addExpression(parser, "process", "process", processType); + // Add buffered items in reversed order + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.push(skipBuffer[i]); } - if (localOptions.console) { - const consoleType = localOptions.console; - addExpression(parser, "console", "console", consoleType); + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); } - const bufferType = localOptions.Buffer; - if (bufferType) { - addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); + + // Traverse all Blocks + for (const block of blockInfo.blocks) iteratorBlock(block); + + if (blockInfo.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); } - if (localOptions.setImmediate) { - const setImmediateType = localOptions.setImmediate; - addExpression( - parser, - "setImmediate", - "timers", - setImmediateType, - ".setImmediate" - ); - addExpression( - parser, - "clearImmediate", - "timers", - setImmediateType, - ".clearImmediate" - ); + break; + } + case LEAVE_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex2(module); + if (index === undefined) { + chunkGroup.setModuleIndex2( + module, + chunkGroupCounters.get(chunkGroup).index2++ + ); + } } - }; - 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); - }); + + 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; -/***/ 59743: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // 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); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // 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; -const ExternalsPlugin = __webpack_require__(75705); + // 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; -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")); + // Update the cache from the first queue + // if the chunkGroup is currently cached + if (chunkGroup === info.chunkGroup) { + minAvailableModules = cachedMinAvailableModules; + } -class NodeTargetPlugin { - apply(compiler) { - new ExternalsPlugin("commonjs", builtins).apply(compiler); + 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; + } } -} +}; -module.exports = NodeTargetPlugin; +/** + * + * @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; + }; -/***/ 90010: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // For all deps, check if chunk groups need to be connected + for (const [chunkGroup, deps] of chunkDependencies) { + if (deps.length === 0) continue; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // 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; -const NodeMainTemplatePlugin = __webpack_require__(78597); -const NodeChunkTemplatePlugin = __webpack_require__(45249); -const NodeHotUpdateChunkTemplatePlugin = __webpack_require__(95909); + // 5. Connect block with chunk + GraphHelpers.connectDependenciesBlockAndChunkGroup( + depBlock, + depChunkGroup + ); -class NodeTemplatePlugin { - constructor(options) { - options = options || {}; - this.asyncChunkLoading = options.asyncChunkLoading; + // 6. Connect chunk with parent + GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); + } } +}; - 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 - ); - }); +/** + * 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"); + } } -} - -module.exports = NodeTemplatePlugin; +}; +/** + * 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(); -/***/ 71610: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Set} */ + const allCreatedChunkGroups = new Set(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {Map} */ + const chunkGroupInfoMap = new Map(); + /** @type {Set} */ + const blocksWithNestedBlocks = new Set(); -const Watchpack = __webpack_require__(77056); -const objectToMap = __webpack_require__(1111); + // PART ONE -class NodeWatchFileSystem { - constructor(inputFileSystem) { - this.inputFileSystem = inputFileSystem; - this.watcherOptions = { - aggregateTimeout: 0 - }; - this.watcher = new Watchpack(this.watcherOptions); - } + visitModules( + compilation, + inputChunkGroups, + chunkGroupInfoMap, + chunkDependencies, + blocksWithNestedBlocks, + allCreatedChunkGroups + ); - 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); + // PART TWO - 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 - ); - }); + connectChunkGroups( + blocksWithNestedBlocks, + chunkDependencies, + chunkGroupInfoMap + ); - this.watcher.watch( - cachedFiles.concat(missing), - cachedDirs.concat(missing), - startTime - ); + // Cleaup work - 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(); - } - } - }; - } -} + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); +}; -module.exports = NodeWatchFileSystem; +module.exports = buildChunkGraph; /***/ }), -/***/ 73839: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 22562: +/***/ (function(module) { "use strict"; /* @@ -101513,680 +96492,506 @@ module.exports = NodeWatchFileSystem; */ -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); }" - ]), - "})" - ]); +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - const plugin = new WasmMainTemplatePlugin( - Object.assign( - { - generateLoadBinaryCode, - supportsStreaming: false - }, - this.options - ) - ); - plugin.apply(compilation.mainTemplate); +// 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; + } } -} - -module.exports = ReadFileCompileWasmTemplatePlugin; +}; /***/ }), -/***/ 7886: +/***/ 72890: /***/ (function(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__(50998); +const { Tracer } = __webpack_require__(92430); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(49049); -const truncateArgs = __webpack_require__(62299); -const util = __webpack_require__(31669); +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ -const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; +let inspector = undefined; -let currentStatusMessage = undefined; -let hasStatusMessage = false; -let currentIndent = ""; -let currentCollapsed = 0; +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"); +} -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); +class Profiler { + constructor(inspector) { + this.session = undefined; + this.inspector = inspector; } -}; -const clearStatusMessage = () => { - if (hasStatusMessage) { - process.stderr.write("\x1b[2K\r"); - hasStatusMessage = false; + hasSession() { + return this.session !== undefined; } -}; - -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(); - }; -}; + startProfiling() { + if (this.inspector === undefined) { + return Promise.resolve(); + } -const writeGroupMessage = writeColored( - "<-> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" -); + try { + this.session = new inspector.Session(); + this.session.connect(); + } catch (_) { + this.session = undefined; + return Promise.resolve(); + } -const writeGroupCollapsedMessage = writeColored( - "<+> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" -); + return Promise.all([ + this.sendCommand("Profiler.setSamplingInterval", { + interval: 100 + }), + this.sendCommand("Profiler.enable"), + this.sendCommand("Profiler.start") + ]); + } -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++; + 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 { - currentIndent += " "; + return Promise.resolve(); } - }, - 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(" ", "", "") -}; - + } -/***/ }), + destroy() { + if (this.hasSession()) { + this.session.disconnect(); + } -/***/ 88197: -/***/ (function(module) { + return Promise.resolve(); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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 + */ -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 || {}; +/** + * @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); - apply(compiler) { - const options = this.options; - const minSizeReduce = options.minSizeReduce || 1.5; + let counter = 0; - 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; - } + 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: "" } - ); + ] } - ); - } -} - -module.exports = AggressiveMergingPlugin; - - -/***/ }), - -/***/ 26688: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const identifierUtils = __webpack_require__(94658); -const { intersect } = __webpack_require__(54262); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(71884); + } + }); -/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" + } + } + }); -const moveModuleBetween = (oldChunk, newChunk) => { - return module => { - oldChunk.moveModule(module, newChunk); + 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 isNotAEntryModule = entryModule => { - return module => { - return entryModule !== module; - }; -}; +const pluginName = "ProfilingPlugin"; -class AggressiveSplittingPlugin { +class ProfilingPlugin { /** - * @param {AggressiveSplittingPluginOptions=} options options object + * @param {ProfilingPluginOptions=} opts 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; - } + constructor(opts) { + validateOptions(schema, opts || {}, "Profiling plugin"); + opts = opts || {}; + this.outputPath = opts.outputPath || "events.json"; } - 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; + apply(compiler) { + const tracer = createTrace(this.outputPath); + tracer.profiler.startProfiling(); - // get chunks with all modules - const selectedChunks = intersect( - selectedModules.map(m => new Set(m.chunksIterable)) - ); + // Compiler Hooks + Object.keys(compiler.hooks).forEach(hookName => { + compiler.hooks[hookName].intercept( + makeInterceptorFor("Compiler", tracer)(hookName) + ); + }); - // No relevant chunks found - if (selectedChunks.size === 0) return false; + Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { + compiler.resolverFactory.hooks[hookName].intercept( + makeInterceptorFor("Resolver", tracer)(hookName) + ); + }); - // 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; - } + 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); + } + ); - // 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); + // 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; + } - if (splitData.id !== null && splitData.id !== undefined) { - newChunk.id = splitData.id; - } - return true; - }; + const cpuStartTime = parsedResults.profile.startTime; + const cpuEndTime = parsedResults.profile.endTime; - // 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; + tracer.trace.completeEvent({ + name: "TaskQueueManager::ProcessTaskFromWorkQueue", + id: ++tracer.counter, + cat: ["toplevel"], + ts: cpuStartTime, + args: { + src_file: "../../ipc/ipc_moji_bootstrap.cc", + src_func: "Accept" } + }); - // for 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; - } + 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" } } - 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); - } + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile } } + }); - 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; - } - } - ); + tracer.profiler.destroy(); + tracer.trace.flush(); + tracer.end(callback); + }); } ); } } -module.exports = AggressiveSplittingPlugin; - - -/***/ }), -/***/ 30346: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const interceptTemplateInstancesFrom = (compilation, tracer) => { + const { + mainTemplate, + chunkTemplate, + hotUpdateChunkTemplate, + moduleTemplates + } = compilation; + const { javascript, webassembly } = moduleTemplates; -const sortByIndex = (a, b) => { - return a.index - b.index; + [ + { + 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 sortByIndex2 = (a, b) => { - return a.index2 - b.index2; +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + Object.keys(instance.hooks).forEach(hookName => { + instance.hooks[hookName].intercept( + makeInterceptorFor(logLabel, tracer)(hookName) + ); + }); + } }; -class ChunkModuleIdRangePlugin { - constructor(options) { - this.options = options; - } +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + "javascript/auto", + "javascript/dynamic", + "javascript/esm", + "json", + "webassembly/experimental" + ]; - 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` - ); - } + moduleTypes.forEach(moduleType => { + moduleFactory.hooks.parser + .for(moduleType) + .tap("ProfilingPlugin", (parser, parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + }); +}; - 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); +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); } - 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; + 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 = ChunkModuleIdRangePlugin; +}; + +module.exports = ProfilingPlugin; +module.exports.Profiler = Profiler; /***/ }), -/***/ 16953: +/***/ 67045: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102195,1483 +97000,1148 @@ module.exports = ChunkModuleIdRangePlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -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); +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; + } -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../util/createHash").Hash} Hash */ -/** @typedef {import("../RequestShortener")} RequestShortener */ + get type() { + return "amd define"; + } +} -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; +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__))` + ] + }; } - return str; -}; -/** - * @typedef {Object} ConcatenationEntry - * @property {"concatenated" | "external"} type - * @property {Module} module - */ + 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); + } -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"; + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); } -}; -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; - } - } + 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; } - 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 + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") ); } - } -}; -const 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); + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); } - 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); + 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]; } - 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; - } + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); } - return 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; - }; +module.exports = AMDDefineDependency; - 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); +/***/ 27057: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Info from Factory - this.rootModule = rootModule; - this.factoryMeta = rootModule.factoryMeta; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 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; +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); - // 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; +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; +}; - // Caching - this._numberOfConcatenatedModules = modules.length; +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; - // Graph - const modulesSet = new Set(modules); - this.reasons = rootModule.reasons.filter( - reason => - !(reason.dependency instanceof HarmonyImportDependency) || - !modulesSet.has(reason.module) - ); +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; - this.dependencies = []; - this.blocks = []; +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; + } - 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; + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); + } - // populate dependencies - for (const d of m.dependencies.filter( - dep => - !(dep instanceof HarmonyImportDependency) || - !modulesSet.has(dep._module) - )) { - this.dependencies.push(d); + 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); } - // populate blocks - for (const d of m.blocks) { - this.blocks.push(d); + }); + 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); } - // populate file dependencies - if (m.buildInfo.fileDependencies) { - for (const file of m.buildInfo.fileDependencies) { - this.buildInfo.fileDependencies.add(file); - } + 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); } - // populate context dependencies - if (m.buildInfo.contextDependencies) { - for (const context of m.buildInfo.contextDependencies) { - this.buildInfo.contextDependencies.add(context); + }); + 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]; } } - // populate warnings - for (const warning of m.warnings) { - this.warnings.push(warning); + 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]; } - // populate errors - for (const error of m.errors) { - this.errors.push(error); + 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; } - - if (m.buildInfo.assets) { - if (this.buildInfo.assets === undefined) { - this.buildInfo.assets = Object.create(null); + } + } + 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; } - Object.assign(this.buildInfo.assets, m.buildInfo.assets); - } - if (m.buildInfo.assetsInfo) { - if (this.buildInfo.assetsInfo === undefined) { - this.buildInfo.assetsInfo = new Map(); + 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; } - for (const [key, value] of m.buildInfo.assetsInfo) { - this.buildInfo.assetsInfo.set(key, value); + 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); } - this._identifier = this._createIdentifier(); - } - get modules() { - return this._orderedConcatenationList - .filter(info => info.type === "concatenated") - .map(info => info.module); - } - - identifier() { - return this._identifier; + 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; } - readableIdentifier(requestShortener) { - return ( - this.rootModule.readableIdentifier(requestShortener) + - ` + ${this._numberOfConcatenatedModules - 1} modules` + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule ); } - - libIdent(options) { - return this.rootModule.libIdent(options); + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); } - - nameForCondition() { - return this.rootModule.nameForCondition(); + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); } +} +module.exports = AMDDefineDependencyParserPlugin; - 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(); +/***/ 85812: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @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; - }); - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); +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); - return list; - } +const NullFactory = __webpack_require__(40438); - _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"); +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; } - 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 + 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; + }); }; - default: - throw new Error(`Unsupported concatenation entry type ${info.type}`); + + 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; - // 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() - ); +/***/ 63960: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 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() - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 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; - } +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; } - // List of all used names to avoid conflicts - const allUsedNames = new Set([ - "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name + if (dep.localModule) { + return dep.localModule.variableName(); + } else { + return runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + } + } +}; - "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.exports = AMDRequireArrayDependency; - "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", +/***/ 99890: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - "onblur", - "onclick", - "onerror", - "onfocus", - "onkeydown", - "onkeypress", - "onkeyup", - "onmouseover", - "onload", - "onmouseup", - "onmousedown", - "onsubmit" - ]); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Set of already checked scopes - const alreadyCheckedScopes = new Set(); - // get all global names - for (const info of modulesWithInfo) { - const superClassExpressions = []; +const ContextDependency = __webpack_require__(11583); +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } - // ignore symbols from moduleScope - if (info.moduleScope) { - alreadyCheckedScopes.add(info.moduleScope); + get type() { + return "amd require context"; + } +} +AMDRequireContextDependency.Template = __webpack_require__(54380); +module.exports = AMDRequireContextDependency; - // 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); - } - } - } - } +/***/ 32894: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 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; - } - } +"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); + } - // 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); + newRequireDependency() { + return new AMDRequireDependency(this); + } +}; + + +/***/ }), + +/***/ 9994: +/***/ (function(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; + } - // 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(); + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); + } - 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"); + 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); } - } 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); - } + } + 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; } - - 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` - ); + } + 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); + } } - } - - // 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` + 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 ); - 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}`); + } 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; } - - 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, - "" + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + {}, + parser ); - - 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; + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } - harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.harmonyInit( - dep, - source, - runtimeTemplate, - dependencyTemplates + processArrayForRequestString(param) { + if (param.isArray()) { + const result = param.items.map(item => + this.processItemForRequestString(item) ); - return; + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return param.array.join(" "); } } - 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; + 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; } - source.replace(dep.range[0], dep.range[1] - 1, content); } -} -class HarmonyImportSideEffectDependencyConcatenatedTemplate { - constructor(originalTemplate, modulesMap) { - this.originalTemplate = originalTemplate; - this.modulesMap = modulesMap; - } + processCallRequire(parser, expr) { + let param; + let dep; + let result; - getHarmonyInitOrder(dep) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - return this.originalTemplate.getHarmonyInitOrder(dep); - } - return NaN; - } + const old = parser.state.current; - harmonyInit(dep, source, runtime, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.harmonyInit( - dep, - source, - runtime, - dependencyTemplates + 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) ); - 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; + parser.state.current = dep; } - } -} - -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 (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 (dep.range) { - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - content + "(" + dep.prefix - ); - source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); - return; + 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; } + } - source.replace( - dep.rangeStatement[0], - dep.rangeStatement[1] - 1, - content + dep.prefix + 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); + } } - -class NullTemplate { - apply() {} -} - -module.exports = ConcatenatedModule; +module.exports = AMDRequireDependenciesBlockParserPlugin; /***/ }), -/***/ 29720: +/***/ 73985: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103680,77 +98150,172 @@ module.exports = ConcatenatedModule; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const GraphHelpers = __webpack_require__(32973); +class AMDRequireDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } +} -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 - ); - } - ); +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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); + +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "amd require"; } } -module.exports = EnsureChunkConditionsPlugin; + +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; /***/ }), -/***/ 25850: -/***/ (function(module) { +/***/ 85358: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -103758,105 +98323,164 @@ module.exports = EnsureChunkConditionsPlugin; 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); -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; +const NullFactory = __webpack_require__(40438); - // 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 - ); +const RequireResolveDependencyParserPlugin = __webpack_require__(68349); +const CommonJsRequireDependencyParserPlugin = __webpack_require__(37278); - // 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++; - } +const ParserHelpers = __webpack_require__(23999); - // 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); - } +class CommonJsPlugin { + constructor(options) { + this.options = options; + } - 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; + 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() + ); - const chunkBModulesCount = chunkB.getNumberOfModules(); + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); - // ids for empty chunks are not included - if (chunkBModulesCount === 0) continue; + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); - // 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; + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); - // is chunkA in chunkB? + compilation.dependencyFactories.set( + RequireResolveHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); - // we do a cheap check for the hash value - const chunkBHash = chunkModulesHash.get(chunkB); - if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + compilation.dependencyFactories.set( + RequireHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); - // compare all modules - for (const m of chunkA.modulesIterable) { - if (!chunkB.containsModule(m)) continue loopB; - } - chunkB.ids.push(chunkA.id); - } + 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 = FlagIncludedChunksPlugin; +module.exports = CommonJsPlugin; /***/ }), -/***/ 3846: +/***/ 26791: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103865,238 +98489,60 @@ module.exports = FlagIncludedChunksPlugin; Author Tobias Koppers @sokra */ +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); -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 CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; } -}; - -class LimitChunkCountPlugin { - /** - * @param {LimitChunkCountPluginOptions=} options options object - */ - constructor(options) { - if (!options) options = {}; - validateOptions(schema, options, "Limit Chunk Count Plugin"); - this.options = options; + get type() { + return "cjs require context"; } +} - /** - * @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; +CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; - let remainingChunksToMerge = chunks.length - maxChunks; +module.exports = CommonJsRequireContextDependency; - // 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(); +/***/ 37504: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // filter pairs that do not have an integratedSize - // meaning they can NOT be integrated! - if (integratedSize === false) continue; +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); - 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); - } +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } - // 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; - } - ); - }); + get type() { + return "cjs require"; } } -module.exports = LimitChunkCountPlugin; + +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = CommonJsRequireDependency; /***/ }), -/***/ 46214: -/***/ (function(module) { +/***/ 37278: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -104105,83 +98551,143 @@ module.exports = LimitChunkCountPlugin; */ -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(); +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); - // 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; - } - } +class CommonJsRequireDependencyParserPlugin { + constructor(options) { + this.options = options; + } - // 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); - } - } - } + apply(parser) { + const options = this.options; - // don't check already processed chunks twice - notDuplicates.add(chunk); - } - } + 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 = MergeDuplicateChunksPlugin; +module.exports = CommonJsRequireDependencyParserPlugin; /***/ }), -/***/ 55607: +/***/ 71101: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104190,88 +98696,39 @@ module.exports = MergeDuplicateChunksPlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -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; +class ConstDependency extends NullDependency { + constructor(expression, range, requireWebpackRequire) { + super(); + this.expression = expression; + this.range = range; + this.requireWebpackRequire = requireWebpackRequire; } - 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; + updateHash(hash) { + hash.update(this.range + ""); + hash.update(this.expression + ""); + } +} - const pair = sortedSizeFilteredExtendedPairCombinations[0]; +ConstDependency.Template = class ConstDependencyTemplate { + apply(dep, source) { + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } - pair[2].integrate(pair[3], "min-size"); - chunks.splice(chunks.indexOf(pair[3]), 1); - return true; - } - ); - }); + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); } -} -module.exports = MinChunkSizePlugin; +}; + +module.exports = ConstDependency; /***/ }), -/***/ 25472: +/***/ 11583: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104280,36 +98737,75 @@ module.exports = MinChunkSizePlugin; Author Tobias Koppers @sokra */ +const Dependency = __webpack_require__(57282); +const CriticalDependencyWarning = __webpack_require__(54983); -const WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); +const regExpToString = r => (r ? r + "" : ""); -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]}`; +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; } - 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." + } + + 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; + } } -module.exports = MinMaxSizeWarning; +// 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; /***/ }), -/***/ 45184: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 5594: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -104318,491 +98814,365 @@ module.exports = MinMaxSizeWarning; */ -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 ContextDependencyHelpers = exports; -const formatBailoutReason = msg => { - return "ModuleConcatenation bailout: " + msg; +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quotemeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); }; -class ModuleConcatenationPlugin { - constructor(options) { - if (typeof options !== "object") options = {}; - this.options = options; +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; } + return { + context, + prefix + }; +}; - 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()"; - }); - }; +const splitQueryFromPostfix = postfix => { + const idx = postfix.indexOf("?"); + let query = ""; + if (idx >= 0) { + query = postfix.substr(idx); + postfix = postfix.substr(0, idx); + } + return { + postfix, + query + }; +}; - 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); +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 bailoutReasonMap = new Map(); + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { postfix, query } = splitQueryFromPostfix(postfixRaw); - const setBailoutReason = (module, reason) => { - bailoutReasonMap.set(module, reason); - module.optimizationBailout.push( - typeof reason === "function" - ? rs => formatBailoutReason(reason(rs)) - : formatBailoutReason(reason) - ); - }; + // When there are more than two quasis, the generated RegExp can be more precise + // We join the quasis with the expression regexp + const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); + const innerRegExp = + options.wrappedContextRegExp.source + + innerQuasis + .map(q => quotemeta(q.string) + options.wrappedContextRegExp.source) + .join(""); - const getBailoutReason = (module, requestShortener) => { - const reason = bailoutReasonMap.get(module); - if (typeof reason === "function") return reason(requestShortener); - return reason; - }; + // 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 = []; - 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; - } + 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); + } + } + }); - // 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; - } + 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"; - // Exports must be known (and not dynamic) - if (!Array.isArray(module.buildMeta.providedExports)) { - setBailoutReason(module, "Module exports are unknown"); - continue; - } + if (parser && param.wrappedInnerExpressions) { + for (const part of param.wrappedInnerExpressions) { + if (part.expression) parser.walkExpression(part.expression); + } + } - // 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; - } + 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"; - // 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; - } + if (parser) { + parser.walkExpression(param.expression); + } - relevantModules.push(module); + return dep; + } +}; - // 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; - } +/***/ 6174: +/***/ (function(module) { - 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; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // create a configuration with the root - const currentConfiguration = new ConcatConfiguration(currentRoot); - // cache failures to add modules - const failureCache = new Map(); +class ContextDependencyTemplateAsId { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); - // 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) - ); + 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` ); } - ); - } - - _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; + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } + } +} +module.exports = ContextDependencyTemplateAsId; - // 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); +/***/ 54380: +/***/ (function(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; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); +class ContextDependencyTemplateAsRequireCall { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); - // 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); + 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); } - } - 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(); + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } } +} +module.exports = ContextDependencyTemplateAsRequireCall; - 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); - } +/***/ 89079: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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; - }) - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getModules() { - return this.modules.asSet(); - } +const ModuleDependency = __webpack_require__(90865); - clone() { - return new ConcatConfiguration(this.rootModule, this); +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest) { + super(request); + if (userRequest) { + this.userRequest = userRequest; + } } - set(config) { - this.rootModule = config.rootModule; - this.modules = config.modules; - this.warnings = config.warnings; + get type() { + return "context element"; } } -module.exports = ModuleConcatenationPlugin; +module.exports = ContextElementDependency; /***/ }), -/***/ 68053: -/***/ (function(module) { +/***/ 54983: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -104811,46 +99181,25 @@ module.exports = ModuleConcatenationPlugin; */ -/** @typedef {import("../Compiler")} Compiler */ +const WebpackError = __webpack_require__(97391); -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; - } - }); - } - ); - }); +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); + + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = NaturalChunkOrderPlugin; +module.exports = CriticalDependencyWarning; /***/ }), -/***/ 83741: +/***/ 53104: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104860,71 +99209,38 @@ module.exports = NaturalChunkOrderPlugin; */ -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(88771); - -/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ +const DependencyReference = __webpack_require__(71722); +const NullDependency = __webpack_require__(5088); -class OccurrenceOrderChunkIdsPlugin { - /** - * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); - this.options = options; +class DelegatedExportsDependency extends NullDependency { + constructor(originModule, exports) { + super(); + this.originModule = originModule; + this.exports = exports; } - 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(); + get type() { + return "delegated exports"; + } - 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++); - } + getReference() { + return new DependencyReference(this.originModule, true, false); + } - 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; - }); - } - ); - } - ); + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; } } -module.exports = OccurrenceOrderChunkIdsPlugin; +module.exports = DelegatedExportsDependency; /***/ }), -/***/ 62000: +/***/ 25930: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104933,119 +99249,97 @@ module.exports = OccurrenceOrderChunkIdsPlugin; Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(81430); - -/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderModuleIdsPlugin").OccurrenceOrderModuleIdsPluginOptions} OccurrenceOrderModuleIdsPluginOptions */ +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); + } -class OccurrenceOrderModuleIdsPlugin { - /** - * @param {OccurrenceOrderModuleIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validateOptions(schema, options, "Occurrence Order Module Ids Plugin"); - this.options = options; + get type() { + return "delegated source"; } +} - 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(); +module.exports = DelegatedSourceDependency; - 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); - } - } +/***/ 71722: +/***/ (function(module) { - 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++); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ - 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; - }); - } - ); + +/** @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 = OccurrenceOrderModuleIdsPlugin; +module.exports = DependencyReference; /***/ }), -/***/ 67340: -/***/ (function(module) { +/***/ 66279: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -105053,142 +99347,83 @@ module.exports = OccurrenceOrderModuleIdsPlugin; Author Tobias Koppers @sokra */ +const Dependency = __webpack_require__(57282); -// 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; +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; } - 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); - } + get type() { + return "dll 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(); - }; +module.exports = DllEntryDependency; - 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(); +/***/ 75159: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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++); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; - }); - } - ); - }); + +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"; } } -module.exports = OccurrenceOrderPlugin; +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; /***/ }), -/***/ 78085: -/***/ (function(module) { +/***/ 66136: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -105196,48 +99431,29 @@ module.exports = OccurrenceOrderPlugin; Author Tobias Koppers @sokra */ +const HarmonyImportDependency = __webpack_require__(81599); -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 - ); - }); +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request, originModule, parserScope) { + super(request, originModule, NaN, parserScope); + this.weak = true; + } + + get type() { + return "harmony accept"; } } -module.exports = RemoveEmptyChunksPlugin; + +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) {} +}; + +module.exports = HarmonyAcceptImportDependency; /***/ }), -/***/ 58142: +/***/ 1533: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105246,134 +99462,38 @@ module.exports = RemoveEmptyChunksPlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const Queue = __webpack_require__(38637); -const { intersect } = __webpack_require__(54262); +class HarmonyCompatibilityDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } -const getParentChunksWithModule = (currentChunk, module) => { - const chunks = []; - const stack = new Set(currentChunk.parentsIterable); + get type() { + return "harmony export header"; + } +} - for (const chunk of stack) { - if (chunk.containsModule(module)) { - chunks.push(chunk); - } else { - for (const parent of chunk.parentsIterable) { - stack.add(parent); - } +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); } } - - 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; +module.exports = HarmonyCompatibilityDependency; /***/ }), -/***/ 76894: -/***/ (function(module) { +/***/ 59310: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -105382,46 +99502,101 @@ module.exports = RemoveParentModulesPlugin; */ -module.exports = class RuntimeChunkPlugin { - constructor(options) { - this.options = Object.assign( - { - name: entrypoint => `runtime~${entrypoint.name}` - }, - options - ); - } +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const HarmonyInitDependency = __webpack_require__(27204); - 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); - } +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); + } } }; /***/ }), -/***/ 83654: +/***/ 49180: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105431,357 +99606,225 @@ module.exports = class RuntimeChunkPlugin { */ -const mm = __webpack_require__(67849); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyExportExpressionDependency = __webpack_require__(84245); 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 - */ +const HarmonyExportHeaderDependency = __webpack_require__(21320); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const ConstDependency = __webpack_require__(71101); -/** - * @typedef {Object} ReexportInfo - * @property {Map} static - * @property {Map>} dynamic - */ +module.exports = class HarmonyExportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + } -/** - * @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; + 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; } - } - } 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 + ); + 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 ); - 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; + 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 || []; } - }); - }); - compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { - compilation.hooks.optimizeDependencies.tap( - "SideEffectsFlagPlugin", - modules => { - /** @type {Map} */ - const reexportMaps = new Map(); + 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; + } + ); + } +}; - // 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); - } - } +/***/ 84245: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 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; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; - } - } +const NullDependency = __webpack_require__(5088); - // Update reexport as all other cases has been handled - addDynamicReexport(info, targetModule, ignored); - } - } +class HarmonyExportExpressionDependency extends NullDependency { + constructor(originModule, range, rangeStatement, prefix) { + super(); + this.originModule = originModule; + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + } - 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; + get type() { + return "harmony export expression"; + } - const newMapping = getMappingFromInfo( - innerInfo, - mapping.exportName - ); - if (!newMapping) break; - mapping = newMapping; - } - addStaticReexport( - info, - key, - mapping.module, - mapping.exportName, - mapping.checked - ); - } - } - } + getExports() { + return { + exports: ["default"], + dependencies: undefined + }; + } +} - // 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; - } - } - } +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); } - 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) - ); + 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 = SideEffectsFlagPlugin; +}; + +module.exports = HarmonyExportExpressionDependency; /***/ }), -/***/ 60474: +/***/ 21320: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105790,1212 +99833,703 @@ module.exports = SideEffectsFlagPlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -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); +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + } -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); + get type() { + return "harmony export header"; } - return requests; -}; +} -const getModulesSize = modules => { - let sum = 0; - for (const m of modules) { - sum += m.size(); +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); } - 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; -}; +module.exports = HarmonyExportHeaderDependency; -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; +/***/ 22864: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = class SplitChunksPlugin { - constructor(options) { - this.options = SplitChunksPlugin.normalizeOptions(options); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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 - ) - }; + +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; } +} - static normalizeName({ +const EMPTY_STAR_MODE = new ExportMode("empty-star"); + +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, 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; + 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; } - 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; + get type() { + return "harmony export imported specifier"; } - 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 || "~" - }; + get _id() { + return this.redirectedId || this.id; } - 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; + 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 (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; + + if ( + !ignoreUnused && + (name ? !used : this.originModule.usedExports === false) + ) { + const mode = new ExportMode("unused"); + mode.name = name || "*"; + return mode; } - 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()); + 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; } - 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; + + 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]]); } - } - 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; + } 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; } } - return false; + mode.module = importedModule; + return mode; } - 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)); - } - } + const hasUsedExports = Array.isArray(this.originModule.usedExports); + const hasProvidedExports = Array.isArray( + importedModule.buildMeta.providedExports + ); + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); - // 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); - } + // 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]) + ); - // Create a list of possible combinations - const combinationsCache = new Map(); // Map[]> + if (map.size === 0) { + return EMPTY_STAR_MODE; + } - 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; - }; + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } - /** - * @typedef {Object} SelectedChunksResult - * @property {Chunk[]} chunks the list of chunks - * @property {string} key a key of the list - */ + 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; - /** - * @typedef {function(Chunk): boolean} ChunkFilterFunction - */ + return true; + }) + .map(item => [item, item]) + ); - /** @type {WeakMap, WeakMap>} */ - const selectedChunksCacheByChunksSet = new WeakMap(); + if (map.size === 0) { + return EMPTY_STAR_MODE; + } - /** - * 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; - }; + const mode = new ExportMode("checked-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } - /** - * @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 - */ + 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; - // Map a list of chunks to a list of modules - // For the key the chunk "index" is used, the value is a SortableSet of modules - /** @type {Map} */ - const chunksInfoMap = new Map(); + return true; + }) + .map(item => [item, item]) + ); - /** - * @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); - } - } - }; + if (map.size === 0) { + return EMPTY_STAR_MODE; + } - // 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; - } + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } - // Prepare some values - const chunksKey = getKey(module.chunksIterable); - let combs = combinationsCache.get(chunksKey); - if (combs === undefined) { - combs = getCombinations(chunksKey); - combinationsCache.set(chunksKey, combs); - } + const mode = new ExportMode("dynamic-reexport"); + mode.module = importedModule; + mode.ignored = new Set([ + "default", + ...this.activeExports, + ...activeFromOtherStarExports + ]); + return mode; + } - 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 - ); + getReference() { + const mode = this.getMode(false); - addModuleToChunksInfoMap( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ); - } - cacheGroupIndex++; - } - } + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + return null; - // 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]); - } - } + case "reexport-non-harmony-default": + case "reexport-named-default": + return new DependencyReference( + mode.module, + ["default"], + false, + this.sourceOrder + ); - /** @type {Map} */ - const maxSizeQueueMap = new Map(); + 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 + ); - 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; - } - } + case "safe-reexport": + case "checked-reexport": + return new DependencyReference( + mode.module, + Array.from(mode.map.values()), + false, + this.sourceOrder + ); - const item = bestEntry; - chunksInfoMap.delete(bestEntryKey); + case "dynamic-reexport": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder + ); - 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 + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } - const selectedChunks = Array.from(item.chunks).filter(chunk => { - // skip if we address ourself - return ( - (!chunkName || chunk.name !== chunkName) && chunk !== newChunk - ); - }); + _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; + } - const enforced = - item.cacheGroup._conditionalEnforce && - item.size >= item.cacheGroup.enforceSizeThreshold; + getExports() { + if (this.name) { + return { + exports: [this.name], + dependencies: undefined + }; + } - // Skip when no chunk selected - if (selectedChunks.length === 0) continue; + const importedModule = this._module; - const usedChunks = new Set(selectedChunks); + if (!importedModule) { + // no imported module available + return { + exports: null, + dependencies: undefined + }; + } - // 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); - } - } - } + 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] + }; + } - outer: for (const chunk of usedChunks) { - for (const module of item.modules) { - if (chunk.containsModule(module)) continue outer; - } - usedChunks.delete(chunk); - } + if (importedModule.buildMeta.providedExports) { + return { + exports: true, + dependencies: undefined + }; + } - // 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; - } + return { + exports: null, + dependencies: [importedModule] + }; + } - // 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); - } + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } - // 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; - } - } - } - } - ); - }); + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; } -}; - -/***/ }), - -/***/ 89339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + 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; + } -const WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } -module.exports = class AssetsOverSizeLimitWarning extends WebpackError { - constructor(assetsOverSizeLimit, assetLimit) { - const assetLists = assetsOverSizeLimit - .map( - asset => - `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` - ) - .join(""); + // 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)]; + } - super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( - assetLimit - )}). -This can impact web performance. -Assets: ${assetLists}`); + updateHash(hash) { + super.updateHash(hash); + const hashValue = this.getHashValue(this._module); + hash.update(hashValue); + } - this.name = "AssetsOverSizeLimitWarning"; - this.assets = assetsOverSizeLimit; + getHashValue(importedModule) { + if (!importedModule) { + return ""; + } - Error.captureStackTrace(this, this.constructor); + const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); + const stringifiedProvidedExport = JSON.stringify( + importedModule.buildMeta.providedExports + ); + return ( + importedModule.used + stringifiedUsedExport + stringifiedProvidedExport + ); } -}; + disconnect() { + super.disconnect(); + this.redirectedId = undefined; + } +} -/***/ }), - -/***/ 41336: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +module.exports = HarmonyExportImportedSpecifierDependency; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ +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 WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); + const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); -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`); + if (Array.isArray(dep.originModule.usedExports)) { + // we know which exports are used - this.name = "EntrypointsOverSizeLimitWarning"; - this.entrypoints = entrypoints; + 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 - Error.captureStackTrace(this, this.constructor); + 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(); -/***/ }), - -/***/ 53006: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + switch (mode.type) { + case "missing": + return `throw new Error(${JSON.stringify( + `Cannot find module '${mode.userRequest}'` + )});\n`; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + 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 + ) + ); -const WebpackError = __webpack_require__(97391); + case "reexport-named-default": + return ( + "/* harmony reexport (default from named exports) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); -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/" - ); + case "reexport-fake-namespace-object": + return ( + "/* harmony reexport (fake namespace object from non-harmony) */ " + + this.getReexportFakeNamespaceObjectStatement( + module, + module.isUsed(mode.name), + importVar + ) + ); - this.name = "NoAsyncChunksWarning"; + case "rexport-non-harmony-undefined": + return ( + "/* harmony reexport (non default export from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + "undefined", + "" + ) + ); - Error.captureStackTrace(this, this.constructor); - } -}; + 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 */"; -/***/ 68310: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + 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(""); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + 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(""); -const EntrypointsOverSizeLimitWarning = __webpack_require__(41336); -const AssetsOverSizeLimitWarning = __webpack_require__(89339); -const NoAsyncChunksWarning = __webpack_require__(53006); + case "dynamic-reexport": { + const ignoredExports = mode.ignored; + let content = + "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + + importVar + + ") "; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint")} Entrypoint */ + // 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` + ); + } -module.exports = class SizeLimitsPlugin { - constructor(options) { - this.hints = options.hints; - this.maxAssetSize = options.maxAssetSize; - this.maxEntrypointSize = options.maxEntrypointSize; - this.assetFilter = options.assetFilter; + default: + throw new Error(`Unknown mode ${mode.type}`); + } } - /** - * @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; - } - } + 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`; + } - 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 - ) - ); - } + getReexportFakeNamespaceObjectStatement(module, key, name) { + const exportsName = module.exportsArgument; + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return __webpack_require__.t(${name}); });\n`; + } - if (warnings.length > 0) { - const hasAsyncChunks = - compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > - 0; + 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`; + } - if (!hasAsyncChunks) { - warnings.push(new NoAsyncChunksWarning()); - } + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } + if (valueKey === "") { + return name; + } + if (valueKey === false) { + return "/* unused export */ undefined"; + } - if (hints === "error") { - compilation.errors.push(...warnings); - } else { - compilation.warnings.push(...warnings); - } - } - } - }); + return `${name}[${JSON.stringify(valueKey)}]`; } }; /***/ }), -/***/ 52315: +/***/ 34834: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -107004,560 +100538,446 @@ module.exports = class SizeLimitsPlugin { Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); - -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; +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(originModule, id, name) { + super(); + this.originModule = originModule; + this.id = id; + this.name = name; } - /** - * @param {T} item an item - * @returns {void} - */ - add(item) { - this.size++; - this._unsortedItems.add(item); + get type() { + return "harmony export specifier"; } - /** - * @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); + getExports() { + return { + exports: [this.name], + dependencies: undefined + }; } +} - /** - * @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); - } - } +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { + apply(dep, source) {} - /** - * @param {K} key key to be removed - * @returns {void} - */ - _deleteKey(key) { - this._keys.delete(key); - this._map.delete(key); + getHarmonyInitOrder(dep) { + return 0; } - /** - * @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; - } + harmonyInit(dep, source, runtime) { + const content = this.getContent(dep); + source.insert(-1, content); } - /** - * @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); - } - }; + getContent(dep) { + const used = dep.originModule.isUsed(dep.name); + if (!used) { + return `/* unused harmony export ${dep.name || "namespace"} */\n`; } - } - /** - * @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); - } - } - } + const exportsName = dep.originModule.exportsArgument; - /** - * @returns {Iterator} the iterator - */ - [Symbol.iterator]() { - const iterators = []; - this._appendIterators(iterators); - iterators.reverse(); - let currentIterator = iterators.pop(); - return { - next: () => { - const res = currentIterator.next(); - if (res.done) { - if (iterators.length === 0) return res; - currentIterator = iterators.pop(); - return currentIterator.next(); - } - return res; - } - }; + return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( + used + )}, function() { return ${dep.id}; });\n`; } -} +}; -module.exports = LazyBucketSortedSet; +module.exports = HarmonyExportSpecifierDependency; /***/ }), -/***/ 38637: -/***/ (function(module) { +/***/ 81599: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @template T - */ -class Queue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {Set} */ - this.set = new Set(items); - /** @private @type {Iterator} */ - this.iterator = this.set[Symbol.iterator](); +const 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; } - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this.set.size; + get _module() { + return this.redirectedModule || this.module; } - /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} - */ - enqueue(item) { - this.set.add(item); + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + false, + this.weak, + this.sourceOrder + ); } - /** - * 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; + 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; } -} -module.exports = Queue; + 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; + } +} -/***/ 33349: -/***/ (function(module) { +module.exports = HarmonyImportDependency; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const importEmittedMap = new WeakMap(); +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { + apply(dep, source, runtime) { + // no-op + } -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); + getHarmonyInitOrder(dep) { + return dep.sourceOrder; } - /** - * @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); - } + 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); } - _continue() { - if (this.available > 0) { - if (this.waiters.length > 0) { - this.available--; - const callback = this.waiters.pop(); - callback(); - } + 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); } -} - -module.exports = Semaphore; +}; /***/ }), -/***/ 54262: -/***/ (function(__unused_webpack_module, exports) { +/***/ 99433: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "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 - * @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 { SyncBailHook } = __webpack_require__(56758); +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; } - 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); + + 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); + } + } + ); } - 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: -/***/ (function(module) { +/***/ 79171: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +const HarmonyImportDependency = __webpack_require__(81599); -/** - * 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); +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + constructor(request, originModule, sourceOrder, parserScope) { + super(request, originModule, sourceOrder, parserScope); } - /** - * 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; - } + getReference() { + if (this._module && this._module.factoryMeta.sideEffectFree) return null; - /** - * @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; + return super.getReference(); } - /** - * @private - * @returns {void} - */ - _invalidateCache() { - if (this._cache !== undefined) { - this._cache.clear(); - } + get type() { + return "harmony side effect evaluation"; } +} - /** - * @private - * @returns {void} - */ - _invalidateOrderedCache() { - if (this._cacheOrderIndependent !== undefined) { - this._cacheOrderIndependent.clear(); - } +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { + getHarmonyInitOrder(dep) { + if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; + return super.getHarmonyInitOrder(dep); } -} +}; -module.exports = SortableSet; +module.exports = HarmonyImportSideEffectDependency; /***/ }), -/***/ 92251: +/***/ 95966: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -107567,148 +100987,169 @@ module.exports = SortableSet; */ -const util = __webpack_require__(31669); +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const HarmonyLinkingError = __webpack_require__(30327); -const TOMBSTONE = {}; -const UNDEFINED_MARKER = {}; +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; + } -class StackedSetMap { - constructor(parentStack) { - this.stack = parentStack === undefined ? [] : parentStack.slice(); - this.map = new Map(); - this.stack.push(this.map); + get type() { + return "harmony import specifier"; } - add(item) { - this.map.set(item, true); + get _id() { + return this.redirectedId || this.id; } - set(item, value) { - this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + this._id && !this.namespaceObjectAsContext ? [this._id] : true, + false, + this.sourceOrder + ); } - delete(item) { - if (this.stack.length > 1) { - this.map.set(item, TOMBSTONE); - } else { - this.map.delete(item); + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; } + return this._getErrors(); } - 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); + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); } - return false; + return []; } - 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); + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; } - 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]); - } + 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; } - this.stack = [this.map]; - } - asArray() { - this._compress(); - return Array.from(this.map.entries(), pair => pair[0]); - } + if (!this._id) { + return; + } - asSet() { - return new Set(this.asArray()); - } + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } - asPairArray() { - this._compress(); - return Array.from(this.map.entries(), pair => - /** @type {[TODO, TODO]} */ (pair[1] === UNDEFINED_MARKER - ? [pair[0], undefined] - : pair) - ); + // 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)]; } - asMap() { - return new Map(this.asPairArray()); + // implement this method to allow the occurrence order plugin to count correctly + getNumberOfIdOccurrences() { + return 0; } - get size() { - this._compress(); - return this.map.size; + 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)) + "" + ); } - createChild() { - return new StackedSetMap(this.stack); + disconnect() { + super.disconnect(); + this.redirectedId = undefined; } +} - get length() { - throw new Error("This is no longer an Array"); +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); } - set length(value) { - throw new Error("This is no longer an Array"); + 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; } -} - -// 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; +module.exports = HarmonyImportSpecifierDependency; /***/ }), -/***/ 67916: -/***/ (function(__unused_webpack_module, exports) { +/***/ 27204: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -107717,83 +101158,66 @@ module.exports = StackedSetMap; */ +const NullDependency = __webpack_require__(5088); -const mergeCache = new WeakMap(); +class HarmonyInitDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } -/** - * 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); + get type() { + return "harmony init"; } - 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); +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 + }); } } - newObject[key] = newArray; - } else { - newObject[key] = secondValue; + } + + 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 + ); } } - return newObject; }; -exports.cachedCleverMerge = cachedCleverMerge; -exports.cleverMerge = cleverMerge; - /***/ }), -/***/ 15660: -/***/ (function(module, exports, __webpack_require__) { +/***/ 66792: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -107801,760 +101225,707 @@ exports.cleverMerge = cleverMerge; 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 AbstractMethodError = __webpack_require__(36104); +const NullFactory = __webpack_require__(40438); -const BULK_SIZE = 1000; +const HarmonyDetectionParserPlugin = __webpack_require__(59310); +const HarmonyImportDependencyParserPlugin = __webpack_require__(99433); +const HarmonyExportDependencyParserPlugin = __webpack_require__(49180); +const HarmonyTopLevelThisParserPlugin = __webpack_require__(58215); -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(); +class HarmonyModulesPlugin { + constructor(options) { + this.options = options; } - /** - * 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(); - } -} + apply(compiler) { + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + HarmonyCompatibilityDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); -exports.Hash = Hash; -/** @typedef {typeof Hash} HashConstructor */ + compilation.dependencyFactories.set( + HarmonyInitDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyInitDependency, + new HarmonyInitDependency.Template() + ); -class BulkUpdateDecorator extends Hash { - /** - * @param {Hash} hash hash - */ - constructor(hash) { - super(); - this.hash = hash; - this.buffer = ""; - } + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); - /** - * 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; - } + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); - /** - * 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(); - } -} + compilation.dependencyFactories.set( + HarmonyExportHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); -/** - * istanbul ignore next - */ -class DebugHash extends Hash { - constructor() { - super(); - this.string = ""; - } + compilation.dependencyFactories.set( + HarmonyExportExpressionDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); - /** - * 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; - } + compilation.dependencyFactories.set( + HarmonyExportSpecifierDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); - /** - * 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") + 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); + } ); } } - -/** - * 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)); - } -}; +module.exports = HarmonyModulesPlugin; /***/ }), -/***/ 30815: -/***/ (function(module) { +/***/ 58215: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ -// 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; - } -} +const ConstDependency = __webpack_require__(71101); -/** - * @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; +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); + } + }); } } -/** - * @template T - * @typedef {Object} GroupedItems - * @property {string} key - * @property {T[]} items - * @property {number} size - */ +module.exports = HarmonyTopLevelThisParserPlugin; -/** - * @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)) - ); +/***/ 20417: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Node[]} */ - const initialNodes = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // lexically ordering of keys - nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); - // 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); - } +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; } - 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); + get type() { + return `import() context ${this.options.mode}`; + } +} - 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]; +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - while (queue.length) { - const group = queue.pop(); - // only groups bigger than maxSize need to be splitted - if (group.size < maxSize) { - result.push(group); - continue; - } +module.exports = ImportContextDependency; - // 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)); +/***/ 38875: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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)); - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 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; - }); +const AsyncDependenciesBlock = __webpack_require__(22814); +const ImportDependency = __webpack_require__(50883); - // 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; +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); } - - // return the results - return result.map(group => { - /** @type {GroupedItems} */ - return { - key: group.key, - items: group.nodes.map(node => node.item), - size: group.size - }; - }); }; /***/ }), -/***/ 94658: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 50883: +/***/ (function(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 ModuleDependency = __webpack_require__(90865); -/** - * @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; -}; +class ImportDependency extends ModuleDependency { + constructor(request, originModule, block) { + super(request); + this.originModule = originModule; + this.block = block; + } -/** - * @typedef {Object} MakeRelativePathsCache - * @property {Map>=} relativePaths - */ + get type() { + return "import()"; + } +} -/** - * - * @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; +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); } - return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); }; -/** - * - * @param {string} p path to normalize - * @returns {string} normalized version of path - */ -const normalizePathSeparator = p => p.replace(/\\/g, "/"); +module.exports = ImportDependency; -/** - * - * @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()); +/***/ 25552: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let cachedResult; - let contextCache = relativePaths.get(context); - if (contextCache === undefined) { - relativePaths.set(context, (contextCache = new Map())); - } else { - cachedResult = contextCache.get(identifier); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (cachedResult !== undefined) { - return cachedResult; - } else { - const relativePath = _makePathsRelative(context, identifier); - contextCache.set(identifier, relativePath); - return relativePath; +const ModuleDependency = __webpack_require__(90865); + +class ImportEagerDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; } -}; -/** - * @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("!"); -}; + get type() { + return "import() eager"; + } +} -/** - * @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("!"); +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); + } }; -exports.absolutify = _absolutify; +module.exports = ImportEagerDependency; /***/ }), -/***/ 1111: -/***/ (function(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: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 93382: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Gajus Kuizinas @gajus + Author Tobias Koppers @sokra */ -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 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); -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); +class ImportParserPlugin { + constructor(options) { + this.options = options; } -}; -const validateObject = (schema, options) => { - const validate = ajv.compile(schema); - const valid = validate(options); - return valid ? [] : filterErrors(validate.errors); -}; + 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 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)); + 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 + ) + ); } - oldError.children = undefined; - children.push(oldError); - return false; } - return true; + + 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; + } }); - if (children.length) { - err.children = children; - } - newErrors.push(err); } +} - return newErrors; -}; - -module.exports = validateSchema; +module.exports = ImportParserPlugin; /***/ }), -/***/ 43101: +/***/ 58839: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(97391); +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); -module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "UnsupportedWebAssemblyFeatureError"; - this.hideStack = true; +class ImportPlugin { + constructor(options) { + this.options = options; + } - Error.captureStackTrace(this, this.constructor); + 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; /***/ }), -/***/ 10557: +/***/ 86817: /***/ (function(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 - ); +const ModuleDependency = __webpack_require__(90865); - if (!ref) continue; +class ImportWeakDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; + this.weak = true; + } - const importedNames = ref.importedNames; + get type() { + return "import() weak"; + } +} - 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); - } - }); - } - } - } - } - } - } - ); +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 = WasmFinalizeExportsPlugin; +module.exports = ImportWeakDependency; /***/ }), -/***/ 65331: +/***/ 54396: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -108563,348 +101934,185 @@ module.exports = WasmFinalizeExportsPlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const Template = __webpack_require__(96066); -const WebAssemblyUtils = __webpack_require__(52136); +class JsonExportsDependency extends NullDependency { + constructor(exports) { + super(); + this.exports = exports; + } -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../MainTemplate")} MainTemplate */ + get type() { + return "json exports"; + } -// 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); - } - } + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; } +} - return array; -}; +module.exports = JsonExportsDependency; -/** - * 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 - ); +/***/ 1129: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const mod = `installedModules[${JSON.stringify(importedModule.id)}]`; - const func = `${mod}.exports[${JSON.stringify(usedName)}]`; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - properties.push({ - module, - name, - value: Template.asString([ - (importedModule.type.startsWith("webassembly") - ? `${mod} ? ${func} : ` - : "") + `function(${params}) {`, - Template.indent([`return ${func}(${params});`]), - "}" - ]) - }); - } - } +const ModuleDependency = __webpack_require__(90865); - let importObject; - if (mangle) { - importObject = [ - "return {", - Template.indent([ - properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "};" - ]; - } else { - const propertiesByModule = new Map(); - for (const p of properties) { - let list = propertiesByModule.get(p.module); - if (list === undefined) { - propertiesByModule.set(p.module, (list = [])); - } - list.push(p); - } - importObject = [ - "return {", - Template.indent([ - Array.from(propertiesByModule, ([module, list]) => { - return Template.asString([ - `${JSON.stringify(module)}: {`, - Template.indent([ - list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "}" - ]); - }).join(",\n") - ]), - "};" - ]; +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); } - 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), - "}," - ]); + get type() { + return "loader"; } -}; +} -class WasmMainTemplatePlugin { - constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; - this.mangleImports = mangleImports; - } +module.exports = LoaderDependency; - /** - * @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), - "};" - ]); + +/***/ }), + +/***/ 31559: +/***/ (function(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 + ); } ); - 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); - } + 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] } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[wasmModuleId] + "`; + ], + 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); + }); } - } - } - ); - 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; +module.exports = LoaderPlugin; /***/ }), -/***/ 13099: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 17356: +/***/ (function(module) { "use strict"; /* @@ -108913,559 +102121,328 @@ module.exports = WasmMainTemplatePlugin; */ -const Generator = __webpack_require__(39172); -const Template = __webpack_require__(96066); -const WebAssemblyUtils = __webpack_require__(52136); -const { RawSource } = __webpack_require__(53665); +class LocalModule { + constructor(module, name, idx) { + this.module = module; + this.name = name; + this.idx = idx; + this.used = false; + } -const { editWithAST, addWithAST } = __webpack_require__(65584); -const { decode } = __webpack_require__(27352); -const t = __webpack_require__(81875); -const { - moduleContextFromModuleAST -} = __webpack_require__(71234); + flagUsed() { + this.used = true; + } -const WebAssemblyExportImportedDependency = __webpack_require__(18925); + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } +} +module.exports = LocalModule; -/** @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 - ); -}; +/***/ 56570: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -// TODO replace with @callback +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * 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(); - } - }); -}; +const NullDependency = __webpack_require__(5088); -/** - * Get imported globals - * - * @param {Object} ast Module's AST - * @returns {Array} - nodes - */ -const getImportedGlobals = ast => { - const importedGlobals = []; +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { + super(); + localModule.flagUsed(); + this.localModule = localModule; + this.range = range; + this.callNew = callNew; + } +} - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); - - return importedGlobals; +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); + } }; -/** - * Get the count for imported func - * - * @param {Object} ast Module's AST - * @returns {Number} - count - */ -const getCountImportedFunc = ast => { - let count = 0; +module.exports = LocalModuleDependency; - 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"); +/***/ 39658: +/***/ (function(module, exports, __webpack_require__) { - if (typeSectionMetadata === undefined) { - return t.indexLiteral(0); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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"); +const LocalModule = __webpack_require__(17356); +const LocalModulesHelpers = exports; - if (funcSectionMetadata === undefined) { - return t.indexLiteral(0 + countImportedFunc); - } +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; - const vectorOfSize = funcSectionMetadata.vectorOfSize.value; + var path = parent.split("/"); + var segs = mod.split("/"); + path.pop(); - return t.indexLiteral(vectorOfSize + countImportedFunc); + 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("/"); }; -/** - * 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); +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; }; -/** - * 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 = []; +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; +}; - bin = editWithAST(state.ast, bin, { - ModuleImport(path) { - if (t.isGlobalType(path.node.descr)) { - const globalType = path.node.descr; +module.exports = LocalModulesHelpers; - globalType.mutability = "var"; - const init = [ - createDefaultInitForGlobal(globalType), - t.instruction("end") - ]; +/***/ }), - newGlobals.push(t.global(globalType, init)); +/***/ 90865: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - path.remove(); - } - }, +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // in order to preserve non-imported global's order we need to re-inject - // those as well - Global(path) { - const { node } = path; - const [init] = node.init; +const Dependency = __webpack_require__(57282); - if (init.id === "get_global") { - node.globalType.mutability = "var"; +class ModuleDependency extends Dependency { + /** + * @param {string} request request path which needs resolving + */ + constructor(request) { + super(); + this.request = request; + this.userRequest = request; + } - const initialGlobalidx = init.args[0]; + getResourceIdentifier() { + return `module${this.request}`; + } +} - node.init = [ - createDefaultInitForGlobal(node.globalType), - t.instruction("end") - ]; +module.exports = ModuleDependency; - 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(); - } - }); +/***/ 63708: +/***/ (function(module) { - // Add global declaration instructions - return addWithAST(state.ast, bin, newGlobals); -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * 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 - ); +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; - 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); - }); +/***/ 60441: +/***/ (function(module) { - const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => { - const args = [t.indexLiteral(index)]; - const body = [ - t.instruction("get_local", args), - t.instruction("set_global", args) - ]; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return [...acc, ...body]; - }, []); - if (typeof startAtFuncOffset === "number") { - funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))); +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; - for (const instr of additionalInitCode) { - funcBody.push(instr); - } - funcBody.push(t.instruction("end")); +/***/ }), - const funcResults = []; +/***/ 29018: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Code section - const funcSignature = t.signature(funcParams, funcResults); - const func = t.func(initFuncId, funcSignature, funcBody); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Type section - const functype = t.typeInstruction(undefined, funcSignature); +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); - // Func section - const funcindex = t.indexInFuncSection(nextTypeIndex); +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } - // Export section - const moduleExport = t.moduleExport( - initFuncId.value, - t.moduleExportDescr("Func", nextFuncIndex) - ); + get type() { + return "module.hot.accept"; + } +} - return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); -}; +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; -/** - * 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; -}; +module.exports = ModuleHotAcceptDependency; -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__" - ); +/***/ 60482: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // parse it - const ast = decode(bin, { - ignoreDataSection: true, - ignoreCodeSection: true, - ignoreCustomNameSection: true - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const moduleContext = moduleContextFromModuleAST(ast.body[0]); +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); - const importedGlobals = getImportedGlobals(ast); - const countImportedFunc = getCountImportedFunc(ast); - const startAtFuncOffset = moduleContext.getStart(); - const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); - const nextTypeIndex = getNextTypeIndex(ast); +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } - 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; - }) - ); + get type() { + return "module.hot.decline"; + } +} - /** @type {t.Instruction[]} */ - const additionalInitCode = []; +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - const transform = compose( - rewriteExportNames({ - ast, - module, - externalExports - }), +module.exports = ModuleHotDeclineDependency; - removeStartFunc({ ast }), - rewriteImportedGlobals({ ast, additionalInitCode }), +/***/ }), - rewriteImports({ - ast, - usedDependencyMap - }), +/***/ 7791: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - addInitFunction({ - ast, - initFuncId, - importedGlobals, - additionalInitCode, - startAtFuncOffset, - nextFuncIndex, - nextTypeIndex - }) - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const newBin = transform(bin); +/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ +const Dependency = __webpack_require__(57282); - return new RawSource(newBin); +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 = WebAssemblyGenerator; +module.exports = MultiEntryDependency; /***/ }), -/***/ 45283: +/***/ 5088: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +const Dependency = __webpack_require__(57282); -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); +class NullDependency extends Dependency { + get type() { + return "null"; } - 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; + updateHash() {} +} - Error.captureStackTrace(this, this.constructor); - } +NullDependency.Template = class NullDependencyTemplate { + apply() {} }; +module.exports = NullDependency; + /***/ }), -/***/ 13411: +/***/ 14237: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -109474,158 +102451,24 @@ ${moduleChains.map(s => `* ${s}`).join("\n")}`; Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); -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});` - : "", +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); + } - // 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; + get type() { + return "prefetch"; } } -module.exports = WebAssemblyJavascriptGenerator; +module.exports = PrefetchDependency; /***/ }), -/***/ 99510: +/***/ 79142: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -109634,134 +102477,92 @@ module.exports = WebAssemblyJavascriptGenerator; Author Tobias Koppers @sokra */ +const ContextDependency = __webpack_require__(11583); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); -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 RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); + this.range = range; + } -class WebAssemblyModulesPlugin { - constructor(options) { - this.options = options; + get type() { + return "require.context"; } +} - /** - * @param {Compiler} compiler compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; - compilation.dependencyFactories.set( - WebAssemblyExportImportedDependency, - normalModuleFactory - ); +module.exports = RequireContextDependency; - 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; +/***/ 10566: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (const module of chunk.modulesIterable) { - if (module.type && module.type.startsWith("webassembly")) { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - result.push({ - render: () => - this.renderWebAssembly( - module, - moduleTemplates.webassembly, - dependencyTemplates - ), - filenameTemplate, - pathOptions: { - module - }, - identifier: `webassemblyModule${module.id}`, - hash: module.hash - }); - } - } - return result; - } - ); +const RequireContextDependency = __webpack_require__(79142); - 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); - } - } - } +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; } - for (const module of initialWasmModules) { - compilation.errors.push( - new WebAssemblyInInitialChunkError( - module, - compilation.requestShortener - ) + // 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; } - }); - } - ); - } - - renderWebAssembly(module, moduleTemplate, dependencyTemplates) { - return moduleTemplate.render(module, dependencyTemplates, {}); + } + }); } -} - -module.exports = WebAssemblyModulesPlugin; +}; /***/ }), -/***/ 77703: +/***/ 89042: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -109771,181 +102572,190 @@ module.exports = WebAssemblyModulesPlugin; */ -const t = __webpack_require__(81875); -const { decode } = __webpack_require__(27352); -const { - moduleContextFromModuleAST -} = __webpack_require__(71234); - -const { Tapable } = __webpack_require__(56758); -const WebAssemblyImportDependency = __webpack_require__(52959); -const WebAssemblyExportImportedDependency = __webpack_require__(18925); - -/** @typedef {import("../Module")} Module */ +const RequireContextDependency = __webpack_require__(79142); +const ContextElementDependency = __webpack_require__(89079); -const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); +const RequireContextDependencyParserPlugin = __webpack_require__(10566); -/** - * @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`; +class RequireContextPlugin { + constructor(modulesDirectories, extensions, mainFiles) { + if (!Array.isArray(modulesDirectories)) { + throw new Error("modulesDirectories must be an array"); } - } - 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`; + if (!Array.isArray(extensions)) { + throw new Error("extensions must be an array"); } + this.modulesDirectories = modulesDirectories; + this.extensions = extensions; + this.mainFiles = mainFiles; } - 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; - } + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); - parse(binary, state) { - // flag it as ESM - state.module.buildMeta.exportsType = "namespace"; + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); - // parse it - const program = decode(binary, decoderOpts); - const module = program.body[0]; + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) + return; - const moduleContext = moduleContextFromModuleAST(module); + new RequireContextDependencyParserPlugin().apply(parser); + }; - // 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 - ); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); - if (incompatibleType) { - jsIncompatibleExports[node.name] = incompatibleType; + 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), []); } - } - - 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); + 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), []); } - } - }, - - 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]; + 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; + }); } - } - - importedGlobals.push(importNode); - }, + ); + } + ); + } +} +module.exports = RequireContextPlugin; - 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 - ); +/***/ 49105: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - state.module.addDependency(dep); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); +const AsyncDependenciesBlock = __webpack_require__(22814); +const RequireEnsureDependency = __webpack_require__(75830); - return state; +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); } -} - -module.exports = WebAssemblyParser; +}; /***/ }), -/***/ 52136: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 24620: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -109954,64 +102764,121 @@ module.exports = WebAssemblyParser; */ -const Template = __webpack_require__(96066); -const WebAssemblyImportDependency = __webpack_require__(52959); - -/** @typedef {import("../Module")} Module */ +const RequireEnsureDependenciesBlock = __webpack_require__(49105); +const RequireEnsureItemDependency = __webpack_require__(5511); +const getFunctionExpression = __webpack_require__(64197); -/** @typedef {Object} UsedWasmDependency - * @property {WebAssemblyImportDependency} dependency the dependency - * @property {string} name the export name - * @property {string} module the module name - */ +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); -const MANGLED_MODULE = "a"; + 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 + ); -/** - * @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; - } + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } - 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 - }); - } - } + 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; + } + } + }); } - return array; }; -exports.getUsedDependencies = getUsedDependencies; -exports.MANGLED_MODULE = MANGLED_MODULE; - /***/ }), -/***/ 52669: +/***/ 75830: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110020,43 +102887,64 @@ exports.MANGLED_MODULE = MANGLED_MODULE; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const WasmMainTemplatePlugin = __webpack_require__(65331); - -class FetchCompileWasmTemplatePlugin { - constructor(options) { - this.options = options || {}; +class RequireEnsureDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; } - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileWasmTemplatePlugin", - compilation => { - const mainTemplate = compilation.mainTemplate; - const generateLoadBinaryCode = path => - `fetch(${mainTemplate.requireFn}.p + ${path})`; + get type() { + return "require.ensure"; + } +} - const plugin = new WasmMainTemplatePlugin( - Object.assign( - { - generateLoadBinaryCode, - supportsStreaming: true - }, - this.options - ) - ); - plugin.apply(mainTemplate); - } +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 = FetchCompileWasmTemplatePlugin; +module.exports = RequireEnsureDependency; /***/ }), -/***/ 31898: +/***/ 5511: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110065,77 +102953,27 @@ module.exports = FetchCompileWasmTemplatePlugin; Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); +const NullDependency = __webpack_require__(5088); -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`); - } +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } - 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) || ""); - } - ); + get type() { + return "require.ensure item"; } } -module.exports = JsonpChunkTemplatePlugin; + +RequireEnsureItemDependency.Template = NullDependency.Template; + +module.exports = RequireEnsureItemDependency; /***/ }), -/***/ 13732: +/***/ 98655: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110145,55 +102983,113 @@ module.exports = JsonpChunkTemplatePlugin; */ -const { ConcatSource } = __webpack_require__(53665); +const RequireEnsureItemDependency = __webpack_require__(5511); +const RequireEnsureDependency = __webpack_require__(75830); -class JsonpExportMainTemplatePlugin { - /** - * @param {string} name jsonp function name - */ - constructor(name) { - this.name = name; - } +const NullFactory = __webpack_require__(40438); - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; +const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(24620); - const onRenderWithEntry = (source, chunk, hash) => { - const name = mainTemplate.getAssetPath(this.name || "", { - hash, - chunk - }); - return new ConcatSource(`${name}(`, source, ");"); - }; +const ParserHelpers = __webpack_require__(23999); - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "JsonpExportMainTemplatePlugin", - onRenderWithEntry - ); - } +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); - mainTemplate.hooks.globalHashPaths.tap( - "JsonpExportMainTemplatePlugin", - paths => { - if (this.name) paths.push(this.name); - return paths; + 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; - mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => { - hash.update("jsonp export"); - hash.update(`${this.name}`); - }); + +/***/ }), + +/***/ 22928: +/***/ (function(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; } } -module.exports = JsonpExportMainTemplatePlugin; +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; /***/ }), -/***/ 44458: +/***/ 58045: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110203,122 +103099,205 @@ module.exports = JsonpExportMainTemplatePlugin; */ -const { ConcatSource } = __webpack_require__(53665); +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const Template = __webpack_require__(96066); -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)},` +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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireIncludeDependency = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const RequireIncludeDependency = __webpack_require__(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 ); - source.add(modulesSource); - source.add(")"); - return source; - } - ); - hotUpdateChunkTemplate.hooks.hash.tap( - "JsonpHotUpdateChunkTemplatePlugin", - hash => { - hash.update("JsonpHotUpdateChunkTemplatePlugin"); - hash.update("3"); - hash.update( - `${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}` + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() ); - hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`); + + 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; -module.exports = JsonpHotUpdateChunkTemplatePlugin; + +/***/ }), + +/***/ 83309: +/***/ (function(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; /***/ }), -/***/ 24916: -/***/ (function(module) { +/***/ 43519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; /* 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 +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyAsId = __webpack_require__(63708); - // 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); +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; } - // 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); - } - }; - }); + get type() { + return "require.resolve"; } -}; +} + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; /***/ }), -/***/ 38017: +/***/ 68349: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110328,620 +103307,319 @@ module.exports = function() { */ -const { SyncWaterfallHook } = __webpack_require__(56758); -const Template = __webpack_require__(96066); +const RequireResolveDependency = __webpack_require__(43519); +const RequireResolveContextDependency = __webpack_require__(83309); +const RequireResolveHeaderDependency = __webpack_require__(69647); +const ContextDependencyHelpers = __webpack_require__(5594); -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; +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; } - return false; }; - const needEntryDeferringCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.chunks.length > 1) 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; } - return false; }; - const needPrefetchingCode = chunk => { - const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; - return allPrefetchChunks && Object.keys(allPrefetchChunks).length; + 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; }; - // 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" - ]); - } - }); + 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; - 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}] + "`; + +/***/ }), + +/***/ 69647: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ModuleDependency = __webpack_require__(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: +/***/ (function(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 + ) + ); } - } - }, - 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 parser.hooks.importCall.call(expr); + }); + }; - 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;" - ]); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("SystemPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("SystemPlugin", handler); } ); - 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)};` - ), - "}" - ]) - : "" - ]); - } +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/" ); - 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; + this.name = "SystemImportDeprecationWarning"; - return Template.asString([ - source, - "", - "// on error function for async loading", - `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };` - ]); - } + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = SystemPlugin; + + +/***/ }), + +/***/ 15826: +/***/ (function(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) ); - 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; +}; + +module.exports = UnsupportedDependency; /***/ }), -/***/ 92764: +/***/ 18925: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110951,29 +103629,37 @@ module.exports = JsonpMainTemplatePlugin; */ -const JsonpMainTemplatePlugin = __webpack_require__(38017); -const JsonpChunkTemplatePlugin = __webpack_require__(31898); -const JsonpHotUpdateChunkTemplatePlugin = __webpack_require__(44458); +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); -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 - ); - }); +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 = JsonpTemplatePlugin; +module.exports = WebAssemblyExportImportedDependency; /***/ }), -/***/ 92929: -/***/ (function(module, exports, __webpack_require__) { +/***/ 52959: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -110982,212 +103668,60 @@ module.exports = JsonpTemplatePlugin; */ -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; +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ -/** - * @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); +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; } - 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"); + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, [this.name], false); } - if (callback) { - if (typeof callback !== "function") { - throw new Error("Invalid argument: callback"); - } + + getErrors() { if ( - options.watch === true || - (Array.isArray(options) && options.some(o => o.watch)) + this.onlyDirectImport && + this.module && + !this.module.type.startsWith("webassembly") ) { - const watchOptions = Array.isArray(options) - ? options.map(o => o.watchOptions || {}) - : options.watchOptions || {}; - return compiler.watch(watchOptions, callback); + return [ + new UnsupportedWebAssemblyFeatureError( + `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` + ) + ]; } - 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] - }); + get type() { + return "wasm import"; } -}; - -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." -); +module.exports = WebAssemblyImportDependency; /***/ }), -/***/ 37919: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 75386: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -111195,5906 +103729,13496 @@ defineMissingPluginError( Author Tobias Koppers @sokra */ +const toErrorCode = err => + `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; -const { ConcatSource } = __webpack_require__(53665); +exports.module = request => + `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; -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; +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;`; +}; /***/ }), -/***/ 45493: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 64197: +/***/ (function(module) { -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +module.exports = expr => { + // + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; + } -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 + ""); - } - ); + // .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 + }; } -} -module.exports = WebWorkerHotUpdateChunkTemplatePlugin; + // (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 + }; + } +}; /***/ }), -/***/ 72337: +/***/ 49: /***/ (function(module) { +"use strict"; /* 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); - } - }; - }); +/** @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 ""; +}; - //eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; +// 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; + /***/ }), -/***/ 20482: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 47194: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + 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)} + "` - } - ); +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 - 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; + 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] -/***/ 21328: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + clear: /** @type {"clear"} */ ("clear"), // no arguments + status: /** @type {"status"} */ ("status") // message, arguments +}); +exports.LogType = LogType; -const WebWorkerMainTemplatePlugin = __webpack_require__(20482); -const WebWorkerChunkTemplatePlugin = __webpack_require__(37919); -const WebWorkerHotUpdateChunkTemplatePlugin = __webpack_require__(45493); +/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ -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 - ); - } - ); +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; } -} -module.exports = WebWorkerTemplatePlugin; + error(...args) { + this[LOG_SYMBOL](LogType.error, args); + } -/***/ }), + warn(...args) { + this[LOG_SYMBOL](LogType.warn, args); + } -/***/ 19728: -/***/ (function(__unused_webpack_module, exports) { + info(...args) { + this[LOG_SYMBOL](LogType.info, args); + } -"use strict"; + log(...args) { + this[LOG_SYMBOL](LogType.log, args); + } + debug(...args) { + this[LOG_SYMBOL](LogType.debug, args); + } -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; -} + assert(assertion, ...args) { + if (!assertion) { + this[LOG_SYMBOL](LogType.error, args); + } + } -/***/ }), + trace() { + this[LOG_SYMBOL](LogType.trace, ["Trace"]); + } -/***/ 81875: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + clear() { + this[LOG_SYMBOL](LogType.clear); + } -"use strict"; + status(...args) { + this[LOG_SYMBOL](LogType.status, args); + } + group(...args) { + this[LOG_SYMBOL](LogType.group, args); + } -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; - } -})); + groupCollapsed(...args) { + this[LOG_SYMBOL](LogType.groupCollapsed, args); + } -var _nodes = __webpack_require__(94841); + groupEnd(...args) { + this[LOG_SYMBOL](LogType.groupEnd, args); + } -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]; - } - }); -}); + profile(label) { + this[LOG_SYMBOL](LogType.profile, [label]); + } -var _nodeHelpers = __webpack_require__(1004); + profileEnd(label) { + this[LOG_SYMBOL](LogType.profileEnd, [label]); + } -var _traverse = __webpack_require__(29436); + time(label) { + this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); + this[TIMERS_SYMBOL].set(label, process.hrtime()); + } -var _signatures = __webpack_require__(77392); + 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]); + } -var _utils = __webpack_require__(38456); + 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]); + } +} -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]; - } - }); -}); +exports.Logger = WebpackLogger; -var _clone = __webpack_require__(19728); /***/ }), -/***/ 1004: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 88838: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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__(94841); - -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 +const { LogType } = __webpack_require__(47194); - default: - { - return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); - } - } - } -} +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ -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); -} +/** @typedef {function(string): boolean} FilterFunction */ -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 + * @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; + } +}; -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; -} +/** + * @enum {number} + */ +const LogLevel = { + none: 6, + false: 6, + error: 5, + warn: 4, + info: 3, + log: 2, + true: 2, + verbose: 1 +}; -function funcParam(valtype, id) { - return { - id: id, - valtype: valtype - }; -} +/** + * @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; -function indexLiteral(value) { - // $FlowIgnore - var x = numberLiteralFromRaw(value, "u32"); - return x; -} + /** + * @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; +}; -function memIndexLiteral(value) { - // $FlowIgnore - var x = numberLiteralFromRaw(value, "u32"); - return x; -} /***/ }), -/***/ 89231: -/***/ (function(__unused_webpack_module, exports) { +/***/ 62299: +/***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ -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); } +/** + * @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; -function findParent(_ref, cb) { - var parentPath = _ref.parentPath; + 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)]; + } + } - 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; -} + // 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 []; + } -function insertBefore(context, newNode) { - return insert(context, newNode); -} + let currentLength = lengths.reduce((a, b) => a + b, 0); -function insertAfter(context, newNode) { - return insert(context, newNode, 1); -} + // Check if all fits into maxLength + if (currentLength <= availableLength) return args; -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; + // Try to remove chars from the longest items until it fits + while (currentLength > availableLength) { + const maxLength = Math.max(...lengths); + const shorterItems = lengths.filter(l => l !== maxLength); + const nextToMaxLength = + shorterItems.length > 0 ? Math.max(...shorterItems) : 0; + const maxReduce = maxLength - nextToMaxLength; + let maxItems = lengths.length - shorterItems.length; + let overrun = currentLength - availableLength; + for (let i = 0; i < lengths.length; i++) { + if (lengths[i] === maxLength) { + const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); + lengths[i] -= reduce; + currentLength -= reduce; + overrun -= reduce; + maxItems--; + } + } + } - if (!inList) { - throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); - } + // 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 ""; + } + }); +}; - if (!(parentPath != null)) { - throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); - } +module.exports = truncateArgs; - // $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)); - } +/***/ 45249: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // $FlowIgnore - var parentNode = parentPath.node; // $FlowIgnore +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; -} +const { ConcatSource } = __webpack_require__(53665); -function stop(context) { - context.shouldStop = true; +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"); + }); + } } -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; - } +module.exports = NodeChunkTemplatePlugin; - 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; -} +/***/ 52520: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function createPathOperations(context) { - // $FlowIgnore - return bindNodeOperations({ - findParent: findParent, - replaceWith: replaceWith, - remove: remove, - insertBefore: insertBefore, - insertAfter: insertAfter, - stop: stop - }, context); -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function createPath(context) { - var path = _extends({}, context); // $FlowIgnore +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); - Object.assign(path, createPathOperations(path)); // $FlowIgnore +class NodeEnvironmentPlugin { + constructor(options) { + this.options = options || {}; + } - return path; + 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; + /***/ }), -/***/ 94841: -/***/ (function(__unused_webpack_module, exports) { +/***/ 95909: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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; - }; -} +const { ConcatSource } = __webpack_require__(53665); -function assertTypeOf(t) { - return function (n) { - return function () { - if (!(n.type === t)) { - throw new Error('n.type === t' + " error: " + (undefined || "unknown")); - } - }(); - }; +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; -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 - }; +/***/ 33514: +/***/ (function(module) { - if (typeof metadata !== "undefined") { - node.metadata = metadata; - } +/* + 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; - return node; -} +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var chunk = require("./" + $hotChunkFilename$); + hotAddUpdateChunk(chunk.id, chunk.modules); + } -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")); - } + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + try { + var update = require("./" + $hotMainFilename$); + } catch (e) { + return Promise.resolve(); + } + return Promise.resolve(update); + } - 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")); - } - } + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; - 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 - }; +/***/ 51433: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (typeof functionNames !== "undefined" && functionNames.length > 0) { - node.functionNames = functionNames; - } +/* + 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; - if (typeof localNames !== "undefined" && localNames.length > 0) { - node.localNames = localNames; - } +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); + }); + } - if (typeof producers !== "undefined" && producers.length > 0) { - node.producers = producers; - } + // 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); + }); + }); + } - return node; -} + // eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; -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)); - } +/***/ 78597: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!(typeof index === "number")) { - throw new Error('typeof index === "number"' + " error: " + ("Argument index must be of type number, given: " + _typeof(index) || 0)); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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)); - } +const Template = __webpack_require__(96066); - if (!(typeof localIndex === "number")) { - throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); - } +module.exports = class NodeMainTemplatePlugin { + constructor(asyncChunkLoading) { + this.asyncChunkLoading = asyncChunkLoading; + } - 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; -} + 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"); + }); + } +}; -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; -} +/***/ 31836: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -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)); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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")); - } +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const mkdirp = __webpack_require__(50998); - var node = { - type: "ProducersSectionMetadata", - producers: producers - }; - return node; +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); + } } -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")); - } +module.exports = NodeOutputFileSystem; - 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)); - } +/***/ 9128: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!(typeof version === "string")) { - throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - var node = { - type: "ProducerMetadataVersionedName", - name: name, - version: version - }; - return node; -} +const AliasPlugin = __webpack_require__(15005); +const ParserHelpers = __webpack_require__(23999); +const nodeLibsBrowser = __webpack_require__(27852); -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")); - } +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; + } - var node = { - type: "LoopInstruction", - id: "loop", - label: label, - resulttype: resulttype, - instr: instr - }; - return node; -} + 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; + } + }; -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)); - } + 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 + ); + }); + }; - if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { - throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + compiler.hooks.compilation.tap( + "NodeSourcePlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; - var node = { - type: "Instr", - id: id, - args: args - }; + 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); + }); + } + } + }); + } +}; - if (typeof object !== "undefined") { - node.object = object; - } - if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { - node.namedArgs = namedArgs; - } +/***/ }), - return node; -} +/***/ 59743: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -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")); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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")); - } +const ExternalsPlugin = __webpack_require__(75705); - var node = { - type: "IfInstruction", - id: "if", - testLabel: testLabel, - test: test, - result: result, - consequent: consequent, - alternate: alternate - }; - return node; +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); + } } -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)); - } +module.exports = NodeTargetPlugin; - 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)); - } +/***/ 90010: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var node = { - type: "NumberLiteral", - value: value, - raw: raw - }; - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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)); - } +const NodeMainTemplatePlugin = __webpack_require__(78597); +const NodeChunkTemplatePlugin = __webpack_require__(45249); +const NodeHotUpdateChunkTemplatePlugin = __webpack_require__(95909); - 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)); - } - } +class NodeTemplatePlugin { + constructor(options) { + options = options || {}; + this.asyncChunkLoading = options.asyncChunkLoading; + } - 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)); - } - } + 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 + ); + }); + } +} - if (!(typeof raw === "string")) { - throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); - } +module.exports = NodeTemplatePlugin; - var node = { - type: "FloatLiteral", - value: value, - raw: raw - }; - if (nan === true) { - node.nan = true; - } +/***/ }), - if (inf === true) { - node.inf = true; - } +/***/ 71610: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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")); - } +const Watchpack = __webpack_require__(77056); +const objectToMap = __webpack_require__(1111); - var node = { - type: "Elem", - table: table, - offset: offset, - funcs: funcs - }; - return node; -} +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); + } -function indexInFuncSection(index) { - var node = { - type: "IndexInFuncSection", - index: index - }; - return node; -} + 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); -function valtypeLiteral(name) { - var node = { - type: "ValtypeLiteral", - name: name - }; - return node; -} + 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 + ); + }); -function typeInstruction(id, functype) { - var node = { - type: "TypeInstruction", - id: id, - functype: functype - }; - return node; -} + this.watcher.watch( + cachedFiles.concat(missing), + cachedDirs.concat(missing), + startTime + ); -function start(index) { - var node = { - type: "Start", - index: index - }; - return node; + 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(); + } + } + }; + } } -function globalType(valtype, mutability) { - var node = { - type: "GlobalType", - valtype: valtype, - mutability: mutability - }; - return node; -} +module.exports = NodeWatchFileSystem; -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)); - } +/***/ 73839: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var node = { - type: "BlockComment", - value: value - }; - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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")); - } +const Template = __webpack_require__(96066); +const WasmMainTemplatePlugin = __webpack_require__(65331); - var node = { - type: "Global", - globalType: globalType, - init: init, - name: name - }; - return node; +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); + } + ); + } } -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)); - } +module.exports = ReadFileCompileWasmTemplatePlugin; - 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; - } +/***/ 7886: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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)); - } +const truncateArgs = __webpack_require__(62299); +const util = __webpack_require__(31669); - if (!(typeof name === "string")) { - throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); - } +const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; - var node = { - type: "ModuleImport", - module: module, - name: name, - descr: descr - }; - return node; -} +let currentStatusMessage = undefined; +let hasStatusMessage = false; +let currentIndent = ""; +let currentCollapsed = 0; -function moduleExportDescr(exportType, id) { - var node = { - type: "ModuleExportDescr", - exportType: exportType, - id: id - }; - return node; -} +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); + } +}; -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)); - } +const clearStatusMessage = () => { + if (hasStatusMessage) { + process.stderr.write("\x1b[2K\r"); + hasStatusMessage = false; + } +}; - var node = { - type: "ModuleExport", - name: name, - descr: descr - }; - return node; -} +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; +}; -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)); - } +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(); + }; +}; - 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)); - } - } +const writeGroupMessage = writeColored( + "<-> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" +); - var node = { - type: "Limit", - min: min - }; +const writeGroupCollapsedMessage = writeColored( + "<+> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" +); - if (typeof max !== "undefined") { - node.max = max; - } +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(" ", "", "") +}; - 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")); - } +/***/ 88197: +/***/ (function(module) { - var node = { - type: "Signature", - params: params, - results: results - }; - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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; -} +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 || {}; + } -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)); - } + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; - 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)); - } - } + 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 + }); + } + }); - var node = { - type: "Identifier", - value: value - }; + 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; + } - if (typeof raw !== "undefined") { - node.raw = raw; - } + pair.improvement = (a + b) / newSize; + } + combinations = combinations.filter(pair => { + return pair.improvement !== false; + }); + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); - return node; -} + const pair = combinations[0]; -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")); - } + if (!pair) return; + if (pair.improvement < minSizeReduce) return; - var node = { - type: "BlockInstruction", - id: "block", - label: label, - instr: instr, - result: result - }; - return node; + if (pair.b.integrate(pair.a, "aggressive-merge")) { + chunks.splice(chunks.indexOf(pair.a), 1); + return true; + } + } + ); + } + ); + } } -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")); - } - } +module.exports = AggressiveMergingPlugin; - 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; - } +/***/ 26688: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return node; -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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 - }; +const identifierUtils = __webpack_require__(94658); +const { intersect } = __webpack_require__(54262); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(71884); - if (typeof intrs !== "undefined" && intrs.length > 0) { - node.intrs = intrs; - } +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ - return node; -} +const moveModuleBetween = (oldChunk, newChunk) => { + return module => { + oldChunk.moveModule(module, newChunk); + }; +}; -function byteArray(values) { - if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { - throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); - } +const isNotAEntryModule = entryModule => { + return module => { + return entryModule !== module; + }; +}; - var node = { - type: "ByteArray", - values: values - }; - return node; -} +class AggressiveSplittingPlugin { + /** + * @param {AggressiveSplittingPluginOptions=} options options object + */ + constructor(options) { + if (!options) options = {}; -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")); - } + validateOptions(schema, options, "Aggressive Splitting Plugin"); - 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)); - } - } + 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); + } - var node = { - type: "Func", - name: name, - signature: signature, - body: body - }; + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } - if (isExternal === true) { - node.isExternal = true; - } + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; - if (typeof metadata !== "undefined") { - node.metadata = metadata; - } + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; - return node; -} + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } -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)); - } + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) + ); - var node = { - type: "InternalBrUnless", - target: target - }; - return node; -} + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; -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)); - } + // 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; - var node = { - type: "InternalGoto", - target: target - }; - return node; -} + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map(m => new Set(m.chunksIterable)) + ); -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)); - } + // No relevant chunks found + if (selectedChunks.size === 0) return false; - var node = { - type: "InternalCallExtern", - target: target - }; - return node; -} + // 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; + } -function internalEndAndReturn() { - var node = { - type: "InternalEndAndReturn" - }; - return node; -} + // 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); -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; + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + } + return true; + }; -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); -}; + // 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; + } -exports.isNode = isNode; + // 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 + }; -var isBlock = function isBlock(node) { - return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); -}; + 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(); -exports.isBlock = isBlock; + // 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); + } + } + } -var isInstruction = function isInstruction(node) { - return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); -}; + 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; + } + } -exports.isInstruction = isInstruction; + // 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); + } + } -var isExpression = function isExpression(node) { - return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); -}; + // record all splits + records.aggressiveSplits = Array.from(allSplits); -exports.isExpression = isExpression; + needAdditionalSeal = false; + } + } + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); + } + ); + } +} +module.exports = AggressiveSplittingPlugin; -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); -}; +/***/ 30346: +/***/ (function(module) { -exports.isImportDescr = isImportDescr; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -var isIntrinsic = function isIntrinsic(node) { - return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); + +const sortByIndex = (a, b) => { + return a.index - b.index; }; -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"] +const sortByIndex2 = (a, b) => { + return a.index2 - b.index2; }; -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; -/***/ }), +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; + } -/***/ 77392: -/***/ (function(__unused_webpack_module, exports) { + 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` + ); + } -"use strict"; + 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; -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; /***/ }), -/***/ 29436: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 16953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.traverse = traverse; - -var _nodePath = __webpack_require__(89231); - -var _nodes = __webpack_require__(94841); +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); -// 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; +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../util/createHash").Hash} Hash */ +/** @typedef {import("../RequestShortener")} RequestShortener */ - function innerWalk(context, callback) { - if (stop) { - return; - } +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; +}; - var node = context.node; +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + */ - if (node === undefined) { - console.warn("traversing with an empty context"); - return; - } +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"; + } +}; - if (node._deleted === true) { - return; - } +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; +}; - var path = (0, _nodePath.createPath)(context); - callback(node.type, path); +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 + ); + } + } +}; - if (path.shouldStop) { - stop = true; - return; - } +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; + } +}; - Object.keys(node).forEach(function (prop) { - var value = node[prop]; +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; + } +}; - if (value === null || value === undefined) { - return; - } +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; +}; - 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); - } - }); - }); - } +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } - innerWalk(context, callback); -} + const nr = node.range; -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); - } - }); - }); -} - -/***/ }), - -/***/ 38456: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; + 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; + } + } + } +}; -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; +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 + }; + }); +}; -var _signatures = __webpack_require__(77392); +class ConcatenatedModule extends Module { + constructor(rootModule, modules, concatenationList) { + super("javascript/esm", null); + super.setChunks(rootModule._chunks); -var _traverse = __webpack_require__(29436); + // Info from Factory + this.rootModule = rootModule; + this.factoryMeta = rootModule.factoryMeta; -var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(66921)); + // Info from Compilation + this.index = rootModule.index; + this.index2 = rootModule.index2; + this.depth = rootModule.depth; -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; } } + // Info from Optimization + this.used = rootModule.used; + this.usedExports = rootModule.usedExports; -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; } + // 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; -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"); } } + // Caching + this._numberOfConcatenatedModules = modules.length; -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); } + // Graph + const modulesSet = new Set(modules); + this.reasons = rootModule.reasons.filter( + reason => + !(reason.dependency instanceof HarmonyImportDependency) || + !modulesSet.has(reason.module) + ); -function isAnonymous(ident) { - return ident.raw === ""; -} + this.dependencies = []; + this.blocks = []; -function getSectionMetadata(ast, name) { - var section; - (0, _traverse.traverse)(ast, { - SectionMetadata: function (_SectionMetadata) { - function SectionMetadata(_x) { - return _SectionMetadata.apply(this, arguments); - } + 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; - SectionMetadata.toString = function () { - return _SectionMetadata.toString(); - }; + // 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); + } - return SectionMetadata; - }(function (_ref) { - var node = _ref.node; + 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(); + } - if (node.section === name) { - section = node; - } - }) - }); - return section; -} + get modules() { + return this._orderedConcatenationList + .filter(info => info.type === "concatenated") + .map(info => info.module); + } -function getSectionMetadatas(ast, name) { - var sections = []; - (0, _traverse.traverse)(ast, { - SectionMetadata: function (_SectionMetadata2) { - function SectionMetadata(_x2) { - return _SectionMetadata2.apply(this, arguments); - } + identifier() { + return this._identifier; + } - SectionMetadata.toString = function () { - return _SectionMetadata2.toString(); - }; + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._numberOfConcatenatedModules - 1} modules` + ); + } - return SectionMetadata; - }(function (_ref2) { - var node = _ref2.node; + libIdent(options) { + return this.rootModule.libIdent(options); + } - if (node.section === name) { - sections.push(node); - } - }) - }); - return sections; -} + nameForCondition() { + return this.rootModule.nameForCondition(); + } -function sortSectionMetadata(m) { - if (m.metadata == null) { - console.warn("sortSectionMetadata: no metadata to sort"); - return; - } // $FlowIgnore + 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); + } - m.metadata.sections.sort(function (a, b) { - var aId = _helperWasmBytecode.default.sections[a.section]; - var bId = _helperWasmBytecode.default.sections[b.section]; + /** + * @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(); - if (typeof aId !== "number" || typeof bId !== "number") { - throw new Error("Section id not found"); - } + /** + * @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; + }); + }; - return aId - bId; - }); -} + 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(); + } + }); + } + }; -function orderedInsertNode(m, n) { - assertHasLoc(n); - var didInsert = false; + enterModule(() => rootModule); - if (n.type === "ModuleExport") { - m.fields.push(n); - return; - } + return list; + } - m.fields = m.fields.reduce(function (acc, field) { - var fieldEndCol = Infinity; + _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"); + } - if (field.loc != null) { - // $FlowIgnore - fieldEndCol = field.loc.end.column; - } // $FlowIgnore: assertHasLoc ensures that + 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); + } - if (didInsert === false && n.loc.start.column < fieldEndCol) { - didInsert = true; - acc.push(n); - } + // Configure template decorators for dependencies + const innerDependencyTemplates = new Map(dependencyTemplates); - 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; + 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() + ); - if (_typeof(node.size.loc) === "object") { - shiftLoc(node.size, delta); - } // Custom sections doesn't have vectorOfSize + // 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; + } + } - if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { - shiftLoc(node.vectorOfSize, delta); - } + // List of all used names to avoid conflicts + const allUsedNames = new Set([ + "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name - var sectionName = node.section; // shift node locations within that section + "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", - (0, _traverse.traverse)(ast, { - Node: function Node(_ref3) { - var node = _ref3.node; - var section = (0, _helperWasmBytecode.getSectionForNode)(node); + "module", + "__dirname", + "__filename", + "exports", - if (section === sectionName && _typeof(node.loc) === "object") { - shiftLoc(node, delta); - } - } - }); -} + "Array", + "Date", + "eval", + "function", + "hasOwnProperty", + "Infinity", + "isFinite", + "isNaN", + "isPrototypeOf", + "length", + "Math", + "NaN", + "name", + "Number", + "Object", + "prototype", + "String", + "toString", + "undefined", + "valueOf", -function signatureForOpcode(object, name) { - var opcodeName = name; + "alert", + "all", + "anchor", + "anchors", + "area", + "assign", + "blur", + "button", + "checkbox", + "clearInterval", + "clearTimeout", + "clientInformation", + "close", + "closed", + "confirm", + "constructor", + "crypto", + "decodeURI", + "decodeURIComponent", + "defaultStatus", + "document", + "element", + "elements", + "embed", + "embeds", + "encodeURI", + "encodeURIComponent", + "escape", + "event", + "fileUpload", + "focus", + "form", + "forms", + "frame", + "innerHeight", + "innerWidth", + "layer", + "layers", + "link", + "location", + "mimeTypes", + "navigate", + "navigator", + "frames", + "frameRate", + "hidden", + "history", + "image", + "images", + "offscreenBuffering", + "open", + "opener", + "option", + "outerHeight", + "outerWidth", + "packages", + "pageXOffset", + "pageYOffset", + "parent", + "parseFloat", + "parseInt", + "password", + "pkcs11", + "plugin", + "prompt", + "propertyIsEnum", + "radio", + "reset", + "screenX", + "screenY", + "scroll", + "secure", + "select", + "self", + "setInterval", + "setTimeout", + "status", + "submit", + "taint", + "text", + "textarea", + "top", + "unescape", + "untaint", + "window", - if (object !== undefined && object !== "") { - opcodeName = object + "." + name; - } + "onblur", + "onclick", + "onerror", + "onfocus", + "onkeydown", + "onkeypress", + "onkeyup", + "onmouseover", + "onload", + "onmouseup", + "onmousedown", + "onsubmit" + ]); - var sign = _signatures.signatures[opcodeName]; + // Set of already checked scopes + const alreadyCheckedScopes = new Set(); - if (sign == undefined) { - // TODO: Uncomment this when br_table and others has been done - //throw new Error("Invalid opcode: "+opcodeName); - return [object, object]; - } + // get all global names + for (const info of modulesWithInfo) { + const superClassExpressions = []; - return sign[0]; -} + // ignore symbols from moduleScope + if (info.moduleScope) { + alreadyCheckedScopes.add(info.moduleScope); -function getUniqueNameGenerator() { - var inc = {}; - return function () { - var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + // 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 + }); + } + } - if (!(prefix in inc)) { - inc[prefix] = 0; - } else { - inc[prefix] = inc[prefix] + 1; - } + // 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); + } + } + } - return prefix + "_" + inc[prefix]; - }; -} + // 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); + } + } + } + } -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)); - } + // 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; + } + } + } - 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")); - } + // 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); + } + } + } + } - var _n$body = _slicedToArray(n.body, 1), - firstInstruction = _n$body[0]; + // Map with all root exposed used exports + /** @type {Map} */ + const exportsMap = new Map(); - return getStartByteOffset(firstInstruction); -} + // Set with all root exposed unused exports + /** @type {Set} */ + const unusedExports = new Set(); -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")); - } + 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); + } + } + } + } - var lastInstruction; + const result = new ConcatSource(); - if (n.instr) { - // $FlowIgnore - lastInstruction = n.instr[n.instr.length - 1]; - } + // 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 + }) + ); + } - if (n.body) { - // $FlowIgnore - lastInstruction = n.body[n.body.length - 1]; - } + // 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` + ); + } + } - if (!(_typeof(lastInstruction) === "object")) { - throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown")); - } + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } - // $FlowIgnore - return getStartByteOffset(lastInstruction); -} + // 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); + } + } -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")); - } + // 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}`); + } + } - var fistInstruction; + return result; + } - if (n.instr) { - // $FlowIgnore - var _n$instr = _slicedToArray(n.instr, 1); + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; - fistInstruction = _n$instr[0]; - } + if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; - if (n.body) { - // $FlowIgnore - var _n$body2 = _slicedToArray(n.body, 1); + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); - fistInstruction = _n$body2[0]; - } + 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; + } - if (!(_typeof(fistInstruction) === "object")) { - throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); - } + 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; + } - // $FlowIgnore - return getStartByteOffset(fistInstruction); + /** + * @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); + } } -/***/ }), - -/***/ 20193: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; +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; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; + 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; + } + } -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); } + 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); + } +} -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +class HarmonyImportSideEffectDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } -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; } + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } -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; } + 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; + } + } -var RuntimeError = -/*#__PURE__*/ -function (_Error) { - _inherits(RuntimeError, _Error); + 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; + } + } +} - function RuntimeError() { - _classCallCheck(this, RuntimeError); +class HarmonyExportExpressionDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + } - return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); - } + 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)}] = `; + } - return RuntimeError; -}(Error); + 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; + } -exports.RuntimeError = RuntimeError; + source.replace( + dep.rangeStatement[0], + dep.rangeStatement[1] - 1, + content + dep.prefix + ); + } +} -var CompileError = -/*#__PURE__*/ -function (_Error2) { - _inherits(CompileError, _Error2); +class NullTemplate { + apply() {} +} - function CompileError() { - _classCallCheck(this, CompileError); +module.exports = ConcatenatedModule; - return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); - } - return CompileError; -}(Error); +/***/ }), -exports.CompileError = CompileError; +/***/ 29720: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var LinkError = -/*#__PURE__*/ -function (_Error3) { - _inherits(LinkError, _Error3); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - function LinkError() { - _classCallCheck(this, LinkError); - return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); - } +const GraphHelpers = __webpack_require__(32973); - return LinkError; -}(Error); +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; -exports.LinkError = LinkError; /***/ }), -/***/ 66921: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 25850: +/***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getSectionForNode", ({ - enumerable: true, - get: function get() { - return _section.getSectionForNode; - } -})); -exports.default = void 0; +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; -var _section = __webpack_require__(79348); + // 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 + ); -var illegalop = "illegal"; -var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; -var moduleVersion = [0x01, 0x00, 0x00, 0x00]; + // 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++; + } -function invertMap(obj) { - var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { - return k; - }; - var result = {}; - var keys = Object.keys(obj); + // 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 (var i = 0, length = keys.length; i < length; i++) { - result[keyModifierFn(obj[keys[i]])] = keys[i]; - } + 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; - return result; -} + const chunkBModulesCount = chunkB.getNumberOfModules(); -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 - }; -} + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; -function createSymbol(name -/*: string */ -) -/*: Symbol*/ -{ - var numberOfArgs - /*: number*/ - = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - return { - name: name, - numberOfArgs: numberOfArgs - }; -} + // 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; -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); - } + // 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; - 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; /***/ }), -/***/ 79348: -/***/ (function(__unused_webpack_module, exports) { +/***/ 3846: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getSectionForNode = getSectionForNode; - -function getSectionForNode(n) { - switch (n.type) { - case "ModuleImport": - return "import"; +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(27993); +const LazyBucketSortedSet = __webpack_require__(52315); - case "CallInstruction": - case "CallIndirectInstruction": - case "Func": - case "Instr": - return "code"; +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ - case "ModuleExport": - return "export"; +/** + * @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 + */ - case "Start": - return "start"; +const addToSetMap = (map, key, value) => { + const set = map.get(key); + if (set === undefined) { + map.set(key, new Set([value])); + } else { + set.add(value); + } +}; - case "TypeInstruction": - return "type"; +class LimitChunkCountPlugin { + /** + * @param {LimitChunkCountPluginOptions=} options options object + */ + constructor(options) { + if (!options) options = {}; - case "IndexInFuncSection": - return "func"; + validateOptions(schema, options, "Limit Chunk Count Plugin"); + this.options = options; + } - case "Global": - return "global"; - // No section + /** + * @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; - default: - return; - } -} + let remainingChunksToMerge = chunks.length - maxChunks; -/***/ }), + // order chunks in a deterministic way + const orderedChunks = chunks.slice().sort((a, b) => a.compareTo(b)); -/***/ 57732: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // 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 + ); -"use strict"; + // 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); -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; + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + if (integratedSize === false) continue; -var _ieee = __webpack_require__(30848); + 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; + }); -/** - * 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 - */ + // list of modified chunks during this run + // combinations affected by this change are skipped to allow + // futher optimizations + /** @type {Set} */ + const modifiedChunks = new Set(); -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; + let changed = false; + // eslint-disable-next-line no-constant-condition + loop: while (true) { + const combination = combinations.popFirst(); + if (combination === undefined) break; -function encodeF32(v) { - var buffer = []; - (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); - return buffer; -} + combination.deleted = true; + const { a, b, integratedSize } = combination; -function encodeF64(v) { - var buffer = []; - (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); - return buffer; -} + // 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); + } + } + } -function decodeF32(bytes) { - var buffer = Buffer.from(bytes); - return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); -} + // merge the chunks + if (a.integrate(b, "limit")) { + chunks.splice(chunks.indexOf(b), 1); -function decodeF64(bytes) { - var buffer = Buffer.from(bytes); - return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); -} + // flag chunk a as modified as further optimization are possible for all children here + modifiedChunks.add(a); -/***/ }), + changed = true; + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break; -/***/ 62904: -/***/ (function(__unused_webpack_module, exports) { + // 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); + } -"use strict"; -// Copyright 2012 The Obvious Corporation. + // 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; -/* - * 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 - */ +/***/ 46214: +/***/ (function(module) { -/** - * 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`. - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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."); - } +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(); - if (defaultBit === undefined) { - defaultBit = 0; - } else if (defaultBit !== 0 && defaultBit !== 1) { - throw new Error("Bad value for defaultBit."); - } + // 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; + } + } - 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. + // 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); + } + } + } - var lastBit = bitIndex + bitLength; - var startByte = Math.floor(bitIndex / 8); - var startBit = bitIndex % 8; - var endByte = Math.floor(lastBit / 8); - var endBit = lastBit % 8; + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + } + ); + } +} +module.exports = MergeDuplicateChunksPlugin; - 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; +/***/ 55607: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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. - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function inject(buffer, bitIndex, bitLength, value) { - if (bitLength < 0 || bitLength > 32) { - throw new Error("Bad value for bitLength."); - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(8670); - var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ - 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. +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 + }; - var atByte = Math.floor(bitIndex / 8); - var atBit = bitIndex % 8; + 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]; + }); - while (bitLength > 0) { - if (value & 1) { - buffer[atByte] |= 1 << atBit; - } else { - buffer[atByte] &= ~(1 << atBit); - } + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; - value >>= 1; - bitLength--; - atBit = (atBit + 1) % 8; + const pair = sortedSizeFilteredExtendedPairCombinations[0]; - if (atBit === 0) { - atByte++; - } - } + pair[2].integrate(pair[3], "min-size"); + chunks.splice(chunks.indexOf(pair[3]), 1); + return true; + } + ); + }); + } } -/** - * Gets the sign bit of the given buffer. - */ - +module.exports = MinChunkSizePlugin; -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 +/***/ 25472: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - while (length > 0 && buffer[length - 1] === fullyWrongByte) { - length--; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (length === 0) { - // Degenerate case. The buffer consists entirely of ~bit. - return -1; - } - var byteToCheck = buffer[length - 1]; - var result = length * 8 - 1; +const WebpackError = __webpack_require__(97391); +const SizeFormatHelpers = __webpack_require__(12496); - for (var i = 7; i > 0; i--) { - if ((byteToCheck >> i & 1) === bit) { - break; - } +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." + ); + } +} - result--; - } +module.exports = MinMaxSizeWarning; - return result; -} /***/ }), -/***/ 7276: -/***/ (function(__unused_webpack_module, exports) { +/***/ 45184: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "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. - */ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/* - * Module variables - */ -/** Pool of buffers, where `bufPool[x].length === x`. */ -var bufPool = []; -/** Maximum length of kept temporary buffers. */ +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); -var TEMP_BUF_MAXIMUM_LENGTH = 20; -/** Minimum exactly-representable 64-bit int. */ +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; +}; -var MIN_EXACT_INT64 = -0x8000000000000000; -/** Maximum exactly-representable 64-bit int. */ +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; + } -var MAX_EXACT_INT64 = 0x7ffffffffffffc00; -/** Maximum exactly-representable 64-bit uint. */ + 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()"; + }); + }; -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). - */ + 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); -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). - */ + const bailoutReasonMap = new Map(); -var BIT_64 = 0x10000000000000000; -/* - * Helper functions - */ + const setBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + module.optimizationBailout.push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; -/** - * Masks off all but the lowest bit set of the given number. - */ + const getBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; -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. - */ + 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; + } -function isLossyToAdd(accum, num) { - if (num === 0) { - return false; - } + // Exports must be known (and not dynamic) + if (!Array.isArray(module.buildMeta.providedExports)) { + setBailoutReason(module, "Module exports are unknown"); + continue; + } - var lowBit = lowestBit(num); - var added = accum + lowBit; + // 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; + } - if (added === accum) { - return true; - } + // 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; + } - if (added - lowBit !== accum) { - return true; - } + relevantModules.push(module); - return false; -} -/* - * Exported functions - */ + // Module must not be the entry points + if (module.isEntryModule()) { + setBailoutReason(module, "Module is an entry point"); + continue; + } -/** - * 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. - */ + // 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; + } -function alloc(length) { - var result = bufPool[length]; + 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; - if (result) { - bufPool[length] = undefined; - } else { - result = new Buffer(length); - } + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration(currentRoot); - result.fill(0); - return result; -} -/** - * Releases a buffer back to the pool. - */ + // 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) + ); + } + ); + } + ); + } -function free(buffer) { - var length = buffer.length; + _getImports(compilation, module) { + return new Set( + module.dependencies - 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). - */ + // 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)) + ) -function resize(buffer, length) { - if (length === buffer.length) { - return buffer; - } + // Take the imported module + .map(ref => ref.module) + ); + } - var newBuf = alloc(length); - buffer.copy(newBuf); - free(buffer); - return newBuf; -} -/** - * Reads an arbitrary signed int from a buffer. - */ + _tryToAdd(compilation, config, module, possibleModules, failureCache) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + return cacheEntry; + } + // Already added? + if (config.has(module)) { + return null; + } -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. + // Not possible to add? + if (!possibleModules.has(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } - 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; + // module must be in the same chunks + if (!config.rootModule.hasEqualsChunks(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } - if (isLossyToAdd(result, one)) { - lossy = true; - } + // Clone config to make experimental changes + const testConfig = config.clone(); - result += one; - } - } + // Add the module + testConfig.add(module); - return { - value: result, - lossy: lossy - }; -} -/** - * Reads an arbitrary unsigned int from a buffer. - */ + // 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; + } + } -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; - } + // Commit experimental changes + config.set(testConfig); - writeUInt64(value, buffer); + // 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; + } } -/** - * Writes a little-endian 64-bit unsigned int into a buffer. - */ +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(); + } + } -function writeUInt64(value, buffer) { - if (value < 0 || value > MAX_EXACT_UINT64) { - throw new Error("Value out of range."); - } + add(module) { + this.modules.add(module); + } - var lowWord = value % BIT_32; - var highWord = Math.floor(value / BIT_32); - buffer.writeUInt32LE(lowWord, 0); - buffer.writeUInt32LE(highWord, 4); -} + has(module) { + return this.modules.has(module); + } -/***/ }), + isEmpty() { + return this.modules.size === 1; + } -/***/ 89943: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + addWarning(module, problem) { + this.warnings.set(module, problem); + } -"use strict"; + 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(); + } -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; + clone() { + return new ConcatConfiguration(this.rootModule, this); + } -var _leb = _interopRequireDefault(__webpack_require__(80881)); + set(config) { + this.rootModule = config.rootModule; + this.modules = config.modules; + this.warnings = config.warnings; + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = ModuleConcatenationPlugin; -/** - * 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); -} +/***/ 68053: +/***/ (function(module) { -function decodeUInt64(encodedBuffer, index) { - return _leb.default.decodeUInt64(encodedBuffer, index); -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function decodeInt32(encodedBuffer, index) { - return _leb.default.decodeInt32(encodedBuffer, index); -} -function decodeUInt32(encodedBuffer, index) { - return _leb.default.decodeUInt32(encodedBuffer, index); -} +/** @typedef {import("../Compiler")} Compiler */ -function encodeU32(v) { - return _leb.default.encodeUInt32(v); +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; + } + }); + } + ); + }); + } } -function encodeI32(v) { - return _leb.default.encodeInt32(v); -} +module.exports = NaturalChunkOrderPlugin; -function encodeI64(v) { - return _leb.default.encodeInt64(v); -} /***/ }), -/***/ 80881: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 83741: +/***/ (function(module, __unused_webpack_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; + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -var _long = _interopRequireDefault(__webpack_require__(77960)); -var bits = _interopRequireWildcard(__webpack_require__(62904)); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(88771); -var bufs = _interopRequireWildcard(__webpack_require__(7276)); +/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ -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; } } +class OccurrenceOrderChunkIdsPlugin { + /** + * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); + this.options = options; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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(); -/* - * Module variables - */ + 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++); + } -/** The minimum possible 32-bit signed int. */ -var MIN_INT32 = -0x80000000; -/** The maximum possible 32-bit signed int. */ + 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; + }); + } + ); + } + ); + } +} -var MAX_INT32 = 0x7fffffff; -/** The maximum possible 32-bit unsigned int. */ +module.exports = OccurrenceOrderChunkIdsPlugin; -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; +/***/ 62000: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; /* - * 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. - */ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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. - */ +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(81430); -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. - */ +/** @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; + } -function encodeBufferCommon(buffer, signed) { - var signBit; - var bitCount; + 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(); - if (signed) { - signBit = bits.getSign(buffer); - bitCount = signedBitCount(buffer); - } else { - signBit = 0; - bitCount = unsignedBitCount(buffer); - } + 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); + } - var byteCount = Math.ceil(bitCount / 7); - var result = bufs.alloc(byteCount); + 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(); + }; - 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. + 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++); + } - result[byteCount - 1] &= 0x7f; - return result; + 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; + }); + } + ); + } + ); + } } -/** - * Gets the byte-length of the value encoded in the given buffer at - * the given index. - */ +module.exports = OccurrenceOrderModuleIdsPlugin; -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"); - } +/***/ 67340: +/***/ (function(module) { - return result; -} -/** - * Common decoder for both signed and unsigned ints. This takes an - * LEB128-encoded buffer, returning a bigint-ish buffer. - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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; +// 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(); - if (signed) { - // Sign-extend the last byte. - var lastByte = result[byteLength - 1]; - var endBit = outIndex % 8; + 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); + } - if (endBit !== 0) { - var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. + 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(); + }; - lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff; - } + if (preferEntry) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } - 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). + 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(); - while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) { - byteLength--; - } + 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++); + } - result = bufs.resize(result, byteLength); - return { - value: result, - nextIndex: index - }; + 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; + }); + } + ); + }); + } } -/* - * Exported bindings - */ - -function encodeIntBuffer(buffer) { - return encodeBufferCommon(buffer, true); -} +module.exports = OccurrenceOrderPlugin; -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); +/***/ 78085: +/***/ (function(module) { - if (value < MIN_INT32 || value > MAX_INT32) { - throw new Error("integer too large"); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; +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; -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 - }; -} +/***/ 58142: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function encodeUIntBuffer(buffer) { - return encodeBufferCommon(buffer, false); -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -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; -} +const Queue = __webpack_require__(38637); +const { intersect } = __webpack_require__(54262); -function decodeUInt32(encodedBuffer, index) { - var result = decodeUIntBuffer(encodedBuffer, index); - var parsed = bufs.readUInt(result.value); - var value = parsed.value; - bufs.free(result.value); +const getParentChunksWithModule = (currentChunk, module) => { + const chunks = []; + const stack = new Set(currentChunk.parentsIterable); - if (value > MAX_UINT32) { - throw new Error("integer too large"); - } + for (const chunk of stack) { + if (chunk.containsModule(module)) { + chunks.push(chunk); + } else { + for (const parent of chunk.parentsIterable) { + stack.add(parent); + } + } + } - return { - value: value, - nextIndex: result.nextIndex - }; -} + return chunks; +}; -function encodeUInt64(num) { - var buf = bufs.alloc(8); - bufs.writeUInt64(num, buf); - var result = encodeUIntBuffer(buf); - bufs.free(buf); - return result; -} +class RemoveParentModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const queue = new Queue(); + const availableModulesMap = new WeakMap(); -function decodeUInt64(encodedBuffer, index) { - var result = decodeUIntBuffer(encodedBuffer, index); + 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); + } + } - var value = _long.default.fromBytesLE(result.value, true); + 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); + } + } + } - bufs.free(result.value); - return { - value: value, - nextIndex: result.nextIndex, - lossy: false - }; + // 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; -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; /***/ }), -/***/ 19418: -/***/ (function(__unused_webpack_module, exports) { +/***/ 76894: +/***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decode = decode; +module.exports = class RuntimeChunkPlugin { + constructor(options) { + this.options = Object.assign( + { + name: entrypoint => `runtime~${entrypoint.name}` + }, + options + ); + } -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); } } + 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); + } + } + }); + }); + } +}; -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; - } -} +/***/ 83654: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function decode(bytes) { - return _decode(bytes).map(function (x) { - return String.fromCharCode(x); - }).join(""); -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function _decode(bytes) { - if (bytes.length === 0) { - return []; - } - /** - * 1 byte - */ +const mm = __webpack_require__(53024); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); - { - var _bytes = _toArray(bytes), - b1 = _bytes[0], - bs = _bytes.slice(1); +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Dependency")} Dependency */ - if (b1 < 0x80) { - return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); - } +/** + * @typedef {Object} ExportInModule + * @property {Module} module the module + * @property {string} exportName the name of the export + * @property {boolean} checked if the export is conditional + */ - if (b1 < 0xc0) { - throw new Error("invalid UTF-8 encoding"); - } - } - /** - * 2 bytes - */ +/** + * @typedef {Object} ReexportInfo + * @property {Map} static + * @property {Map>} dynamic + */ - { - var _bytes2 = _toArray(bytes), - _b = _bytes2[0], - b2 = _bytes2[1], - _bs = _bytes2.slice(2); +/** + * @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; +}; - if (_b < 0xe0) { - return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); - } - } - /** - * 3 bytes - */ +/** + * @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 + }); +}; - { - var _bytes3 = _toArray(bytes), - _b2 = _bytes3[0], - _b3 = _bytes3[1], - b3 = _bytes3[2], - _bs2 = _bytes3.slice(3); +/** + * @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)); + } +}; - if (_b2 < 0xf0) { - return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); - } - } - /** - * 4 bytes - */ +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; + } + } - { - var _bytes4 = _toArray(bytes), - _b4 = _bytes4[0], - _b5 = _bytes4[1], - _b6 = _bytes4[2], - b4 = _bytes4[3], - _bs3 = _bytes4.slice(4); + 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(); - 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"); + // 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; + /***/ }), -/***/ 43882: -/***/ (function(__unused_webpack_module, exports) { +/***/ 60474: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.encode = encode; +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; -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); } } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ -function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } +const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); -function con(n) { - return 0x80 | n & 0x3f; -} +const hashFilename = name => { + return crypto + .createHash("md4") + .update(name) + .digest("hex") + .slice(0, 8); +}; -function encode(str) { - var arr = str.split("").map(function (x) { - return x.charCodeAt(0); - }); - return _encode(arr); -} +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; -function _encode(arr) { - if (arr.length === 0) { - return []; - } +const getRequests = chunk => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); + } + return requests; +}; - var _arr = _toArray(arr), - n = _arr[0], - ns = _arr.slice(1); +const getModulesSize = modules => { + let sum = 0; + for (const m of modules) { + sum += m.size(); + } + return sum; +}; - if (n < 0) { - throw new Error("utf8"); - } +/** + * @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; +}; - if (n < 0x80) { - return [n].concat(_toConsumableArray(_encode(ns))); - } +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; + } +}; - if (n < 0x800) { - return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); - } +const compareNumbers = (a, b) => a - b; - if (n < 0x10000) { - return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); - } +const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); +const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); +const ALL_CHUNK_FILTER = chunk => true; - if (n < 0x110000) { - return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); - } +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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + +const WebpackError = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + +const WebpackError = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + +const WebpackError = __webpack_require__(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(__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: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const util = __webpack_require__(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: +/***/ (function(__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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(__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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Generator = __webpack_require__(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__(27352); +const t = __webpack_require__(81875); +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: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Generator = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Generator = __webpack_require__(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: +/***/ (function(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__(81875); +const { decode } = __webpack_require__(27352); +const { + moduleContextFromModuleAST +} = __webpack_require__(71234); + +const { Tapable } = __webpack_require__(56758); +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: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(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: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { ConcatSource } = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { ConcatSource } = __webpack_require__(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { ConcatSource } = __webpack_require__(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: +/***/ (function(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: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { SyncWaterfallHook } = __webpack_require__(56758); +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]); + } + ); - throw new Error("utf8"); + 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; -/***/ }), - -/***/ 81637: -/***/ (function(__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__(19418); - -var _encoder = __webpack_require__(43882); /***/ }), -/***/ 28458: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 92764: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decode = decode; - -var _helperApiError = __webpack_require__(20193); - -var ieee754 = _interopRequireWildcard(__webpack_require__(57732)); - -var utf8 = _interopRequireWildcard(__webpack_require__(81637)); - -var t = _interopRequireWildcard(__webpack_require__(81875)); - -var _leb = __webpack_require__(89943); - -var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(66921)); - -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; - } - } +const JsonpMainTemplatePlugin = __webpack_require__(38017); +const JsonpChunkTemplatePlugin = __webpack_require__(31898); +const JsonpHotUpdateChunkTemplatePlugin = __webpack_require__(44458); - return true; +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 + ); + }); + } } -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); +module.exports = JsonpTemplatePlugin; - 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); - } +/***/ 92929: +/***/ (function(module, exports, __webpack_require__) { - mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); - return { - value: sign * mantissa, - nan: true, - nextIndex: ieee754.NUMBER_OF_BYTE_F32 - }; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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. +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; - 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. - */ +/** @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); - function readU32() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt32)(buffer); - } + 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; +}; - function readVaruint32() { - // where 32 bits = max 4 bytes - var bytes = readBytes(4); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt32)(buffer); - } +exports = module.exports = webpack; +exports.version = version; - 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 - */ +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] + }); + } +}; - 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 - */ +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); + } + }); +}; - function read64() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeInt64)(buffer); - } +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "UglifyJsPlugin", + "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." +); - function readU64() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt64)(buffer); - } +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "CommonsChunkPlugin", + "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." +); - function readByte() { - return readBytes(1)[0]; - } - function parseModuleHeader() { - if (isEOF() === true || offset + 4 > buf.length) { - throw new Error("unexpected end"); - } +/***/ }), - var header = readBytes(4); +/***/ 37919: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { - throw new _helperApiError.CompileError("magic header not detected"); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - dump(header, "wasm magic header"); - eatBytes(4); - } - function parseVersion() { - if (isEOF() === true || offset + 4 > buf.length) { - throw new Error("unexpected end"); - } +const { ConcatSource } = __webpack_require__(53665); - var version = readBytes(4); +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; - 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"); +/***/ 45493: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (length === 0) { - return []; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - var elements = []; +const { ConcatSource } = __webpack_require__(53665); - for (var i = 0; i < length; i++) { - var byte = readByte(); - eatBytes(1); - var value = cast(byte); - dump([byte], value); +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; - 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 +/***/ 72337: +/***/ (function(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; - function parseTypeSection(numberOfTypes) { - var typeInstructionNodes = []; - dump([numberOfTypes], "num types"); +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon - for (var i = 0; i < numberOfTypes; i++) { - var _startLoc = getPosition(); + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + importScripts($require$.p + $hotChunkFilename$); + } - dumpSep("type " + i); - var type = readByte(); - eatBytes(1); + // 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); + } + }; + }); + } - 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)); - } - } + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; - return typeInstructionNodes; - } // Import section - // https://webassembly.github.io/spec/binary/modules.html#binary-importsec +/***/ }), - function parseImportSection(numberOfImports) { - var imports = []; +/***/ 20482: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (var i = 0; i < numberOfImports; i++) { - dumpSep("import header " + i); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - var _startLoc2 = getPosition(); - /** - * Module name - */ +const Template = __webpack_require__(96066); - var moduleName = readUTF8String(); - eatBytes(moduleName.nextIndex); - dump([], "module name (".concat(moduleName.value, ")")); - /** - * Name - */ +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)} + "` + } + ); - var name = readUTF8String(); - eatBytes(name.nextIndex); - dump([], "name (".concat(name.value, ")")); - /** - * Import descr - */ + 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; - 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; +/***/ 21328: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (descrType === "func") { - var indexU32 = readU32(); - var typeindex = indexU32.value; - eatBytes(indexU32.nextIndex); - dump([typeindex], "type index"); - var signature = state.typesInModule[typeindex]; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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); - } +const WebWorkerMainTemplatePlugin = __webpack_require__(20482); +const WebWorkerChunkTemplatePlugin = __webpack_require__(37919); +const WebWorkerHotUpdateChunkTemplatePlugin = __webpack_require__(45493); - imports.push(function () { - var endLoc = getPosition(); - return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2); - }()); - } +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; - return imports; - } // Function section - // https://webassembly.github.io/spec/binary/modules.html#function-section +/***/ }), - function parseFuncSection(numberOfFunctions) { - dump([numberOfFunctions], "num funcs"); +/***/ 19728: +/***/ (function(__unused_webpack_module, exports) { - 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]; +"use strict"; - if (typeof signature === "undefined") { - throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); - } // preserve anonymous, a name might be resolved later +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.cloneNode = cloneNode; - 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 cloneNode(n) { + // $FlowIgnore + var newObj = {}; + for (var k in n) { + newObj[k] = n[k]; + } - function parseExportSection(numberOfExport) { - dump([numberOfExport], "num exports"); // Parse vector of exports + return newObj; +} - for (var i = 0; i < numberOfExport; i++) { - var _startLoc3 = getPosition(); - /** - * Name - */ +/***/ }), +/***/ 81875: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - var name = readUTF8String(); - eatBytes(name.nextIndex); - dump([], "export name (".concat(name.value, ")")); - /** - * exportdescr - */ +"use strict"; - 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]; +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; + } +})); - if (typeof func === "undefined") { - throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); - } +var _nodes = __webpack_require__(94841); - id = t.numberLiteralFromRaw(index, String(index)); - signature = func.signature; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { - var table = state.tablesInModule[index]; +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]; + } + }); +}); - if (typeof table === "undefined") { - throw new _helperApiError.CompileError("unknown table ".concat(index)); - } +var _nodeHelpers = __webpack_require__(1004); - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { - var memNode = state.memoriesInModule[index]; +var _traverse = __webpack_require__(29436); - if (typeof memNode === "undefined") { - throw new _helperApiError.CompileError("unknown memory ".concat(index)); - } +var _signatures = __webpack_require__(77392); - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { - var global = state.globalsInModule[index]; +var _utils = __webpack_require__(38456); - if (typeof global === "undefined") { - throw new _helperApiError.CompileError("unknown global ".concat(index)); - } +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]; + } + }); +}); - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; - } else { - console.warn("Unsupported export type: " + toHex(typeIndex)); - return; - } +var _clone = __webpack_require__(19728); - 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 +/***/ }), +/***/ 1004: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - function parseCodeSection(numberOfFuncs) { - dump([numberOfFuncs], "number functions"); // Parse vector of function +"use strict"; - 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 +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 bodySizeU32 = readU32(); - eatBytes(bodySizeU32.nextIndex); - dump([bodySizeU32.value], "function body size"); - var code = []; - /** - * Parse locals - */ +var _wastParser = __webpack_require__(9016); - var funcLocalNumU32 = readU32(); - var funcLocalNum = funcLocalNumU32.value; - eatBytes(funcLocalNumU32.nextIndex); - dump([funcLocalNum], "num locals"); - var locals = []; +var _nodes = __webpack_require__(94841); - for (var _i = 0; _i < funcLocalNum; _i++) { - var _startLoc5 = getPosition(); +function numberLiteralFromRaw(rawValue) { + var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32"; + var original = rawValue; // Remove numeric separators _ - 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 = []; + if (typeof rawValue === "string") { + rawValue = rawValue.replace(/_/g, ""); + } - for (var _i2 = 0; _i2 < localCount; _i2++) { - args.push(t.valtypeLiteral(type)); + 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)); } - var localNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); - }(); - - locals.push(localNode); - dump([valtypeByte], type); + case "u32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parseU32)(rawValue), String(original)); + } - if (typeof type === "undefined") { - throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); + case "i64": + { + return (0, _nodes.longNumberLiteral)((0, _wastParser.parse64I)(rawValue), String(original)); } - } - code.push.apply(code, locals); // Decode instructions until the end + case "f32": + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse32F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + // f64 - parseInstructionBlock(code); - var endLoc = getPosition(); - state.elementsInCodeSection.push({ - code: code, - locals: locals, - endLoc: endLoc, - startLoc: _startLoc4, - bodySize: bodySizeU32.value - }); + default: + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } } } +} - function parseInstructionBlock(code) { - while (true) { - var _startLoc6 = getPosition(); +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); +} - var instructionAlreadyCreated = false; - var instructionByte = readByte(); - eatBytes(1); +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 + */ - if (instructionByte === 0xfe) { - throw new _helperApiError.CompileError("Atomic instructions are not implemented"); - } - var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; +function withLoc(n, end, start) { + var loc = { + start: start, + end: end + }; + n.loc = loc; + return n; +} - if (typeof instruction === "undefined") { - throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); - } +function withRaw(n, raw) { + n.raw = raw; + return n; +} - if (typeof instruction.object === "string") { - dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); - } else { - dump([instructionByte], instruction.name); - } - /** - * End of the function - */ +function funcParam(valtype, id) { + return { + id: id, + valtype: valtype + }; +} +function indexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} - if (instruction.name === "end") { - var node = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); - }(); +function memIndexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} - code.push(node); - break; - } +/***/ }), - var args = []; +/***/ 89231: +/***/ (function(__unused_webpack_module, exports) { - if (instruction.name === "loop") { - var _startLoc7 = getPosition(); +"use strict"; - 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)); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPath = createPath; - var instr = []; - parseInstructionBlock(instr); // preserve anonymous +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); } - var label = t.withRaw(t.identifier(getUniqueName("loop")), ""); +function findParent(_ref, cb) { + var parentPath = _ref.parentPath; - var loopNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); - }(); + if (parentPath == null) { + throw new Error("node is root"); + } - code.push(loopNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "if") { - var _startLoc8 = getPosition(); + var currentPath = parentPath; - var _blocktypeByte = readByte(); + while (cb(currentPath) !== false) { + // Hit the root node, stop + // $FlowIgnore + if (currentPath.parentPath == null) { + return null; + } // $FlowIgnore - eatBytes(1); - var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; - dump([_blocktypeByte], "blocktype"); - if (typeof _blocktype === "undefined") { - throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); - } + currentPath = currentPath.parentPath; + } - var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); - var ifBody = []; - parseInstructionBlock(ifBody); // Defaults to no alternate + return currentPath.node; +} - var elseIndex = 0; +function insertBefore(context, newNode) { + return insert(context, newNode); +} - for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { - var _instr = ifBody[elseIndex]; +function insertAfter(context, newNode) { + return insert(context, newNode, 1); +} - if (_instr.type === "Instr" && _instr.id === "else") { - break; - } - } +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; - var consequentInstr = ifBody.slice(0, elseIndex); - var alternate = ifBody.slice(elseIndex + 1); // wast sugar + if (!inList) { + throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); + } - var testInstrs = []; + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } - var ifNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); - }(); + // $FlowIgnore + var parentList = parentPath.node[parentKey]; + var indexInList = parentList.findIndex(function (n) { + return n === node; + }); + parentList.splice(indexInList + indexOffset, 0, newNode); +} - code.push(ifNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "block") { - var _startLoc9 = getPosition(); +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]; + } - var _blocktypeByte2 = readByte(); + node._deleted = true; +} - eatBytes(1); - var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; - dump([_blocktypeByte2], "blocktype"); +function stop(context) { + context.shouldStop = true; +} - if (typeof _blocktype2 === "undefined") { - throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); - } +function replaceWith(context, newNode) { + // $FlowIgnore + var parentNode = context.parentPath.node; // $FlowIgnore - var _instr2 = []; - parseInstructionBlock(_instr2); // preserve anonymous + var parentProperty = parentNode[context.parentKey]; - var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); + 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; + } - var blockNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); - }(); + context.node._deleted = true; + context.node = newNode; +} // bind the context to the first argument of node operations - 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); - }(); +function bindNodeOperations(operations, context) { + var keys = Object.keys(operations); + var boundOperations = {}; + keys.forEach(function (key) { + boundOperations[key] = operations[key].bind(null, context); + }); + return boundOperations; +} - code.push(callNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "call_indirect") { - var _startLoc10 = getPosition(); +function createPathOperations(context) { + // $FlowIgnore + return bindNodeOperations({ + findParent: findParent, + replaceWith: replaceWith, + remove: remove, + insertBefore: insertBefore, + insertAfter: insertAfter, + stop: stop + }, context); +} - var indexU32 = readU32(); - var typeindex = indexU32.value; - eatBytes(indexU32.nextIndex); - dump([typeindex], "type index"); - var signature = state.typesInModule[typeindex]; +function createPath(context) { + var path = _extends({}, context); // $FlowIgnore - 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), []); + Object.assign(path, createPathOperations(path)); // $FlowIgnore - var flagU32 = readU32(); - var flag = flagU32.value; // 0x00 - reserved byte + return path; +} - eatBytes(flagU32.nextIndex); +/***/ }), - if (flag !== 0) { - throw new _helperApiError.CompileError("zero flag expected"); - } +/***/ 94841: +/***/ (function(__unused_webpack_module, exports) { - 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"); +"use strict"; - 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(); +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; - var _index2 = _indexU.value; - eatBytes(_indexU.nextIndex); +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); } - if (_index2 !== 0) { - throw new Error("zero flag expected"); - } +// THIS FILE IS AUTOGENERATED +// see scripts/generateNodeUtils.js +function isTypeOf(t) { + return function (n) { + return n.type === t; + }; +} - 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)); - } +function assertTypeOf(t) { + return function (n) { + return function () { + if (!(n.type === t)) { + throw new Error('n.type === t' + " error: " + (undefined || "unknown")); + } + }(); + }; +} - if (instruction.object === "u32") { - var valueu32 = readU32(); - var _value = valueu32.value; - eatBytes(valueu32.nextIndex); - dump([_value], "u32 value"); - args.push(t.numberLiteralFromRaw(_value)); - } +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 (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 (!(_typeof(fields) === "object" && typeof fields.length !== "undefined")) { + throw new Error('typeof fields === "object" && typeof fields.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - 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); - } + var node = { + type: "Module", + id: id, + fields: fields + }; - 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 (typeof metadata !== "undefined") { + node.metadata = metadata; + } - 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)); - } - } + return node; +} - 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); - }(); +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")); + } - code.push(_node3); - } else { - var _node4 = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); - }(); + 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")); + } + } - code.push(_node4); - } - } + 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")); } - } // https://webassembly.github.io/spec/core/binary/types.html#limits + } + 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")); + } + } - function parseLimits() { - var limitType = readByte(); - eatBytes(1); - dump([limitType], "limit type"); - var min, max; + var node = { + type: "ModuleMetadata", + sections: sections + }; - 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 (typeof functionNames !== "undefined" && functionNames.length > 0) { + node.functionNames = functionNames; + } - if (limitType === 0x00) { - var _u32min = readU32(); + if (typeof localNames !== "undefined" && localNames.length > 0) { + node.localNames = localNames; + } - min = parseInt(_u32min.value); - eatBytes(_u32min.nextIndex); - dump([min], "min"); - } + if (typeof producers !== "undefined" && producers.length > 0) { + node.producers = producers; + } - return t.limit(min, max); - } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype + 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)); + } - 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]; + var node = { + type: "ModuleNameMetadata", + value: value + }; + return node; +} - if (typeof elementType === "undefined") { - throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType)); - } +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)); + } - var limits = parseLimits(); - return t.table(elementType, limits, name); - } // https://webassembly.github.io/spec/binary/types.html#global-types + 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 parseGlobalType() { - var valtypeByte = readByte(); - eatBytes(1); - var type = _helperWasmBytecode.default.valtypes[valtypeByte]; - dump([valtypeByte], type); +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 type === "undefined") { - throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte)); - } + if (!(typeof localIndex === "number")) { + throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); + } - var globalTypeByte = readByte(); - eatBytes(1); - var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte]; - dump([globalTypeByte], "global type (".concat(globalType, ")")); + if (!(typeof functionIndex === "number")) { + throw new Error('typeof functionIndex === "number"' + " error: " + ("Argument functionIndex must be of type number, given: " + _typeof(functionIndex) || 0)); + } - if (typeof globalType === "undefined") { - throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte)); - } + var node = { + type: "LocalNameMetadata", + value: value, + localIndex: localIndex, + functionIndex: functionIndex + }; + return node; +} - 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 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")); + } - function parseNameSectionFunctions() { - var functionNames = []; - var numberOfFunctionsu32 = readU32(); - var numbeOfFunctions = numberOfFunctionsu32.value; - eatBytes(numberOfFunctionsu32.nextIndex); + var node = { + type: "BinaryModule", + id: id, + blob: blob + }; + return node; +} - 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)); +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)); } + } - return functionNames; + if (!(_typeof(string) === "object" && typeof string.length !== "undefined")) { + throw new Error('typeof string === "object" && typeof string.length !== "undefined"' + " error: " + (undefined || "unknown")); } - function parseNameSectionLocals() { - var localNames = []; - var numbeOfFunctionsu32 = readU32(); - var numbeOfFunctions = numbeOfFunctionsu32.value; - eatBytes(numbeOfFunctionsu32.nextIndex); + 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; +} - 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); +function producersSectionMetadata(producers) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - 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)); - } - } + var node = { + type: "ProducersSectionMetadata", + producers: producers + }; + return node; +} - return localNames; - } // this is a custom section used for name resolution - // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section +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")); + } - function parseNameSection(remainingBytes) { - var nameMetadata = []; - var initialOffset = offset; + if (!(_typeof(sdk) === "object" && typeof sdk.length !== "undefined")) { + throw new Error('typeof sdk === "object" && typeof sdk.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - while (offset - initialOffset < remainingBytes) { - // name_type - var sectionTypeByte = readVaruint7(); - eatBytes(sectionTypeByte.nextIndex); // name_payload_len + var node = { + type: "ProducerMetadata", + language: language, + processedBy: processedBy, + sdk: sdk + }; + return node; +} - var subSectionSizeInBytesu32 = readVaruint32(); - eatBytes(subSectionSizeInBytesu32.nextIndex); +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)); + } - 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; - } + if (!(typeof version === "string")) { + throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); + } - case 2: - { - nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals())); - break; - } + var node = { + type: "ProducerMetadataVersionedName", + name: name, + version: version + }; + return node; +} - default: - { - // skip unknown subsection - eatBytes(subSectionSizeInBytesu32.value); - } - } - } +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")); + } - return nameMetadata; - } // this is a custom section used for information about the producers - // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md + 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)); + } - function parseProducersSection() { - var metadata = t.producersSectionMetadata([]); // field_count + if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { + throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - var sectionTypeByte = readVaruint32(); - eatBytes(sectionTypeByte.nextIndex); - dump([sectionTypeByte.value], "num of producers"); - var fields = { - language: [], - "processed-by": [], - sdk: [] - }; // fields + var node = { + type: "Instr", + id: id, + args: args + }; - for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) { - // field_name - var fieldName = readUTF8String(); - eatBytes(fieldName.nextIndex); // field_value_count + if (typeof object !== "undefined") { + node.object = object; + } - var valueCount = readVaruint32(); - eatBytes(valueCount.nextIndex); // field_values + if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { + node.namedArgs = namedArgs; + } - 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)); - } + return node; +} - metadata.producers.push(fields[fieldName.value]); - } +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")); + } - return metadata; + if (!(_typeof(consequent) === "object" && typeof consequent.length !== "undefined")) { + throw new Error('typeof consequent === "object" && typeof consequent.length !== "undefined"' + " error: " + (undefined || "unknown")); } - function parseGlobalSection(numberOfGlobals) { - var globals = []; - dump([numberOfGlobals], "num globals"); + if (!(_typeof(alternate) === "object" && typeof alternate.length !== "undefined")) { + throw new Error('typeof alternate === "object" && typeof alternate.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - for (var i = 0; i < numberOfGlobals; i++) { - var _startLoc11 = getPosition(); + var node = { + type: "IfInstruction", + id: "if", + testLabel: testLabel, + test: test, + result: result, + consequent: consequent, + alternate: alternate + }; + return node; +} - var globalType = parseGlobalType(); - /** - * Global expressions - */ +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 init = []; - parseInstructionBlock(init); + var node = { + type: "StringLiteral", + value: value + }; + return node; +} - var node = function () { - var endLoc = getPosition(); - return t.withLoc(t.global(globalType, init), endLoc, _startLoc11); - }(); +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)); + } - globals.push(node); - state.globalsInModule.push(node); - } + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } - return globals; + 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)); } - function parseElemSection(numberOfElements) { - var elems = []; - dump([numberOfElements], "num elements"); + var node = { + type: "LongNumberLiteral", + value: value, + raw: raw + }; + return node; +} - for (var i = 0; i < numberOfElements; i++) { - var _startLoc12 = getPosition(); +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)); + } - var tableindexu32 = readU32(); - var tableindex = tableindexu32.value; - eatBytes(tableindexu32.nextIndex); - dump([tableindex], "table index"); - /** - * Parse instructions - */ + 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)); + } + } - var instr = []; - parseInstructionBlock(instr); - /** - * Parse ( vector function index ) * - */ + 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)); + } + } - var indicesu32 = readU32(); - var indices = indicesu32.value; - eatBytes(indicesu32.nextIndex); - dump([indices], "num indices"); - var indexValues = []; + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } - 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 node = { + type: "FloatLiteral", + value: value, + raw: raw + }; - var elemNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); - }(); + if (nan === true) { + node.nan = true; + } - elems.push(elemNode); - } + if (inf === true) { + node.inf = true; + } - return elems; - } // https://webassembly.github.io/spec/core/binary/types.html#memory-types + 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")); + } - function parseMemoryType(i) { - var limits = parseLimits(); - return t.memory(limits, t.indexLiteral(i)); - } // https://webassembly.github.io/spec/binary/modules.html#table-section + 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 parseTableSection(numberOfElements) { - var tables = []; - dump([numberOfElements], "num elements"); +function indexInFuncSection(index) { + var node = { + type: "IndexInFuncSection", + index: index + }; + return node; +} - for (var i = 0; i < numberOfElements; i++) { - var tablesNode = parseTableType(i); - state.tablesInModule.push(tablesNode); - tables.push(tablesNode); - } +function valtypeLiteral(name) { + var node = { + type: "ValtypeLiteral", + name: name + }; + return node; +} - return tables; - } // https://webassembly.github.io/spec/binary/modules.html#memory-section +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 parseMemorySection(numberOfElements) { - var memories = []; - dump([numberOfElements], "num elements"); +function globalType(valtype, mutability) { + var node = { + type: "GlobalType", + valtype: valtype, + mutability: mutability + }; + return node; +} - for (var i = 0; i < numberOfElements; i++) { - var memoryNode = parseMemoryType(i); - state.memoriesInModule.push(memoryNode); - memories.push(memoryNode); - } +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)); + } - return memories; - } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec + 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)); + } - 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 + 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 parseDataSection(numberOfElements) { - var dataEntries = []; - dump([numberOfElements], "num elements"); +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")); + } - 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; + var node = { + type: "Global", + globalType: globalType, + init: init, + name: name + }; + return node; +} - if (hasExtraInstrs) { - throw new _helperApiError.CompileError("data section offset must be a single instruction"); - } +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)); + } - var bytes = parseVec(function (b) { - return b; - }); - dump([], "init"); - dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); + 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")); } + } - return dataEntries; - } // https://webassembly.github.io/spec/binary/modules.html#binary-section + var node = { + type: "Table", + elementType: elementType, + limits: limits, + name: name + }; + if (typeof elements !== "undefined" && elements.length > 0) { + node.elements = elements; + } - function parseSection(sectionIndex) { - var sectionId = readByte(); - eatBytes(1); + return node; +} - 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)); - } +function memory(limits, id) { + var node = { + type: "Memory", + limits: limits, + id: id + }; + return node; +} - var nextSectionIndex = sectionIndex; - var startOffset = offset; - var startLoc = getPosition(); - var u32 = readU32(); - var sectionSizeInBytes = u32.value; - eatBytes(u32.nextIndex); +function funcImportDescr(id, signature) { + var node = { + type: "FuncImportDescr", + id: id, + signature: signature + }; + return node; +} - var sectionSizeInBytesNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); - }(); +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)); + } - switch (sectionId) { - case _helperWasmBytecode.default.sections.type: - { - dumpSep("section Type"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + var node = { + type: "ModuleImport", + module: module, + name: name, + descr: descr + }; + return node; +} - var _startLoc13 = getPosition(); +function moduleExportDescr(exportType, id) { + var node = { + type: "ModuleExportDescr", + exportType: exportType, + id: id + }; + return node; +} - var _u = readU32(); +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 numberOfTypes = _u.value; - eatBytes(_u.nextIndex); + var node = { + type: "ModuleExport", + name: name, + descr: descr + }; + return node; +} - var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13); - }()); +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)); + } - var _nodes = parseTypeSection(numberOfTypes); + 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)); + } + } - return { - nodes: _nodes, - metadata: _metadata, - nextSectionIndex: nextSectionIndex - }; - } + var node = { + type: "Limit", + min: min + }; - case _helperWasmBytecode.default.sections.table: - { - dumpSep("section Table"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + if (typeof max !== "undefined") { + node.max = max; + } - var _startLoc14 = getPosition(); + return node; +} - var _u2 = readU32(); +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")); + } - var numberOfTable = _u2.value; - eatBytes(_u2.nextIndex); - dump([numberOfTable], "num tables"); + if (!(_typeof(results) === "object" && typeof results.length !== "undefined")) { + throw new Error('typeof results === "object" && typeof results.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); - }()); + var node = { + type: "Signature", + params: params, + results: results + }; + return node; +} - var _nodes2 = parseTableSection(numberOfTable); +function program(body) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - return { - nodes: _nodes2, - metadata: _metadata2, - nextSectionIndex: nextSectionIndex - }; - } + var node = { + type: "Program", + body: body + }; + return node; +} - case _helperWasmBytecode.default.sections.import: - { - dumpSep("section Import"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); +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)); + } - var _startLoc15 = getPosition(); + 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 numberOfImportsu32 = readU32(); - var numberOfImports = numberOfImportsu32.value; - eatBytes(numberOfImportsu32.nextIndex); - dump([numberOfImports], "number of imports"); + var node = { + type: "Identifier", + value: value + }; - var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); - }()); + if (typeof raw !== "undefined") { + node.raw = raw; + } - var _nodes3 = parseImportSection(numberOfImports); + return node; +} - return { - nodes: _nodes3, - metadata: _metadata3, - nextSectionIndex: nextSectionIndex - }; - } +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")); + } - case _helperWasmBytecode.default.sections.func: - { - dumpSep("section Function"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + var node = { + type: "BlockInstruction", + id: "block", + label: label, + instr: instr, + result: result + }; + return node; +} - var _startLoc16 = getPosition(); +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 numberOfFunctionsu32 = readU32(); - var numberOfFunctions = numberOfFunctionsu32.value; - eatBytes(numberOfFunctionsu32.nextIndex); + var node = { + type: "CallInstruction", + id: "call", + index: index + }; - var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); - }()); + if (typeof instrArgs !== "undefined" && instrArgs.length > 0) { + node.instrArgs = instrArgs; + } - parseFuncSection(numberOfFunctions); - var _nodes4 = []; - return { - nodes: _nodes4, - metadata: _metadata4, - nextSectionIndex: nextSectionIndex - }; - } + if (typeof numeric !== "undefined") { + node.numeric = numeric; + } - case _helperWasmBytecode.default.sections.export: - { - dumpSep("section Export"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + return node; +} - var _startLoc17 = getPosition(); +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 _u3 = readU32(); + var node = { + type: "CallIndirectInstruction", + id: "call_indirect", + signature: signature + }; - var numberOfExport = _u3.value; - eatBytes(_u3.nextIndex); + if (typeof intrs !== "undefined" && intrs.length > 0) { + node.intrs = intrs; + } - var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17); - }()); + return node; +} - parseExportSection(numberOfExport); - var _nodes5 = []; - return { - nodes: _nodes5, - metadata: _metadata5, - nextSectionIndex: nextSectionIndex - }; - } +function byteArray(values) { + if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { + throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - case _helperWasmBytecode.default.sections.code: - { - dumpSep("section Code"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + var node = { + type: "ByteArray", + values: values + }; + return node; +} - var _startLoc18 = getPosition(); +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")); + } - var _u4 = readU32(); + 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 numberOfFuncs = _u4.value; - eatBytes(_u4.nextIndex); + var node = { + type: "Func", + name: name, + signature: signature, + body: body + }; - var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); - }()); + if (isExternal === true) { + node.isExternal = true; + } - if (opts.ignoreCodeSection === true) { - var remainingBytes = sectionSizeInBytes - _u4.nextIndex; - eatBytes(remainingBytes); // eat the entire section - } else { - parseCodeSection(numberOfFuncs); - } + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } - var _nodes6 = []; - return { - nodes: _nodes6, - metadata: _metadata6, - nextSectionIndex: nextSectionIndex - }; - } + return node; +} - case _helperWasmBytecode.default.sections.start: - { - dumpSep("section Start"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); +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 _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); + var node = { + type: "InternalBrUnless", + target: target + }; + return node; +} - var _nodes7 = [parseStartSection()]; - return { - nodes: _nodes7, - metadata: _metadata7, - nextSectionIndex: nextSectionIndex - }; - } +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)); + } - case _helperWasmBytecode.default.sections.element: - { - dumpSep("section Element"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + var node = { + type: "InternalGoto", + target: target + }; + return node; +} - var _startLoc19 = getPosition(); +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 numberOfElementsu32 = readU32(); - var numberOfElements = numberOfElementsu32.value; - eatBytes(numberOfElementsu32.nextIndex); + var node = { + type: "InternalCallExtern", + target: target + }; + return node; +} - var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); - }()); +function internalEndAndReturn() { + var node = { + type: "InternalEndAndReturn" + }; + return node; +} - var _nodes8 = parseElemSection(numberOfElements); +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; - return { - nodes: _nodes8, - metadata: _metadata8, - nextSectionIndex: nextSectionIndex - }; - } +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); +}; - case _helperWasmBytecode.default.sections.global: - { - dumpSep("section Global"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); +exports.isNode = isNode; - var _startLoc20 = getPosition(); +var isBlock = function isBlock(node) { + return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); +}; - var numberOfGlobalsu32 = readU32(); - var numberOfGlobals = numberOfGlobalsu32.value; - eatBytes(numberOfGlobalsu32.nextIndex); +exports.isBlock = isBlock; - var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); - }()); +var isInstruction = function isInstruction(node) { + return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); +}; - var _nodes9 = parseGlobalSection(numberOfGlobals); +exports.isInstruction = isInstruction; - return { - nodes: _nodes9, - metadata: _metadata9, - nextSectionIndex: nextSectionIndex - }; - } +var isExpression = function isExpression(node) { + return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); +}; - case _helperWasmBytecode.default.sections.memory: - { - dumpSep("section Memory"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); +exports.isExpression = isExpression; - var _startLoc21 = getPosition(); +var isNumericLiteral = function isNumericLiteral(node) { + return isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node); +}; - var _numberOfElementsu = readU32(); +exports.isNumericLiteral = isNumericLiteral; - var _numberOfElements = _numberOfElementsu.value; - eatBytes(_numberOfElementsu.nextIndex); +var isImportDescr = function isImportDescr(node) { + return isGlobalType(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node); +}; - var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); - }()); +exports.isImportDescr = isImportDescr; - var _nodes10 = parseMemorySection(_numberOfElements); +var isIntrinsic = function isIntrinsic(node) { + return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; - return { - nodes: _nodes10, - metadata: _metadata10, - nextSectionIndex: nextSectionIndex - }; - } +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; - case _helperWasmBytecode.default.sections.data: - { - dumpSep("section Data"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); +/***/ }), - var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode); +/***/ 77392: +/***/ (function(__unused_webpack_module, exports) { - var _startLoc22 = getPosition(); +"use strict"; - var _numberOfElementsu2 = readU32(); - var _numberOfElements2 = _numberOfElementsu2.value; - eatBytes(_numberOfElementsu2.nextIndex); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.signatures = void 0; - _metadata11.vectorOfSize = function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22); - }(); +function sign(input, output) { + return [input, output]; +} - if (opts.ignoreDataSection === true) { - var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex; +var u32 = "u32"; +var i32 = "i32"; +var i64 = "i64"; +var f32 = "f32"; +var f64 = "f64"; - eatBytes(_remainingBytes); // eat the entire section +var vector = function vector(t) { + var vecType = [t]; // $FlowIgnore - dumpSep("ignore data (" + sectionSizeInBytes + " bytes)"); - return { - nodes: [], - metadata: _metadata11, - nextSectionIndex: nextSectionIndex - }; - } else { - var _nodes11 = parseDataSection(_numberOfElements2); + vecType.vector = true; + return vecType; +}; - return { - nodes: _nodes11, - metadata: _metadata11, - nextSectionIndex: nextSectionIndex - }; - } - } +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; - 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; +/***/ 29436: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - if (sectionName.value === "name") { - var initialOffset = offset; +"use strict"; - 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)"); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.traverse = traverse; - return { - nodes: [], - metadata: _metadata12, - nextSectionIndex: nextSectionIndex - }; - } - } +var _nodePath = __webpack_require__(89231); - throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); - } +var _nodes = __webpack_require__(94841); - 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 - */ +// 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; - while (offset < buf.length) { - var _parseSection = parseSection(sectionIndex), - _nodes12 = _parseSection.nodes, - _metadata13 = _parseSection.metadata, - nextSectionIndex = _parseSection.nextSectionIndex; + function innerWalk(context, callback) { + if (stop) { + return; + } - 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 + var node = context.node; - if (nextSectionIndex) { - sectionIndex = nextSectionIndex; + if (node === undefined) { + console.warn("traversing with an empty context"); + return; } - } - /** - * Transform the state into AST nodes - */ + if (node._deleted === true) { + return; + } - 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 + var path = (0, _nodePath.createPath)(context); + callback(node.type, path); - if (func.isExternal === true) { + if (path.shouldStop) { + stop = true; return; } - var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex]; + Object.keys(node).forEach(function (prop) { + var value = node[prop]; - if (opts.ignoreCodeSection === false) { - if (typeof decodedElementInCodeSection === "undefined") { - throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found"); + if (value === null || value === undefined) { + return; } - body = decodedElementInCodeSection.code; - } - - funcIndex++; - var funcNode = t.func(func.id, t.signature(params, result), body); + 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); + } + }); + }); + } - if (func.isExternal === true) { - funcNode.isExternal = func.isExternal; - } // Add function position in the binary if possible + innerWalk(context, callback); +} +var noop = function noop() {}; - if (opts.ignoreCodeSection === false) { - var _startLoc23 = decodedElementInCodeSection.startLoc, - endLoc = decodedElementInCodeSection.endLoc, - bodySize = decodedElementInCodeSection.bodySize; - funcNode = t.withLoc(funcNode, endLoc, _startLoc23); - funcNode.metadata = { - bodySize: bodySize - }; +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)); } - - 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)); + 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); + } + }); }); - dumpSep("end of program"); - var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers)); - return t.program([module]); } /***/ }), -/***/ 27352: +/***/ 38456: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -117103,8292 +117227,8883 @@ function decode(ab, opts) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decode = decode; +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 decoder = _interopRequireWildcard(__webpack_require__(28458)); +var _signatures = __webpack_require__(77392); -var t = _interopRequireWildcard(__webpack_require__(81875)); +var _traverse = __webpack_require__(29436); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(66921)); 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 _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 restoreFunctionNames(ast) { - var functionNames = []; - t.traverse(ast, { - FunctionNameMetadata: function FunctionNameMetadata(_ref) { +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; - functionNames.push({ - name: node.value, - index: node.index - }); - } - }); - if (functionNames.length === 0) { - return; - } + if (node.section === name) { + section = node; + } + }) + }); + return section; +} - t.traverse(ast, { - Func: function (_Func) { - function Func(_x) { - return _Func.apply(this, arguments); +function getSectionMetadatas(ast, name) { + var sections = []; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata2) { + function SectionMetadata(_x2) { + return _SectionMetadata2.apply(this, arguments); } - Func.toString = function () { - return _Func.toString(); + SectionMetadata.toString = function () { + return _SectionMetadata2.toString(); }; - return Func; + 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 - var nodeName = node.name; - var indexBasedFunctionName = nodeName.value; - var index = Number(indexBasedFunctionName.replace("func_", "")); - var functionName = functionNames.find(function (f) { - return f.index === index; - }); + fieldEndCol = field.loc.end.column; + } // $FlowIgnore: assertHasLoc ensures that - 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); - } + if (didInsert === false && n.loc.start.column < fieldEndCol) { + didInsert = true; + acc.push(n); + } - ModuleExport.toString = function () { - return _ModuleExport.toString(); - }; + acc.push(field); + return acc; + }, []); // Handles empty modules or n is the last element - return ModuleExport; - }(function (_ref3) { - var node = _ref3.node; + if (didInsert === false) { + m.fields.push(n); + } +} - 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; - }); +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")); + } +} - if (functionName) { - node.descr.id = t.identifier(functionName.name); - } - } - }), - ModuleImport: function (_ModuleImport) { - function ModuleImport(_x3) { - return _ModuleImport.apply(this, arguments); - } +function getEndOfSection(s) { + assertHasLoc(s.size); + return s.startOffset + s.size.value + ( // $FlowIgnore + s.size.loc.end.column - s.size.loc.start.column); +} - ModuleImport.toString = function () { - return _ModuleImport.toString(); - }; +function shiftLoc(node, delta) { + // $FlowIgnore + node.loc.start.column += delta; // $FlowIgnore - return ModuleImport; - }(function (_ref4) { - var node = _ref4.node; + node.loc.end.column += delta; +} - 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; - }); +function shiftSection(ast, node, delta) { + if (node.type !== "SectionMetadata") { + throw new Error("Can not shift node " + JSON.stringify(node.type)); + } - if (functionName) { - // $FlowIgnore - node.descr.id = t.identifier(functionName.name); - } - } - }), - CallInstruction: function (_CallInstruction) { - function CallInstruction(_x4) { - return _CallInstruction.apply(this, arguments); - } + node.startOffset += delta; - CallInstruction.toString = function () { - return _CallInstruction.toString(); - }; + if (_typeof(node.size.loc) === "object") { + shiftLoc(node.size, delta); + } // Custom sections doesn't have vectorOfSize - 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 + if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { + shiftLoc(node.vectorOfSize, delta); + } - delete node.raw; + 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 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 - }); - } - }); +function signatureForOpcode(object, name) { + var opcodeName = name; - if (localNames.length === 0) { - return; + if (object !== undefined && object !== "") { + opcodeName = object + "." + name; } - t.traverse(ast, { - Func: function (_Func2) { - function Func(_x5) { - return _Func2.apply(this, arguments); - } + var sign = _signatures.signatures[opcodeName]; - Func.toString = function () { - return _Func2.toString(); - }; + if (sign == undefined) { + // TODO: Uncomment this when br_table and others has been done + //throw new Error("Invalid opcode: "+opcodeName); + return [object, object]; + } - return Func; - }(function (_ref6) { - var node = _ref6.node; - var signature = node.signature; + return sign[0]; +} - if (signature.type !== "Signature") { - return; - } // $FlowIgnore +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; + } - 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; - }); + return prefix + "_" + inc[prefix]; + }; +} - if (paramName && paramName.name !== "") { - param.id = paramName.name; - } - }); - }) - }); +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 restoreModuleName(ast) { - t.traverse(ast, { - ModuleNameMetadata: function (_ModuleNameMetadata) { - function ModuleNameMetadata(_x6) { - return _ModuleNameMetadata.apply(this, arguments); - } +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); + } - ModuleNameMetadata.toString = function () { - return _ModuleNameMetadata.toString(); - }; + return n.loc.end.column; +} - return ModuleNameMetadata; - }(function (moduleNameMetadataPath) { - // update module - t.traverse(ast, { - Module: function (_Module) { - function Module(_x7) { - return _Module.apply(this, arguments); - } +function getFunctionBeginingByteOffset(n) { + if (!(n.body.length > 0)) { + throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown")); + } - Module.toString = function () { - return _Module.toString(); - }; + var _n$body = _slicedToArray(n.body, 1), + firstInstruction = _n$body[0]; - return Module; - }(function (_ref7) { - var node = _ref7.node; - var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser + return getStartByteOffset(firstInstruction); +} - if (name === "") { - name = null; - } +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")); + } - node.id = name; - }) - }); - }) - }); + 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 decode(buf, customOpts) { - var opts = Object.assign({}, defaultDecoderOpts, customOpts); - var ast = decoder.decode(buf, opts); +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 (opts.ignoreCustomNameSection === false) { - restoreFunctionNames(ast); - restoreLocalNames(ast); - restoreModuleName(ast); + if (!(_typeof(fistInstruction) === "object")) { + throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); } - return ast; + // $FlowIgnore + return getStartByteOffset(fistInstruction); } /***/ }), -/***/ 77087: +/***/ 20193: /***/ (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" - }; +"use strict"; - // 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"; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; - var keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" - }; +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 keywordRelationalOperator = /^in(stanceof)?$/; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // ## Character categories +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; } - // 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"; +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 nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +var RuntimeError = +/*#__PURE__*/ +function (_Error) { + _inherits(RuntimeError, _Error); - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + function RuntimeError() { + _classCallCheck(this, RuntimeError); - // 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 + return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); + } - // 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]; + return RuntimeError; +}(Error); - // 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]; +exports.RuntimeError = RuntimeError; - // 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 } - } - } +var CompileError = +/*#__PURE__*/ +function (_Error2) { + _inherits(CompileError, _Error2); - // Test whether a given character code starts an identifier. + function CompileError() { + _classCallCheck(this, CompileError); - 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) + return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); } - // 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) - } + return CompileError; +}(Error); - // ## Token types +exports.CompileError = CompileError; - // 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. +var LinkError = +/*#__PURE__*/ +function (_Error3) { + _inherits(LinkError, _Error3); - // All token type variables start with an underscore, to make them - // easy to recognize. + function LinkError() { + _classCallCheck(this, LinkError); - // 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. + return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); + } - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; + return LinkError; +}(Error); - 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; - }; +exports.LinkError = LinkError; - 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. +/***/ 66921: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - var keywords$1 = {}; +"use strict"; - // 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) +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "getSectionForNode", ({ + enumerable: true, + get: function get() { + return _section.getSectionForNode; } +})); +exports.default = void 0; - 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. +var _section = __webpack_require__(79348); - 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}), +var illegalop = "illegal"; +var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; +var moduleVersion = [0x01, 0x00, 0x00, 0x00]; - // 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}) +function invertMap(obj) { + var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { + return k; }; + var result = {}; + var keys = Object.keys(obj); - // 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)) + for (var i = 0, length = keys.length; i < length; i++) { + result[keyModifierFn(obj[keys[i]])] = keys[i]; } - 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. + return result; +} - function has(obj, propName) { - return hasOwnProperty.call(obj, propName) - } +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 + }; +} - var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" - ); }); +function createSymbol(name +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return { + name: name, + numberOfArgs: numberOfArgs + }; +} - function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") +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); } - // 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. + 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; - 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: +/***/ 79348: +/***/ (function(__unused_webpack_module, exports) { - 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 - }; +"use strict"; - // Interpret and default an options object - function getOptions(opts) { - var options = {}; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getSectionForNode = getSectionForNode; - for (var opt in defaultOptions) - { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } +function getSectionForNode(n) { + switch (n.type) { + case "ModuleImport": + return "import"; - if (options.ecmaVersion >= 2015) - { options.ecmaVersion -= 2009; } + case "CallInstruction": + case "CallIndirectInstruction": + case "Func": + case "Instr": + return "code"; - if (options.allowReserved == null) - { options.allowReserved = options.ecmaVersion < 5; } + case "ModuleExport": + return "export"; - 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); } + case "Start": + return "start"; - return options - } + case "TypeInstruction": + return "type"; - 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); - } - } + case "IndexInFuncSection": + return "func"; - // 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; + case "Global": + return "global"; + // No section - function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + default: + return; } +} - // 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); } +/***/ 57732: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); +"use strict"; - // 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 } }; +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; - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) - }; +var _ieee = __webpack_require__(30848); - 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()) }; +/** + * 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 + */ - // Switch to a getter for 7.0.0. - Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; +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; - Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; +function encodeF32(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); + return buffer; +} - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls - }; +function encodeF64(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); + return buffer; +} - Parser.parse = function parse (input, options) { - return new this(options, input).parse() - }; +function decodeF32(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); +} - Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() - }; +function decodeF64(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); +} - Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) - }; +/***/ }), - Object.defineProperties( Parser.prototype, prototypeAccessors ); +/***/ 62904: +/***/ (function(__unused_webpack_module, exports) { - var pp = Parser.prototype; +"use strict"; +// Copyright 2012 The Obvious Corporation. - // ## Parser utilities +/* + * 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]`. + */ - 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; +/* + * Modules used + */ - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - if (this.input[start] === ";") - { start++; } - } - }; +/* + * Exported bindings + */ - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. +/** + * 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`. + */ - pp.eat = function(type) { - if (this.type === type) { - this.next(); - return true - } else { - return false - } - }; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extract = extract; +exports.inject = inject; +exports.getSign = getSign; +exports.highOrder = highOrder; - // Tests whether parsed token is a contextual keyword. +function extract(buffer, bitIndex, bitLength, defaultBit) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } - pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc - }; + if (defaultBit === undefined) { + defaultBit = 0; + } else if (defaultBit !== 0 && defaultBit !== 1) { + throw new Error("Bad value for defaultBit."); + } - // Consumes contextual keyword if possible. + 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. - pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true - }; + var lastBit = bitIndex + bitLength; + var startByte = Math.floor(bitIndex / 8); + var startBit = bitIndex % 8; + var endByte = Math.floor(lastBit / 8); + var endBit = lastBit % 8; - // Asserts that following token is given contextual keyword. + 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; + } - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } - }; + while (endByte > startByte) { + endByte--; + result = result << 8 | get(endByte); + } - // Test whether a semicolon can be inserted at the current position. + result >>>= startBit; + return result; - pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; + 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. + */ - 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. +function inject(buffer, bitIndex, bitLength, value) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } - pp.semicolon = function() { - if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } - }; + var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); - 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 - } - }; + 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. - // 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(); - }; + var atByte = Math.floor(bitIndex / 8); + var atBit = bitIndex % 8; - // Raise an unexpected token error. + while (bitLength > 0) { + if (value & 1) { + buffer[atByte] |= 1 << atBit; + } else { + buffer[atByte] &= ~(1 << atBit); + } - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); - }; + value >>= 1; + bitLength--; + atBit = (atBit + 1) % 8; - function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; + if (atBit === 0) { + atByte++; + } } +} +/** + * Gets the sign bit of the given buffer. + */ - 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"); } - }; +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`. + */ - 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" - }; +function highOrder(bit, buffer) { + var length = buffer.length; + var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte - var pp$1 = Parser.prototype; + while (length > 0 && buffer[length - 1] === fullyWrongByte) { + length--; + } - // ### Statement parsing + if (length === 0) { + // Degenerate case. The buffer consists entirely of ~bit. + return -1; + } - // 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. + var byteToCheck = buffer[length - 1]; + var result = length * 8 - 1; - 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); + for (var i = 7; i > 0; i--) { + if ((byteToCheck >> i & 1) === bit) { + break; } - 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") - }; + result--; + } - var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + return result; +} - 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 - }; +/***/ 7276: +/***/ (function(__unused_webpack_module, exports) { - // 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 } +"use strict"; - 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. +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. - pp$1.parseStatement = function(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; +/* + * bufs: Buffer utilities. + */ - if (this.isLet(context)) { - starttype = types._var; - kind = "let"; - } +/* + * Module variables + */ - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. +/** Pool of buffers, where `bufPool[x].length === x`. */ +var bufPool = []; +/** Maximum length of kept temporary buffers. */ - 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()) } - } +var TEMP_BUF_MAXIMUM_LENGTH = 20; +/** Minimum exactly-representable 64-bit int. */ - 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) +var MIN_EXACT_INT64 = -0x8000000000000000; +/** Maximum exactly-representable 64-bit int. */ - // 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 MAX_EXACT_INT64 = 0x7ffffffffffffc00; +/** Maximum exactly-representable 64-bit uint. */ - 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) } - } - }; +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). + */ - 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(); - } +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). + */ - // 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") - }; +var BIT_64 = 0x10000000000000000; +/* + * Helper functions + */ - pp$1.parseDebuggerStatement = function(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement") - }; +/** + * Masks off all but the lowest bit set of the given number. + */ - 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") - }; +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. + */ - // 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) - }; +function isLossyToAdd(accum, num) { + if (num === 0) { + return false; + } - pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) - }; + var lowBit = lowestBit(num); + var added = accum + lowBit; - 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") - }; + if (added === accum) { + return true; + } - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - { this.raise(this.start, "'return' outside of function"); } - this.next(); + if (added - lowBit !== accum) { + return true; + } + + return false; +} +/* + * Exported functions + */ - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. +/** + * 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. + */ - 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); +function alloc(length) { + var result = bufPool[length]; - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. + if (result) { + bufPool[length] = undefined; + } else { + result = new Buffer(length); + } - 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") - }; + result.fill(0); + return result; +} +/** + * Releases a buffer back to the pool. + */ - 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. +function free(buffer) { + var length = buffer.length; - var empty = []; + 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). + */ - 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") - }; +function resize(buffer, length) { + if (length === buffer.length) { + return buffer; + } - 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") - }; + var newBuf = alloc(length); + buffer.copy(newBuf); + free(buffer); + return newBuf; +} +/** + * Reads an arbitrary signed int from a buffer. + */ - 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") - }; +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. - 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 (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 (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 } + if (isLossyToAdd(result, one)) { + lossy = true; + } + + result += one; } - 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") + return { + value: result, + lossy: lossy }; +} +/** + * Reads an arbitrary unsigned int from a buffer. + */ - // 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(); +function readUInt(buffer) { + var length = buffer.length; + var result = 0; + var lossy = false; // Note: See above in re bit manipulation. - 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 (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]; } - if (createNewLexicalScope) { this.exitScope(); } - return this.finishNode(node, "BlockStatement") - }; + } else { + for (var _i2 = length - 1; _i2 >= 0; _i2--) { + var one = buffer[_i2]; + result *= 0x100; - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. + if (isLossyToAdd(result, one)) { + lossy = true; + } - 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") + result += one; + } + } + + return { + value: result, + lossy: lossy }; +} +/** + * Writes a little-endian 64-bit signed int into a buffer. + */ - // 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(); +function writeInt64(value, buffer) { + if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) { + throw new Error("Value out of range."); + } - 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") - }; + if (value < 0) { + value += BIT_64; + } - // Parse a list of variable declarations. + writeUInt64(value, buffer); +} +/** + * Writes a little-endian 64-bit unsigned int into a buffer. + */ - 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); - }; +function writeUInt64(value, buffer) { + if (value < 0 || value > MAX_EXACT_UINT64) { + throw new Error("Value out of range."); + } - var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + var lowWord = value % BIT_32; + var highWord = Math.floor(value / BIT_32); + buffer.writeUInt32LE(lowWord, 0); + buffer.writeUInt32LE(highWord, 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; } +/***/ 89943: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - 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); } - } +"use strict"; - 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; } +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; - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false); +var _leb = _interopRequireDefault(__webpack_require__(80881)); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") - }; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - }; +/** + * 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) + */ - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). +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; - pp$1.parseClass = function(node, isStatement) { - this.next(); +function decodeInt64(encodedBuffer, index) { + return _leb.default.decodeInt64(encodedBuffer, index); +} - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; +function decodeUInt64(encodedBuffer, index) { + return _leb.default.decodeUInt64(encodedBuffer, index); +} - 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") - }; +function decodeInt32(encodedBuffer, index) { + return _leb.default.decodeInt32(encodedBuffer, index); +} - pp$1.parseClassElement = function(constructorAllowsSuper) { - var this$1 = this; +function decodeUInt32(encodedBuffer, index) { + return _leb.default.decodeUInt32(encodedBuffer, index); +} - if (this.eat(types.semi)) { return null } +function encodeU32(v) { + return _leb.default.encodeUInt32(v); +} - var method = this.startNode(); - var tryContextual = function (k, noLineBreak) { - if ( noLineBreak === void 0 ) noLineBreak = false; +function encodeI32(v) { + return _leb.default.encodeInt32(v); +} - 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 - }; +function encodeI64(v) { + return _leb.default.encodeInt64(v); +} - 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 - }; +/***/ }), + +/***/ 80881: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +// Copyright 2012 The Obvious Corporation. - pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - return this.finishNode(method, "MethodDefinition") - }; +/* + * leb: LEB128 utilities. + */ - 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; - } - }; +/* + * Modules used + */ - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; - }; - // Parses module export declaration. +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; - 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]; +var _long = _interopRequireDefault(__webpack_require__(77960)); - this.checkUnreserved(spec.local); - // check if export is defined - this.checkLocalExport(spec.local); - } +var bits = _interopRequireWildcard(__webpack_require__(62904)); - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") - }; +var bufs = _interopRequireWildcard(__webpack_require__(7276)); - pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has(exports, name)) - { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } - exports[name] = true; - }; +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; } } - 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]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - 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]; +/* + * Module variables + */ - 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); } - }; +/** The minimum possible 32-bit signed int. */ +var MIN_INT32 = -0x80000000; +/** The maximum possible 32-bit signed int. */ - pp$1.checkVariableExport = function(exports, decls) { - if (!exports) { return } - for (var i = 0, list = decls; i < list.length; i += 1) - { - var decl = list[i]; +var MAX_INT32 = 0x7fffffff; +/** The maximum possible 32-bit unsigned int. */ - this.checkPatternExport(exports, decl.id); - } - }; +var MAX_UINT32 = 0xffffffff; +/** The minimum possible 64-bit signed int. */ +// const MIN_INT64 = -0x8000000000000000; - 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() - }; +/** + * The maximum possible 64-bit signed int that is representable as a + * JavaScript number. + */ +// const MAX_INT64 = 0x7ffffffffffffc00; - // Parses a comma-separated list of module exports. +/** + * The maximum possible 64-bit unsigned int that is representable as a + * JavaScript number. + */ +// const MAX_UINT64 = 0xfffffffffffff800; - 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; } +/* + * Helper functions + */ - 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 - }; +/** + * 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. + */ - // Parses import declaration. +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. + */ - 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. +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. + */ - 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 - }; +function encodeBufferCommon(buffer, signed) { + var signBit; + var bitCount; - // 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] === "'") - ) - }; + if (signed) { + signBit = bits.getSign(buffer); + bitCount = signedBitCount(buffer); + } else { + signBit = 0; + bitCount = unsignedBitCount(buffer); + } - var pp$2 = Parser.prototype; + var byteCount = Math.ceil(bitCount / 7); + var result = bufs.alloc(byteCount); - // Convert existing expression atom to assignable pattern - // if possible. + 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. - 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 + result[byteCount - 1] &= 0x7f; + return result; +} +/** + * Gets the byte-length of the value encoded in the given buffer at + * the given index. + */ - 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 +function encodedLength(encodedBuffer, index) { + var result = 0; - 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 + while (encodedBuffer[index + result] >= 0x80) { + result++; + } - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break + result++; // to account for the last byte - 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 + if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives + // throw new Error("integer representation too long"); + } - 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 + return result; +} +/** + * Common decoder for both signed and unsigned ints. This takes an + * LEB128-encoded buffer, returning a bigint-ish buffer. + */ - case "AssignmentPattern": - break - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break +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; - case "MemberExpression": - if (!isBinding) { break } + while (length > 0) { + bits.inject(result, outIndex, 7, encodedBuffer[index]); + outIndex += 7; + index++; + length--; + } - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node - }; + var signBit; + var signByte; - // Convert list of expression atoms to binding list. + if (signed) { + // Sign-extend the last byte. + var lastByte = result[byteLength - 1]; + var endBit = outIndex % 8; - 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); } + 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; } - return exprList + + 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 + */ - // 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") +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 }; +} - pp$2.parseRestBinding = function() { - var node = this.startNode(); - this.next(); +function encodeUIntBuffer(buffer) { + return encodeBufferCommon(buffer, false); +} - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } +function decodeUIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, false); +} - node.argument = this.parseBindingAtom(); +function encodeUInt32(num) { + var buf = bufs.alloc(4); + buf.writeUInt32LE(num, 0); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} - return this.finishNode(node, "RestElement") +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 }; +} - // Parses lvalue (assignable) atom. +function encodeUInt64(num) { + var buf = bufs.alloc(8); + bufs.writeUInt64(num, buf); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} - 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") +function decodeUInt64(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); - case types.braceL: - return this.parseObj(true) - } - } - return this.parseIdent() - }; + var value = _long.default.fromBytesLE(result.value, true); - 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 + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false }; +} - pp$2.parseBindingListItem = function(param) { - return param - }; +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; - // 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") - }; +/***/ 19418: +/***/ (function(__unused_webpack_module, exports) { - // 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 +"use strict"; - 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 +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; - case "MemberExpression": - if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break +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); } } - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) - { - var prop = list[i]; +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } - this.checkLVal(prop, bindingType, checkClashes); - } - break +function con(b) { + if ((b & 0xc0) === 0x80) { + return b & 0x3f; + } else { + throw new Error("invalid UTF-8 encoding"); + } +} - case "Property": - // AssignmentProperty has type === "Property" - this.checkLVal(expr.value, bindingType, checkClashes); - break +function code(min, n) { + if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { + throw new Error("invalid UTF-8 encoding"); + } else { + return n; + } +} - 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]; +function decode(bytes) { + return _decode(bytes).map(function (x) { + return String.fromCharCode(x); + }).join(""); +} - if (elem) { this.checkLVal(elem, bindingType, checkClashes); } - } - break +function _decode(bytes) { + if (bytes.length === 0) { + return []; + } + /** + * 1 byte + */ - case "AssignmentPattern": - this.checkLVal(expr.left, bindingType, checkClashes); - break - case "RestElement": - this.checkLVal(expr.argument, bindingType, checkClashes); - break + { + var _bytes = _toArray(bytes), + b1 = _bytes[0], + bs = _bytes.slice(1); - case "ParenthesizedExpression": - this.checkLVal(expr.expression, bindingType, checkClashes); - break + if (b1 < 0x80) { + return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); + } - default: - this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); + if (b1 < 0xc0) { + throw new Error("invalid UTF-8 encoding"); } - }; + } + /** + * 2 bytes + */ - // A recursive descent parser operates by defining functions for all + { + var _bytes2 = _toArray(bytes), + _b = _bytes2[0], + b2 = _bytes2[1], + _bs = _bytes2.slice(2); - var pp$3 = Parser.prototype; + if (_b < 0xe0) { + return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); + } + } + /** + * 3 bytes + */ - // 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. + { + var _bytes3 = _toArray(bytes), + _b2 = _bytes3[0], + _b3 = _bytes3[1], + b3 = _bytes3[2], + _bs2 = _bytes3.slice(3); - 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 - }; + if (_b2 < 0xf0) { + return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); } - other[kind] = true; - }; + } + /** + * 4 bytes + */ - // ### Expression parsing + { + var _bytes4 = _toArray(bytes), + _b4 = _bytes4[0], + _b5 = _bytes4[1], + _b6 = _bytes4[2], + b4 = _bytes4[3], + _bs3 = _bytes4.slice(4); - // 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. + 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"); +} - // 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 - }; +/***/ 43882: +/***/ (function(__unused_webpack_module, exports) { - // Parse an assignment expression. This includes applications of - // operators like `+=`. +"use strict"; - 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; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encode = encode; - 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 - }; +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); } } - // Parse a ternary conditional (`?:`) operator. +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } - 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 - }; +function con(n) { + return 0x80 | n & 0x3f; +} - // Start the precedence parser. +function encode(str) { + var arr = str.split("").map(function (x) { + return x.charCodeAt(0); + }); + return _encode(arr); +} - 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) - }; +function _encode(arr) { + if (arr.length === 0) { + return []; + } - // 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. + var _arr = _toArray(arr), + n = _arr[0], + ns = _arr.slice(1); - 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 - }; + if (n < 0) { + throw new Error("utf8"); + } - 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") - }; + if (n < 0x80) { + return [n].concat(_toConsumableArray(_encode(ns))); + } - // Parse unary operators, both prefix and postfix. + if (n < 0x800) { + return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); + } - 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 (n < 0x10000) { + return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } - if (!sawUnary && this.eat(types.starstar)) - { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } - else - { return expr } - }; + if (n < 0x110000) { + return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } - // Parse call, dot, and `[]`-subscript expressions. + throw new Error("utf8"); +} - 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; - } - }; +/***/ 81637: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - 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"); - } +"use strict"; - 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 `{}`. +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; + } +})); - 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 _decoder = __webpack_require__(19418); - 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") +var _encoder = __webpack_require__(43882); - 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 +/***/ 28458: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node +"use strict"; - 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") +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; - 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 +var _helperApiError = __webpack_require__(20193); - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") +var ieee754 = _interopRequireWildcard(__webpack_require__(57732)); - case types.braceL: - return this.parseObj(false, refDestructuringErrors) +var utf8 = _interopRequireWildcard(__webpack_require__(81637)); - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) +var t = _interopRequireWildcard(__webpack_require__(81875)); - case types._class: - return this.parseClass(this.startNode(), false) +var _leb = __webpack_require__(89943); - case types._new: - return this.parseNew() +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(66921)); - case types.backQuote: - return this.parseTemplate() +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - case types._import: - if (this.options.ecmaVersion > 10) { - return this.parseDynamicImport() - } else { - return this.unexpected() - } +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; } } - default: - this.unexpected(); - } - }; +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); } } - pp$3.parseDynamicImport = function() { - var node = this.startNode(); - this.next(); - if (this.type !== types.parenL) { - this.unexpected(); - } - return this.finishNode(node, "Import") - }; +function toHex(n) { + return "0x" + Number(n).toString(16); +} - 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") - }; +function byteArrayEq(l, r) { + if (l.length !== r.length) { + return false; + } - pp$3.parseParenExpression = function() { - this.expect(types.parenL); - var val = this.parseExpression(); - this.expect(types.parenR); - return val - }; + for (var i = 0; i < l.length; i++) { + if (l[i] !== r[i]) { + return false; + } + } - 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(); + return true; +} - 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); +function decode(ab, opts) { + var buf = new Uint8Array(ab); + var getUniqueName = t.getUniqueNameGenerator(); + var offset = 0; - 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) - } + function getPosition() { + return { + line: -1, + column: offset + }; + } - 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; + function dump(b, msg) { + if (opts.dump === false) return; + var pad = "\t\t\t\t\t\t\t\t\t\t"; + var str = ""; - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc); - val.expressions = exprList; - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); - } else { - val = exprList[0]; - } + if (b.length < 5) { + str = b.map(toHex).join(" "); } else { - val = this.parseParenExpression(); + str = "..."; } - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc); - par.expression = val; - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } - }; + console.log(toHex(offset) + ":\t", str, pad, ";", msg); + } - pp$3.parseParenItem = function(item) { - return item - }; + 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 + */ - 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 state = { + elementsInFuncSection: [], + elementsInExportSection: [], + elementsInCodeSection: [], - var empty$1 = []; + /** + * Decode memory from: + * - Memory section + */ + memoriesInModule: [], - 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") - }; + /** + * Decoded types from: + * - Type section + */ + typesInModule: [], - // Parse template expression. + /** + * Decoded functions from: + * - Function section + * - Import section + */ + functionsInModule: [], - pp$3.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; + /** + * Decoded tables from: + * - Table section + */ + tablesInModule: [], - 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") + /** + * Decoded globals from: + * - Global section + */ + globalsInModule: [] }; - pp$3.parseTemplate = function(ref) { - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + function isEOF() { + return offset >= buf.length; + } - 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})); + function eatBytes(n) { + offset = offset + n; + } + + function readBytesAtOffset(_offset, numberOfBytes) { + var arr = []; + + for (var i = 0; i < numberOfBytes; i++) { + arr.push(buf[_offset + i]); } - 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)) - }; + return arr; + } - // Parse an object literal or binding pattern. + function readBytes(numberOfBytes) { + return readBytesAtOffset(offset, numberOfBytes); + } - 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; } + function readF64() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64); + var value = ieee754.decodeF64(bytes); - var prop = this.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; } - 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 (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); } - 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; + + mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; } - 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(); } + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } - 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(); } - }; + function readF32() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32); + var value = ieee754.decodeF32(bytes); - 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; - } + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; } - return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") - }; - // Initialize empty function node. + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; - 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; } - }; + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } - // Parse object or class method. + mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } - pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } + 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. - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + 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. + */ - 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") - }; + function readU32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } - // Parse arrow function expression with given parameters. + function readVaruint32() { + // where 32 bits = max 4 bytes + var bytes = readBytes(4); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); + } - pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + 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 + */ - 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; + 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 + */ - 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") - }; + function read64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt64)(buffer); + } - // Parse function body and check parameters. + function readU64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt64)(buffer); + } - pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; + function readByte() { + return readBytes(1)[0]; + } - 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; } + function parseModuleHeader() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } - // 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; + var header = readBytes(4); + + if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { + throw new _helperApiError.CompileError("magic header not detected"); } - 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; - }; + dump(header, "wasm magic header"); + eatBytes(4); + } - pp$3.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; + function parseVersion() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } - if (param.type !== "Identifier") { return false - } } - return true - }; + var version = readBytes(4); - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. + if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) { + throw new _helperApiError.CompileError("unknown binary version"); + } - pp$3.checkParams = function(node, allowDuplicates) { - var nameHash = {}; - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; + dump(version, "wasm version"); + eatBytes(4); + } - this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); + function parseVec(cast) { + var u32 = readU32(); + var length = u32.value; + eatBytes(u32.nextIndex); + dump([length], "number"); + + if (length === 0) { + return []; } - }; - // 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). + var elements = []; - 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; } + for (var i = 0; i < length; i++) { + var byte = readByte(); + eatBytes(1); + var value = cast(byte); + dump([byte], value); - 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); + if (typeof value === "undefined") { + throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value"); } - elts.push(elt); + + elements.push(value); } - return elts - }; - pp$3.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; + return elements; + } // Type section + // https://webassembly.github.io/spec/binary/modules.html#binary-typesec - 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. + function parseTypeSection(numberOfTypes) { + var typeInstructionNodes = []; + dump([numberOfTypes], "num types"); - 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; + for (var i = 0; i < numberOfTypes; i++) { + var _startLoc = getPosition(); - // 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(); + 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)); } - } 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. + return typeInstructionNodes; + } // Import section + // https://webassembly.github.io/spec/binary/modules.html#binary-importsec - 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") - }; + function parseImportSection(numberOfImports) { + var imports = []; - pp$3.parseAwait = function() { - if (!this.awaitPos) { this.awaitPos = this.start; } + for (var i = 0; i < numberOfImports; i++) { + dumpSep("import header " + i); - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeUnary(null, true); - return this.finishNode(node, "AwaitExpression") - }; + var _startLoc2 = getPosition(); + /** + * Module name + */ - 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. + var moduleName = readUTF8String(); + eatBytes(moduleName.nextIndex); + dump([], "module name (".concat(moduleName.value, ")")); + /** + * Name + */ - 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 - }; + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "name (".concat(name.value, ")")); + /** + * Import descr + */ - pp$4.raiseRecoverable = pp$4.raise; + var descrTypeByte = readByte(); + eatBytes(1); + var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte]; + dump([descrTypeByte], "import kind"); - pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - }; + if (typeof descrType === "undefined") { + throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte)); + } - var pp$5 = Parser.prototype; + var importDescr = void 0; - 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 = []; - }; + if (descrType === "func") { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; - // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + 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); + }()); + } - pp$5.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); - }; + return imports; + } // Function section + // https://webassembly.github.io/spec/binary/modules.html#function-section - 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) - }; + function parseFuncSection(numberOfFunctions) { + dump([numberOfFunctions], "num funcs"); - 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")); } - }; + 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]; - 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; - } - }; + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } // preserve anonymous, a name might be resolved later - 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 } + 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 - // 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]; } - }; + function parseExportSection(numberOfExport) { + dump([numberOfExport], "num exports"); // Parse vector of exports - // Start an AST node, attaching a start offset. + for (var i = 0; i < numberOfExport; i++) { + var _startLoc3 = getPosition(); + /** + * Name + */ - var pp$6 = Parser.prototype; - pp$6.startNode = function() { - return new Node(this, this.start, this.startLoc) - }; + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "export name (".concat(name.value, ")")); + /** + * exportdescr + */ - pp$6.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - }; + 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; - // Finish an AST node, adding `type` and `end` properties. + if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") { + var func = state.functionsInModule[index]; - 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 - } + if (typeof func === "undefined") { + throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); + } - pp$6.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - }; + id = t.numberLiteralFromRaw(index, String(index)); + signature = func.signature; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { + var table = state.tablesInModule[index]; - // Finish node at given position + if (typeof table === "undefined") { + throw new _helperApiError.CompileError("unknown table ".concat(index)); + } - pp$6.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - }; + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { + var memNode = state.memoriesInModule[index]; - // The algorithm used to determine whether a regexp can appear at a + if (typeof memNode === "undefined") { + throw new _helperApiError.CompileError("unknown memory ".concat(index)); + } - var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; - }; + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { + var global = state.globalsInModule[index]; - 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) - }; + if (typeof global === "undefined") { + throw new _helperApiError.CompileError("unknown global ".concat(index)); + } - var pp$7 = Parser.prototype; + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else { + console.warn("Unsupported export type: " + toHex(typeIndex)); + return; + } - pp$7.initialContext = function() { - return [types$1.b_stat] - }; + 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 - 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 - }; + function parseCodeSection(numberOfFuncs) { + dump([numberOfFuncs], "number functions"); // Parse vector of function - 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 - }; + for (var i = 0; i < numberOfFuncs; i++) { + var _startLoc4 = getPosition(); - 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; } - }; + dumpSep("function body " + i); // the u32 size of the function code in bytes + // Ignore it for now - // Token-specific context update code + var bodySizeU32 = readU32(); + eatBytes(bodySizeU32.nextIndex); + dump([bodySizeU32.value], "function body size"); + var code = []; + /** + * Parse locals + */ - 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; - }; + var funcLocalNumU32 = readU32(); + var funcLocalNum = funcLocalNumU32.value; + eatBytes(funcLocalNumU32.nextIndex); + dump([funcLocalNum], "num locals"); + var locals = []; - types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; - }; + for (var _i = 0; _i < funcLocalNum; _i++) { + var _startLoc5 = getPosition(); - types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; - }; + 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 = []; - 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; - }; + for (var _i2 = 0; _i2 < localCount; _i2++) { + args.push(t.valtypeLiteral(type)); + } - types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - }; + var localNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); + }(); - 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; - }; + locals.push(localNode); + dump([valtypeByte], type); - 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; - }; + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); + } + } - 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; - }; + code.push.apply(code, locals); // Decode instructions until the end - 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; } + parseInstructionBlock(code); + var endLoc = getPosition(); + state.elementsInCodeSection.push({ + code: code, + locals: locals, + endLoc: endLoc, + startLoc: _startLoc4, + bodySize: bodySizeU32.value + }); } - 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) + function parseInstructionBlock(code) { + while (true) { + var _startLoc6 = getPosition(); - // #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 - }; + var instructionAlreadyCreated = false; + var instructionByte = readByte(); + eatBytes(1); - // #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"; + if (instructionByte === 0xfe) { + throw new _helperApiError.CompileError("Atomic instructions are not implemented"); + } - // #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 instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; - var data = {}; - function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + if (typeof instruction === "undefined") { + throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); } - }; - 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); + if (typeof instruction.object === "string") { + dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); + } else { + dump([instructionByte], instruction.name); + } + /** + * End of the function + */ - 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 = []; - }; + if (instruction.name === "end") { + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); + }(); - 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; - }; + code.push(node); + break; + } - RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); - }; + var args = []; - // 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 - }; + if (instruction.name === "loop") { + var _startLoc7 = getPosition(); - 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 - }; + var blocktypeByte = readByte(); + eatBytes(1); + var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte]; + dump([blocktypeByte], "blocktype"); - RegExpValidationState.prototype.current = function current () { - return this.at(this.pos) - }; + 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")), ""); - RegExpValidationState.prototype.lookahead = function lookahead () { - return this.at(this.nextIndex(this.pos)) - }; + var loopNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); + }(); - RegExpValidationState.prototype.advance = function advance () { - this.pos = this.nextIndex(this.pos); - }; + code.push(loopNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "if") { + var _startLoc8 = getPosition(); - RegExpValidationState.prototype.eat = function eat (ch) { - if (this.current() === ch) { - this.advance(); - return true - } - return false - }; + var _blocktypeByte = readByte(); - function codePointToString(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) - } + eatBytes(1); + var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; + dump([_blocktypeByte], "blocktype"); - /** - * 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; + if (typeof _blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); + } - 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"); - } - } - }; + var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); + var ifBody = []; + parseInstructionBlock(ifBody); // Defaults to no alternate - /** - * 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); + var elseIndex = 0; - // 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); - } - }; + for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { + var _instr = ifBody[elseIndex]; - // 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; + if (_instr.type === "Instr" && _instr.id === "else") { + break; + } + } - this.regexp_disjunction(state); + var consequentInstr = ifBody.slice(0, elseIndex); + var alternate = ifBody.slice(elseIndex + 1); // wast sugar - 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]; + var testInstrs = []; - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } - } - }; + var ifNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); + }(); - // 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); - } + code.push(ifNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "block") { + var _startLoc9 = getPosition(); - // 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"); - } - }; + var _blocktypeByte2 = readByte(); - // 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)) - { } - }; + eatBytes(1); + var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; + dump([_blocktypeByte2], "blocktype"); - // 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"); + if (typeof _blocktype2 === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); } - } - return true - } - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } + var _instr2 = []; + parseInstructionBlock(_instr2); // preserve anonymous - return false - }; + var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); - // 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; + var blockNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); + }(); - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } + code.push(blockNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call") { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } + var callNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6); + }(); - // 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"); + 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, ")")); } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } - state.pos = start; - return false - }; + var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []); - // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier - pp$8.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; + var flagU32 = readU32(); + var flag = flagU32.value; // 0x00 - reserved byte - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false - }; + eatBytes(flagU32.nextIndex); - // 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 (flag !== 0) { + throw new _helperApiError.CompileError("zero flag expected"); } - 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"); + + 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"); } - return true + + 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 (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 + if (instruction.object === "u32") { + var valueu32 = readU32(); + var _value = valueu32.value; + eatBytes(valueu32.nextIndex); + dump([_value], "u32 value"); + args.push(t.numberLiteralFromRaw(_value)); } - 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) - ) - }; + 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); + } - // 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 - }; + 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); + } - // 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 /* } */ - ) - } + 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))); + } - // 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 - }; + 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)); + } + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter - pp$8.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false - }; + if (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); + }(); - // 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"); + code.push(_node3); + } else { + var _node4 = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); + }(); + + code.push(_node4); } - state.groupNames.push(state.lastStringValue); - return } - state.raise("Invalid group"); } - }; + } // https://webassembly.github.io/spec/core/binary/types.html#limits - // 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 + + 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"); } - state.raise("Invalid capture group name"); + + if (limitType === 0x00) { + var _u32min = readU32(); + + min = parseInt(_u32min.value); + eatBytes(_u32min.nextIndex); + dump([min], "min"); } - 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 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)); } - return false - }; - // RegExpIdentifierStart[U] :: - // UnicodeIDStart - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[?U] - pp$8.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var ch = state.current(); - state.advance(); + var limits = parseLimits(); + return t.table(elementType, limits, name); + } // https://webassembly.github.io/spec/binary/types.html#global-types - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { - ch = state.lastIntValue; + + 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)); } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true + + 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)); } - state.pos = start; - return false - }; - function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ - } + 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 - // 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 + 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)); } - state.pos = start; - return false - }; - function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + return functionNames; } - // 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 + 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)); } - 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 + + 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); + } } - 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 + 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)); } - 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 + metadata.producers.push(fields[fieldName.value]); } - 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 */) - ) + return metadata; } - // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence - pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state) { - var start = state.pos; + function parseGlobalSection(numberOfGlobals) { + var globals = []; + dump([numberOfGlobals], "num globals"); - 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; + 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 false - }; - function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF + return globals; } - // 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 + 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)); } - return false + + var elemNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); + }(); + + elems.push(elemNode); } - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true + 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 false - }; + return tables; + } // https://webassembly.github.io/spec/binary/modules.html#memory-section - // 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(); + function parseMemorySection(numberOfElements) { + var memories = []; + dump([numberOfElements], "num elements"); - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true + for (var i = 0; i < numberOfElements; i++) { + var memoryNode = parseMemoryType(i); + state.memoriesInModule.push(memoryNode); + memories.push(memoryNode); } - 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 memories; + } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec - 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; + 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 - // 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 + + 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"); } - } - state.pos = start; - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true + var bytes = parseVec(function (b) { + return b; + }); + dump([], "init"); + dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); } - 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 /* _ */ - } + return dataEntries; + } // https://webassembly.github.io/spec/binary/modules.html#binary-section - // 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) - }; + function parseSection(sectionIndex) { + var sectionId = readByte(); + eatBytes(1); - // 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"); + 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)); } - 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"); - } - } - } - }; + var nextSectionIndex = sectionIndex; + var startOffset = offset; + var startLoc = getPosition(); + var u32 = readU32(); + var sectionSizeInBytes = u32.value; + eatBytes(u32.nextIndex); - // 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; + var sectionSizeInBytesNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); + }(); - 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"); + 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 + }; } - state.raise("Invalid escape"); - } - state.pos = start; - } - var ch = state.current(); - if (ch !== 0x5D /* [ */) { - state.lastIntValue = ch; - state.advance(); - return true - } + case _helperWasmBytecode.default.sections.table: + { + dumpSep("section Table"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - return false - }; + var _startLoc14 = getPosition(); - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape - pp$8.regexp_eatClassEscape = function(state) { - var start = state.pos; + var _u2 = readU32(); - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } + var numberOfTable = _u2.value; + eatBytes(_u2.nextIndex); + dump([numberOfTable], "num tables"); - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } + var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); + }()); - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } + var _nodes2 = parseTableSection(numberOfTable); - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) - }; + return { + nodes: _nodes2, + metadata: _metadata2, + nextSectionIndex: nextSectionIndex + }; + } - // 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 - }; + case _helperWasmBytecode.default.sections.import: + { + dumpSep("section Import"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - // 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 - }; + var _startLoc15 = getPosition(); - // 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 */ - } + var numberOfImportsu32 = readU32(); + var numberOfImports = numberOfImportsu32.value; + eatBytes(numberOfImportsu32.nextIndex); + dump([numberOfImports], "number of imports"); - // 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 */ - } + var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); + }()); - // 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; + var _nodes3 = parseImportSection(numberOfImports); + + return { + nodes: _nodes3, + metadata: _metadata3, + nextSectionIndex: nextSectionIndex + }; } - } 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 */ - } + case _helperWasmBytecode.default.sections.func: + { + dumpSep("section Function"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - // 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 - }; + var _startLoc16 = getPosition(); - // 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 numberOfFunctionsu32 = readU32(); + var numberOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); - 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]; } - }; + var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); + }()); - // ## Tokenizer + parseFuncSection(numberOfFunctions); + var _nodes4 = []; + return { + nodes: _nodes4, + metadata: _metadata4, + nextSectionIndex: nextSectionIndex + }; + } - var pp$9 = Parser.prototype; + 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"); - // Move to the next token + var _startLoc18 = getPosition(); - pp$9.next = function() { - if (this.options.onToken) - { this.options.onToken(new Token(this)); } + var _u4 = readU32(); - this.lastTokEnd = this.end; - this.lastTokStart = this.start; - this.lastTokEndLoc = this.endLoc; - this.lastTokStartLoc = this.startLoc; - this.nextToken(); - }; + var numberOfFuncs = _u4.value; + eatBytes(_u4.nextIndex); - pp$9.getToken = function() { - this.next(); - return new Token(this) - }; + var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); + }()); - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - { pp$9[Symbol.iterator] = function() { - var this$1 = this; + if (opts.ignoreCodeSection === true) { + var remainingBytes = sectionSizeInBytes - _u4.nextIndex; + eatBytes(remainingBytes); // eat the entire section + } else { + parseCodeSection(numberOfFuncs); + } - return { - next: function () { - var token = this$1.getToken(); + var _nodes6 = []; return { - done: token.type === types.eof, - value: token - } + nodes: _nodes6, + metadata: _metadata6, + nextSectionIndex: nextSectionIndex + }; } - } - }; } - - // 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) } + case _helperWasmBytecode.default.sections.start: + { + dumpSep("section Start"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } - }; + var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); - 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() } + var _nodes7 = [parseStartSection()]; + return { + nodes: _nodes7, + metadata: _metadata7, + nextSectionIndex: nextSectionIndex + }; + } - return this.getTokenFromCode(code) - }; + case _helperWasmBytecode.default.sections.element: + { + dumpSep("section Element"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - 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 - }; + var _startLoc19 = getPosition(); - 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()); } - }; + var numberOfElementsu32 = readU32(); + var numberOfElements = numberOfElementsu32.value; + eatBytes(numberOfElementsu32.nextIndex); - 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()); } - }; + var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); + }()); - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. + var _nodes8 = parseElemSection(numberOfElements); - 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 + return { + nodes: _nodes8, + metadata: _metadata8, + nextSectionIndex: nextSectionIndex + }; } - } - } - }; - // 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. + case _helperWasmBytecode.default.sections.global: + { + dumpSep("section Global"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - 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; + var _startLoc20 = getPosition(); - this.updateContext(prevType); - }; + var numberOfGlobalsu32 = readU32(); + var numberOfGlobals = numberOfGlobalsu32.value; + eatBytes(numberOfGlobalsu32.nextIndex); - // ### Token reading + var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); + }()); - // 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) - } - }; + var _nodes9 = parseGlobalSection(numberOfGlobals); - 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) - }; + return { + nodes: _nodes9, + metadata: _metadata9, + nextSectionIndex: nextSectionIndex + }; + } - 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; + case _helperWasmBytecode.default.sections.memory: + { + dumpSep("section Memory"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } + var _startLoc21 = getPosition(); - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) - }; + var _numberOfElementsu = readU32(); - 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) - }; + var _numberOfElements = _numberOfElementsu.value; + eatBytes(_numberOfElementsu.nextIndex); - 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) - }; + var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); + }()); - 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) - }; + var _nodes10 = parseMemorySection(_numberOfElements); - 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) { - // `` 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) + }; - FunctionDeclaration(node) { - this.visitFunction(node); + 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) } - - FunctionExpression(node) { - this.visitFunction(node); + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `