diff --git a/assets/json-schema-faker-bundle.js b/assets/json-schema-faker-bundle.js new file mode 100644 index 000000000..406eeef4d --- /dev/null +++ b/assets/json-schema-faker-bundle.js @@ -0,0 +1,11746 @@ +/*! + * JSON Schema $Ref Parser v6.1.0 (February 21st 2019) + * + * https://apidevtools.org/json-schema-ref-parser/ + * + * @author James Messinger (https://jamesmessinger.com) + * @license MIT + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.$RefParser=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i0?u:s;plugins.sort(i),plugins.run(i,"parse",r).then(function(n){!n.plugin.allowEmpty&&isEmpty(n.result)?t(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty',r.url,n.plugin.name)):e(n)},function(n){n?(n=n instanceof Error?n:new Error(n),t(ono.syntax(n,"Error parsing %s",r.url))):t(ono.syntax("Unable to parse %s",r.url))})})}function isEmpty(r){return void 0===r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.trim().length||Buffer.isBuffer(r)&&0===r.length}module.exports=parse}).call(this,{isBuffer:require("../node_modules/is-buffer/index.js")})},{"../node_modules/is-buffer/index.js":32,"./util/plugins":17,"./util/url":18,ono:64}],7:[function(require,module,exports){(function(Buffer){"use strict";var BINARY_REGEXP=/\.(jpeg|jpg|gif|png|bmp|ico)$/i;module.exports={order:400,allowEmpty:!0,canParse:function(r){return Buffer.isBuffer(r.data)&&BINARY_REGEXP.test(r.url)},parse:function(r){return Buffer.isBuffer(r.data)?r.data:new Buffer(r.data)}}}).call(this,require("buffer").Buffer)},{buffer:23}],8:[function(require,module,exports){(function(Buffer){"use strict";module.exports={order:100,allowEmpty:!0,canParse:".json",parse:function(r){return new Promise(function(e,t){var n=r.data;Buffer.isBuffer(n)&&(n=n.toString()),"string"==typeof n?0===n.trim().length?e(void 0):e(JSON.parse(n)):e(n)})}}}).call(this,{isBuffer:require("../../node_modules/is-buffer/index.js")})},{"../../node_modules/is-buffer/index.js":32}],9:[function(require,module,exports){(function(Buffer){"use strict";var TEXT_REGEXP=/\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i;module.exports={order:300,allowEmpty:!0,encoding:"utf8",canParse:function(t){return("string"==typeof t.data||Buffer.isBuffer(t.data))&&TEXT_REGEXP.test(t.url)},parse:function(t){if("string"==typeof t.data)return t.data;if(Buffer.isBuffer(t.data))return t.data.toString(this.encoding);throw new Error("data is not text")}}}).call(this,{isBuffer:require("../../node_modules/is-buffer/index.js")})},{"../../node_modules/is-buffer/index.js":32}],10:[function(require,module,exports){(function(Buffer){"use strict";var YAML=require("../util/yaml");module.exports={order:200,allowEmpty:!0,canParse:[".yaml",".yml",".json"],parse:function(r){return new Promise(function(e,t){var a=r.data;Buffer.isBuffer(a)&&(a=a.toString()),e("string"==typeof a?YAML.parse(a):a)})}}}).call(this,{isBuffer:require("../../node_modules/is-buffer/index.js")})},{"../../node_modules/is-buffer/index.js":32,"../util/yaml":19}],11:[function(require,module,exports){"use strict";module.exports=Pointer;var $Ref=require("./ref"),url=require("./util/url"),ono=require("ono"),slashes=/\//g,tildes=/~/g,escapedSlash=/~1/g,escapedTilde=/~0/g;function Pointer(e,r,t){this.$ref=e,this.path=r,this.originalPath=t||r,this.value=void 0,this.circular=!1,this.indirections=0}function resolveIf$Ref(e,r){if($Ref.isAllowed$Ref(e.value,r)){var t=url.resolve(e.path,e.value.$ref);if(t!==e.path){var i=e.$ref.$refs._resolve(t,r);return e.indirections+=i.indirections+1,$Ref.isExtended$Ref(e.value)?(e.value=$Ref.dereference(e.value,i.value),!1):(e.$ref=i.$ref,e.path=i.path,e.value=i.value,!0)}e.circular=!0}}function setValue(e,r,t){if(!e.value||"object"!=typeof e.value)throw ono.syntax('Error assigning $ref pointer "%s". \nCannot set "%s" of a non-object.',e.path,r);return"-"===r&&Array.isArray(e.value)?e.value.push(t):e.value[r]=t,t}Pointer.prototype.resolve=function(e,r){var t=Pointer.parse(this.path);this.value=e;for(var i=0;i0},$Ref.isExternal$Ref=function(e){return $Ref.is$Ref(e)&&"#"!==e.$ref[0]},$Ref.isAllowed$Ref=function(e,t){if($Ref.is$Ref(e)){if("#/"===e.$ref.substr(0,2)||"#"===e.$ref)return!0;if("#"!==e.$ref[0]&&(!t||t.resolve.external))return!0}},$Ref.isExtended$Ref=function(e){return $Ref.is$Ref(e)&&Object.keys(e).length>1},$Ref.dereference=function(e,t){if(t&&"object"==typeof t&&$Ref.isExtended$Ref(e)){var r={};return Object.keys(e).forEach(function(t){"$ref"!==t&&(r[t]=e[t])}),Object.keys(t).forEach(function(e){e in r||(r[e]=t[e])}),r}return t}},{"./pointer":11}],13:[function(require,module,exports){"use strict";var ono=require("ono"),$Ref=require("./ref"),url=require("./util/url");function $Refs(){this.circular=!1,this._$refs={},this._root$Ref=null}function getPaths(e,r){var t=Object.keys(e);return(r=Array.isArray(r[0])?r[0]:Array.prototype.slice.call(r)).length>0&&r[0]&&(t=t.filter(function(t){return-1!==r.indexOf(e[t].pathType)})),t.map(function(r){return{encoded:r,decoded:"file"===e[r].pathType?url.toFileSystemPath(r,!0):r}})}module.exports=$Refs,$Refs.prototype.paths=function(e){return getPaths(this._$refs,arguments).map(function(e){return e.decoded})},$Refs.prototype.values=function(e){var r=this._$refs;return getPaths(r,arguments).reduce(function(e,t){return e[t.decoded]=r[t.encoded].value,e},{})},$Refs.prototype.toJSON=$Refs.prototype.values,$Refs.prototype.exists=function(e,r){try{return this._resolve(e,r),!0}catch(e){return!1}},$Refs.prototype.get=function(e,r){return this._resolve(e,r).value},$Refs.prototype.set=function(e,r){var t=url.resolve(this._root$Ref.path,e),o=url.stripHash(t),s=this._$refs[o];if(!s)throw ono('Error resolving $ref pointer "%s". \n"%s" not found.',e,o);s.set(t,r)},$Refs.prototype._add=function(e){var r=url.stripHash(e),t=new $Ref;return t.path=r,t.$refs=this,this._$refs[r]=t,this._root$Ref=this._root$Ref||t,t},$Refs.prototype._resolve=function(e,r){var t=url.resolve(this._root$Ref.path,e),o=url.stripHash(t),s=this._$refs[o];if(!s)throw ono('Error resolving $ref pointer "%s". \n"%s" not found.',e,o);return s.resolve(t,r,e)},$Refs.prototype._get$Ref=function(e){e=url.resolve(this._root$Ref.path,e);var r=url.stripHash(e);return this._$refs[r]}},{"./ref":12,"./util/url":18,ono:64}],14:[function(require,module,exports){"use strict";var $Ref=require("./ref"),Pointer=require("./pointer"),parse=require("./parse"),url=require("./util/url");function resolveExternal(e,r){if(!r.resolve.external)return Promise.resolve();try{var t=crawl(e.schema,e.$refs._root$Ref.path+"#",e.$refs,r);return Promise.all(t)}catch(e){return Promise.reject(e)}}function crawl(e,r,t,o){var s=[];return e&&"object"==typeof e&&($Ref.isExternal$Ref(e)?s.push(resolve$Ref(e,r,t,o)):Object.keys(e).forEach(function(l){var a=Pointer.join(r,l),n=e[l];$Ref.isExternal$Ref(n)?s.push(resolve$Ref(n,a,t,o)):s=s.concat(crawl(n,a,t,o))})),s}function resolve$Ref(e,r,t,o){var s=url.resolve(r,e.$ref),l=url.stripHash(s);return(e=t._$refs[l])?Promise.resolve(e.value):parse(s,t,o).then(function(e){var r=crawl(e,l+"#",t,o);return Promise.all(r)})}module.exports=resolveExternal},{"./parse":6,"./pointer":11,"./ref":12,"./util/url":18}],15:[function(require,module,exports){"use strict";var fs=require("fs"),ono=require("ono"),url=require("../util/url");module.exports={order:100,canRead:function(r){return url.isFileSystemPath(r.url)},read:function(r){return new Promise(function(e,o){var n;try{n=url.toFileSystemPath(r.url)}catch(e){o(ono.uri(e,"Malformed URI: %s",r.url))}try{fs.readFile(n,function(r,u){r?o(ono(r,'Error opening file "%s"',n)):e(u)})}catch(r){o(ono(r,'Error opening file "%s"',n))}})}}},{"../util/url":18,fs:21,ono:64}],16:[function(require,module,exports){(function(process,Buffer){"use strict";var http=require("http"),https=require("https"),ono=require("ono"),url=require("../util/url");function download(t,o,e){return new Promise(function(r,n){t=url.parse(t),(e=e||[]).push(t.href),get(t,o).then(function(s){if(s.statusCode>=400)throw ono({status:s.statusCode},"HTTP ERROR %d",s.statusCode);if(s.statusCode>=300)if(e.length>o.redirects)n(ono({status:s.statusCode},"Error downloading %s. \nToo many redirects: \n %s",e[0],e.join(" \n ")));else{if(!s.headers.location)throw ono({status:s.statusCode},"HTTP %d redirect with no location header",s.statusCode);download(url.resolve(t,s.headers.location),o,e).then(r,n)}else r(s.body||new Buffer(0))}).catch(function(o){n(ono(o,"Error downloading",t.href))})})}function get(t,o){return new Promise(function(e,r){var n=("https:"===t.protocol?https:http).get({hostname:t.hostname,port:t.port,path:t.path,auth:t.auth,protocol:t.protocol,headers:o.headers||{},withCredentials:o.withCredentials});"function"==typeof n.setTimeout&&n.setTimeout(o.timeout),n.on("timeout",function(){n.abort()}),n.on("error",r),n.once("response",function(t){t.body=new Buffer(0),t.on("data",function(o){t.body=Buffer.concat([t.body,new Buffer(o)])}),t.on("error",r),t.on("end",function(){e(t)})})})}module.exports={order:200,headers:null,timeout:5e3,redirects:5,withCredentials:!1,canRead:function(t){return url.isHttp(t.url)},read:function(t){var o=url.parse(t.url);return process.browser&&!o.protocol&&(o.protocol=url.parse(location.href).protocol),download(o,this)}}}).call(this,require("_process"),require("buffer").Buffer)},{"../util/url":18,_process:66,buffer:23,http:80,https:29,ono:64}],17:[function(require,module,exports){"use strict";function getResult(t,n,r,e){var u=t[n];if("function"==typeof u)return u.apply(t,[r,e]);if(!e){if(u instanceof RegExp)return u.test(r.url);if("string"==typeof u)return u===r.extension;if(Array.isArray(u))return-1!==u.indexOf(r.extension)}return u}exports.all=function(t){return Object.keys(t).filter(function(n){return"object"==typeof t[n]}).map(function(n){return t[n].name=n,t[n]})},exports.filter=function(t,n,r){return t.filter(function(t){return!!getResult(t,n,r)})},exports.sort=function(t){return t.forEach(function(t){t.order=t.order||Number.MAX_SAFE_INTEGER}),t.sort(function(t,n){return t.order-n.order})},exports.run=function(t,n,r){var e,u,o=0;return new Promise(function(i,f){function c(){if(!(e=t[o++]))return f(u);try{var i=getResult(e,n,r,s);i&&"function"==typeof i.then?i.then(p,a):void 0!==i&&p(i)}catch(t){a(t)}}function s(t,n){t?a(t):p(n)}function p(t){i({plugin:e,result:t})}function a(t){u=t,c()}c()})}},{}],18:[function(require,module,exports){(function(process){"use strict";var isWindows=/^win/.test(process.platform),forwardSlashPattern=/\//g,protocolPattern=/^(\w{2,}):\/\//i,url=module.exports,urlEncodePatterns=[/\?/g,"%3F",/\#/g,"%23"],urlDecodePatterns=[/\%23/g,"#",/\%24/g,"$",/\%26/g,"&",/\%2C/g,",",/\%40/g,"@"];exports.parse=require("url").parse,exports.resolve=require("url").resolve,exports.cwd=function(){return process.browser?location.href:process.cwd()+"/"},exports.getProtocol=function(r){var e=protocolPattern.exec(r);if(e)return e[1].toLowerCase()},exports.getExtension=function(r){var e=r.lastIndexOf(".");return e>=0?r.substr(e).toLowerCase():""},exports.getHash=function(r){var e=r.indexOf("#");return e>=0?r.substr(e):"#"},exports.stripHash=function(r){var e=r.indexOf("#");return e>=0&&(r=r.substr(0,e)),r},exports.isHttp=function(r){var e=url.getProtocol(r);return"http"===e||"https"===e||void 0===e&&process.browser},exports.isFileSystemPath=function(r){if(process.browser)return!1;var e=url.getProtocol(r);return void 0===e||"file"===e},exports.fromFileSystemPath=function(r){isWindows&&(r=r.replace(/\\/g,"/")),r=encodeURI(r);for(var e=0;e0)throw new Error("Invalid string. Length must be a multiple of 4");var e=o.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function byteLength(o){var r=getLens(o),e=r[0],t=r[1];return 3*(e+t)/4-t}function _byteLength(o,r,e){return 3*(r+e)/4-e}function toByteArray(o){for(var r,e=getLens(o),t=e[0],n=e[1],u=new Arr(_byteLength(o,t,n)),p=0,a=n>0?t-4:t,h=0;h>16&255,u[p++]=r>>8&255,u[p++]=255&r;return 2===n&&(r=revLookup[o.charCodeAt(h)]<<2|revLookup[o.charCodeAt(h+1)]>>4,u[p++]=255&r),1===n&&(r=revLookup[o.charCodeAt(h)]<<10|revLookup[o.charCodeAt(h+1)]<<4|revLookup[o.charCodeAt(h+2)]>>2,u[p++]=r>>8&255,u[p++]=255&r),u}function tripletToBase64(o){return lookup[o>>18&63]+lookup[o>>12&63]+lookup[o>>6&63]+lookup[63&o]}function encodeChunk(o,r,e){for(var t,n=[],u=r;up?p:u+16383));return 1===t?(r=o[e-1],n.push(lookup[r>>2]+lookup[r<<4&63]+"==")):2===t&&(r=(o[e-2]<<8)+o[e-1],n.push(lookup[r>>10]+lookup[r>>4&63]+lookup[r<<2&63]+"=")),n.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],21:[function(require,module,exports){},{}],22:[function(require,module,exports){(function(global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +!function(e){var o="object"==typeof exports&&exports&&!exports.nodeType&&exports,n="object"==typeof module&&module&&!module.nodeType&&module,t="object"==typeof global&&global;t.global!==t&&t.window!==t&&t.self!==t||(e=t);var r,u,i=2147483647,f=36,c=1,l=26,s=38,d=700,p=72,a=128,h="-",v=/^xn--/,g=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,x={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},b=f-c,y=Math.floor,C=String.fromCharCode;function m(e){throw new RangeError(x[e])}function j(e,o){for(var n=e.length,t=[];n--;)t[n]=o(e[n]);return t}function A(e,o){var n=e.split("@"),t="";return n.length>1&&(t=n[0]+"@",e=n[1]),t+j((e=e.replace(w,".")).split("."),o).join(".")}function I(e){for(var o,n,t=[],r=0,u=e.length;r=55296&&o<=56319&&r65535&&(o+=C((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=C(e)}).join("")}function F(e,o){return e+22+75*(e<26)-((0!=o)<<5)}function O(e,o,n){var t=0;for(e=n?y(e/d):e>>1,e+=y(e/o);e>b*l>>1;t+=f)e=y(e/b);return y(t+(b+1)*e/(e+s))}function S(e){var o,n,t,r,u,s,d,v,g,w,x,b=[],C=e.length,j=0,A=a,I=p;for((n=e.lastIndexOf(h))<0&&(n=0),t=0;t=128&&m("not-basic"),b.push(e.charCodeAt(t));for(r=n>0?n+1:0;r=C&&m("invalid-input"),((v=(x=e.charCodeAt(r++))-48<10?x-22:x-65<26?x-65:x-97<26?x-97:f)>=f||v>y((i-j)/s))&&m("overflow"),j+=v*s,!(v<(g=d<=I?c:d>=I+l?l:d-I));d+=f)s>y(i/(w=f-g))&&m("overflow"),s*=w;I=O(j-u,o=b.length+1,0==u),y(j/o)>i-A&&m("overflow"),A+=y(j/o),j%=o,b.splice(j++,0,A)}return E(b)}function T(e){var o,n,t,r,u,s,d,v,g,w,x,b,j,A,E,S=[];for(b=(e=I(e)).length,o=a,n=0,u=p,s=0;s=o&&xy((i-n)/(j=t+1))&&m("overflow"),n+=(d-o)*j,o=d,s=0;si&&m("overflow"),x==o){for(v=n,g=f;!(v<(w=g<=u?c:g>=u+l?l:g-u));g+=f)E=v-w,A=f-w,S.push(C(F(w+E%A,0))),v=y(E/A);S.push(C(F(v,0))),u=O(n,j,t==r),n=0,++t}++n,++o}return S.join("")}if(r={version:"1.4.1",ucs2:{decode:I,encode:E},decode:S,encode:T,toASCII:function(e){return A(e,function(e){return g.test(e)?"xn--"+T(e):e})},toUnicode:function(e){return A(e,function(e){return v.test(e)?S(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return r});else if(o&&n)if(module.exports==o)n.exports=r;else for(u in r)r.hasOwnProperty(u)&&(o[u]=r[u]);else e.punycode=r}(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],23:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;function typedArraySupport(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function createBuffer(e){if(e>K_MAX_LENGTH)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=Buffer.prototype,t}function Buffer(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(e)}return from(e,t,r)}function from(e,t,r){if("string"==typeof e)return fromString(e,t);if(ArrayBuffer.isView(e))return fromArrayLike(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(isInstance(e,ArrayBuffer)||e&&isInstance(e.buffer,ArrayBuffer))return fromArrayBuffer(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return Buffer.from(n,t,r);var f=fromObject(e);if(f)return f;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return Buffer.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function assertSize(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function alloc(e,t,r){return assertSize(e),e<=0?createBuffer(e):void 0!==t?"string"==typeof r?createBuffer(e).fill(t,r):createBuffer(e).fill(t):createBuffer(e)}function allocUnsafe(e){return assertSize(e),createBuffer(e<0?0:0|checked(e))}function fromString(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!Buffer.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|byteLength(e,t),n=createBuffer(r),f=n.write(e,t);return f!==r&&(n=n.slice(0,f)),n}function fromArrayLike(e){for(var t=e.length<0?0:0|checked(e.length),r=createBuffer(t),n=0;n=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return 0|e}function SlowBuffer(e){return+e!=e&&(e=0),Buffer.alloc(+e)}function byteLength(e,t){if(Buffer.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||isInstance(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var f=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return base64ToBytes(e).length;default:if(f)return n?-1:utf8ToBytes(e).length;t=(""+t).toLowerCase(),f=!0}}function slowToString(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,r);case"utf8":case"utf-8":return utf8Slice(this,t,r);case"ascii":return asciiSlice(this,t,r);case"latin1":case"binary":return latin1Slice(this,t,r);case"base64":return base64Slice(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function swap(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function bidirectionalIndexOf(e,t,r,n,f){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),numberIsNaN(r=+r)&&(r=f?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(f)return-1;r=e.length-1}else if(r<0){if(!f)return-1;r=0}if("string"==typeof t&&(t=Buffer.from(t,n)),Buffer.isBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,r,n,f);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?f?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):arrayIndexOf(e,[t],r,n,f);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,r,n,f){var i,o=1,u=e.length,s=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,u/=2,s/=2,r/=2}function a(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(f){var h=-1;for(i=r;iu&&(r=u-s),i=r;i>=0;i--){for(var c=!0,l=0;lf&&(n=f):n=f;var i=t.length;n>i/2&&(n=i/2);for(var o=0;o239?4:a>223?3:a>191?2:1;if(f+c<=r)switch(c){case 1:a<128&&(h=a);break;case 2:128==(192&(i=e[f+1]))&&(s=(31&a)<<6|63&i)>127&&(h=s);break;case 3:i=e[f+1],o=e[f+2],128==(192&i)&&128==(192&o)&&(s=(15&a)<<12|(63&i)<<6|63&o)>2047&&(s<55296||s>57343)&&(h=s);break;case 4:i=e[f+1],o=e[f+2],u=e[f+3],128==(192&i)&&128==(192&o)&&128==(192&u)&&(s=(15&a)<<18|(63&i)<<12|(63&o)<<6|63&u)>65535&&s<1114112&&(h=s)}null===h?(h=65533,c=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),f+=c}return decodeCodePointsArray(n)}exports.kMaxLength=K_MAX_LENGTH,Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.warn||console.warn("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(e,t,r){return from(e,t,r)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(e,t,r){return alloc(e,t,r)},Buffer.allocUnsafe=function(e){return allocUnsafe(e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(e)},Buffer.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==Buffer.prototype},Buffer.compare=function(e,t){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),isInstance(t,Uint8Array)&&(t=Buffer.from(t,t.offset,t.byteLength)),!Buffer.isBuffer(e)||!Buffer.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,f=0,i=Math.min(r,n);ft&&(e+=" ... "),""},Buffer.prototype.compare=function(e,t,r,n,f){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),!Buffer.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===f&&(f=this.length),t<0||r>e.length||n<0||f>this.length)throw new RangeError("out of range index");if(n>=f&&t>=r)return 0;if(n>=f)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(f>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0),u=Math.min(i,o),s=this.slice(n,f),a=e.slice(t,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var f=this.length-t;if((void 0===r||r>f)&&(r=f),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return hexWrite(this,e,t,r);case"utf8":case"utf-8":return utf8Write(this,e,t,r);case"ascii":return asciiWrite(this,e,t,r);case"latin1":case"binary":return latin1Write(this,e,t,r);case"base64":return base64Write(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var f="",i=t;ir)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,r,n,f,i){if(!Buffer.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>f||te.length)throw new RangeError("Index out of range")}function checkIEEE754(e,t,r,n,f,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function writeFloat(e,t,r,n,f){return t=+t,r>>>=0,f||checkIEEE754(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(e,t,r,n,23,4),r+4}function writeDouble(e,t,r,n,f){return t=+t,r>>>=0,f||checkIEEE754(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(e,t,r,n,52,8),r+8}Buffer.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e],f=1,i=0;++i>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e+--t],f=1;t>0&&(f*=256);)n+=this[e+--t]*f;return n},Buffer.prototype.readUInt8=function(e,t){return e>>>=0,t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUInt16LE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUInt16BE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e],f=1,i=0;++i=(f*=128)&&(n-=Math.pow(2,8*t)),n},Buffer.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=t,f=1,i=this[e+--n];n>0&&(f*=256);)i+=this[e+--n]*f;return i>=(f*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return e>>>=0,t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt16BE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),ieee754.read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),ieee754.read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),ieee754.read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),ieee754.read(this,e,!1,52,8)},Buffer.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var f=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var f=r-1,i=1;for(this[t+f]=255&e;--f>=0&&(i*=256);)this[t+f]=e/i&255;return t+r},Buffer.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,1,255,0),this[t]=255&e,t+1},Buffer.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},Buffer.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},Buffer.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var f=Math.pow(2,8*r-1);checkInt(this,e,t,r,f-1,-f)}var i=0,o=1,u=0;for(this[t]=255&e;++i>0)-u&255;return t+r},Buffer.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var f=Math.pow(2,8*r-1);checkInt(this,e,t,r,f-1,-f)}var i=r-1,o=1,u=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===u&&0!==this[t+i+1]&&(u=1),this[t+i]=(e/o>>0)-u&255;return t+r},Buffer.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},Buffer.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},Buffer.prototype.writeFloatLE=function(e,t,r){return writeFloat(this,e,t,!0,r)},Buffer.prototype.writeFloatBE=function(e,t,r){return writeFloat(this,e,t,!1,r)},Buffer.prototype.writeDoubleLE=function(e,t,r){return writeDouble(this,e,t,!0,r)},Buffer.prototype.writeDoubleBE=function(e,t,r){return writeDouble(this,e,t,!1,r)},Buffer.prototype.copy=function(e,t,r,n){if(!Buffer.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return f},Buffer.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Buffer.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var f=e.charCodeAt(0);("utf8"===n&&f<128||"latin1"===n)&&(e=f)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!f){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&i.push(239,191,189);continue}f=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),f=r;continue}r=65536+(f-55296<<10|r-56320)}else f&&(t-=3)>-1&&i.push(239,191,189);if(f=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function asciiToBytes(e){for(var t=[],r=0;r>8,f=r%256,i.push(f),i.push(n);return i}function base64ToBytes(e){return base64.toByteArray(base64clean(e))}function blitBuffer(e,t,r,n){for(var f=0;f=t.length||f>=e.length);++f)t[f+r]=e[f];return f}function isInstance(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function numberIsNaN(e){return e!=e}},{"base64-js":20,ieee754:30}],24:[function(require,module,exports){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],25:[function(require,module,exports){(function(process,global){"use strict";var next=global.process&&process.nextTick||global.setImmediate||function(n){setTimeout(n,0)};module.exports=function(n,t){return n?void t.then(function(t){next(function(){n(null,t)})},function(t){next(function(){n(t)})}):t}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:66}],26:[function(require,module,exports){(function(Buffer){function isArray(r){return Array.isArray?Array.isArray(r):"[object Array]"===objectToString(r)}function isBoolean(r){return"boolean"==typeof r}function isNull(r){return null===r}function isNullOrUndefined(r){return null==r}function isNumber(r){return"number"==typeof r}function isString(r){return"string"==typeof r}function isSymbol(r){return"symbol"==typeof r}function isUndefined(r){return void 0===r}function isRegExp(r){return"[object RegExp]"===objectToString(r)}function isObject(r){return"object"==typeof r&&null!==r}function isDate(r){return"[object Date]"===objectToString(r)}function isError(r){return"[object Error]"===objectToString(r)||r instanceof Error}function isFunction(r){return"function"==typeof r}function isPrimitive(r){return null===r||"boolean"==typeof r||"number"==typeof r||"string"==typeof r||"symbol"==typeof r||void 0===r}function objectToString(r){return Object.prototype.toString.call(r)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":32}],27:[function(require,module,exports){var objectCreate=Object.create||objectCreatePolyfill,objectKeys=Object.keys||objectKeysPolyfill,bind=Function.prototype.bind||functionBindPolyfill;function EventEmitter(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=objectCreate(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0;var hasDefineProperty,defaultMaxListeners=10;try{var o={};Object.defineProperty&&Object.defineProperty(o,"x",{value:0}),hasDefineProperty=0===o.x}catch(e){hasDefineProperty=!1}function $getMaxListeners(e){return void 0===e._maxListeners?EventEmitter.defaultMaxListeners:e._maxListeners}function emitNone(e,t,n){if(t)e.call(n);else for(var r=e.length,i=arrayClone(e,r),s=0;s0&&o.length>i){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else o=s[t]=n,++e._eventsCount;return e}function onceWrapper(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var l=new Error('Unhandled "error" event. ('+t+")");throw l.context=t,l}if(!(n=o[e]))return!1;var u="function"==typeof n;switch(r=arguments.length){case 1:emitNone(n,u,this);break;case 2:emitOne(n,u,this,arguments[1]);break;case 3:emitTwo(n,u,this,arguments[1],arguments[2]);break;case 4:emitThree(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),s=1;s=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():spliceOne(n,i),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,o||t)}return this},EventEmitter.prototype.removeAllListeners=function(e){var t,n,r;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=objectCreate(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=objectCreate(null):delete n[e]),this;if(0===arguments.length){var i,s=objectKeys(n);for(r=0;r=0;r--)this.removeListener(e,t[r]);return this},EventEmitter.prototype.listeners=function(e){return _listeners(this,e,!0)},EventEmitter.prototype.rawListeners=function(e){return _listeners(this,e,!1)},EventEmitter.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],28:[function(require,module,exports){function format(e){var r=Array.prototype.slice.call(arguments,1);return r.length&&(e=e.replace(/(%?)(%([jds]))/g,function(e,t,a,n){var s=r.shift();switch(n){case"s":s=""+s;break;case"d":s=Number(s);break;case"j":s=JSON.stringify(s)}return t?(r.unshift(s),e):s})),r.length&&(e+=" "+r.join(" ")),""+(e=e.replace(/%{2,2}/g,"%"))}module.exports=format},{}],29:[function(require,module,exports){var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);function validateParams(t){if("string"==typeof t&&(t=url.parse(t)),t.protocol||(t.protocol="https:"),"https:"!==t.protocol)throw new Error('Protocol "'+t.protocol+'" not supported. Expected "https:"');return t}https.request=function(t,r){return t=validateParams(t),http.request.call(this,t,r)},https.get=function(t,r){return t=validateParams(t),http.get.call(this,t,r)}},{http:80,url:87}],30:[function(require,module,exports){exports.read=function(a,o,t,r,h){var M,p,w=8*h-r-1,f=(1<>1,i=-7,N=t?h-1:0,n=t?-1:1,s=a[o+N];for(N+=n,M=s&(1<<-i)-1,s>>=-i,i+=w;i>0;M=256*M+a[o+N],N+=n,i-=8);for(p=M&(1<<-i)-1,M>>=-i,i+=r;i>0;p=256*p+a[o+N],N+=n,i-=8);if(0===M)M=1-e;else{if(M===f)return p?NaN:1/0*(s?-1:1);p+=Math.pow(2,r),M-=e}return(s?-1:1)*p*Math.pow(2,M-r)},exports.write=function(a,o,t,r,h,M){var p,w,f,e=8*M-h-1,i=(1<>1,n=23===h?Math.pow(2,-24)-Math.pow(2,-77):0,s=r?0:M-1,u=r?1:-1,l=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(w=isNaN(o)?1:0,p=i):(p=Math.floor(Math.log(o)/Math.LN2),o*(f=Math.pow(2,-p))<1&&(p--,f*=2),(o+=p+N>=1?n/f:n*Math.pow(2,1-N))*f>=2&&(p++,f/=2),p+N>=i?(w=0,p=i):p+N>=1?(w=(o*f-1)*Math.pow(2,h),p+=N):(w=o*Math.pow(2,N-1)*Math.pow(2,h),p=0));h>=8;a[t+s]=255&w,s+=u,w/=256,h-=8);for(p=p<0;a[t+s]=255&p,s+=u,p/=256,e-=8);a[t+s-u]|=128*l}},{}],31:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(t,e){t.super_=e;var o=function(){};o.prototype=e.prototype,t.prototype=new o,t.prototype.constructor=t}},{}],32:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function isBuffer(f){return!!f.constructor&&"function"==typeof f.constructor.isBuffer&&f.constructor.isBuffer(f)}function isSlowBuffer(f){return"function"==typeof f.readFloatLE&&"function"==typeof f.slice&&isBuffer(f.slice(0,0))}module.exports=function(f){return null!=f&&(isBuffer(f)||isSlowBuffer(f)||!!f._isBuffer)}},{}],33:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(r){return"[object Array]"==toString.call(r)}},{}],34:[function(require,module,exports){"use strict";var yaml=require("./lib/js-yaml.js");module.exports=yaml},{"./lib/js-yaml.js":35}],35:[function(require,module,exports){"use strict";var loader=require("./js-yaml/loader"),dumper=require("./js-yaml/dumper");function deprecated(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}module.exports.Type=require("./js-yaml/type"),module.exports.Schema=require("./js-yaml/schema"),module.exports.FAILSAFE_SCHEMA=require("./js-yaml/schema/failsafe"),module.exports.JSON_SCHEMA=require("./js-yaml/schema/json"),module.exports.CORE_SCHEMA=require("./js-yaml/schema/core"),module.exports.DEFAULT_SAFE_SCHEMA=require("./js-yaml/schema/default_safe"),module.exports.DEFAULT_FULL_SCHEMA=require("./js-yaml/schema/default_full"),module.exports.load=loader.load,module.exports.loadAll=loader.loadAll,module.exports.safeLoad=loader.safeLoad,module.exports.safeLoadAll=loader.safeLoadAll,module.exports.dump=dumper.dump,module.exports.safeDump=dumper.safeDump,module.exports.YAMLException=require("./js-yaml/exception"),module.exports.MINIMAL_SCHEMA=require("./js-yaml/schema/failsafe"),module.exports.SAFE_SCHEMA=require("./js-yaml/schema/default_safe"),module.exports.DEFAULT_SCHEMA=require("./js-yaml/schema/default_full"),module.exports.scan=deprecated("scan"),module.exports.parse=deprecated("parse"),module.exports.compose=deprecated("compose"),module.exports.addConstructor=deprecated("addConstructor")},{"./js-yaml/dumper":37,"./js-yaml/exception":38,"./js-yaml/loader":39,"./js-yaml/schema":41,"./js-yaml/schema/core":42,"./js-yaml/schema/default_full":43,"./js-yaml/schema/default_safe":44,"./js-yaml/schema/failsafe":45,"./js-yaml/schema/json":46,"./js-yaml/type":47}],36:[function(require,module,exports){"use strict";function isNothing(e){return null==e}function isObject(e){return"object"==typeof e&&null!==e}function toArray(e){return Array.isArray(e)?e:isNothing(e)?[]:[e]}function extend(e,t){var r,o,n,i;if(t)for(r=0,o=(i=Object.keys(t)).length;ri&&" "!==e[u+1],u=o);else if(!isPrintable(a))return STYLE_DOUBLE;d=d&&isPlainSafe(a)}s=s||c&&o-u-1>i&&" "!==e[u+1]}return l||s?n>9&&needIndentIndicator(e)?STYLE_DOUBLE:s?STYLE_FOLDED:STYLE_LITERAL:d&&!r(e)?STYLE_PLAIN:STYLE_SINGLE}function writeScalar(e,t,n,i){e.dump=function(){if(0===t.length)return"''";if(!e.noCompatMode&&-1!==DEPRECATED_BOOLEANS_SYNTAX.indexOf(t))return"'"+t+"'";var r=e.indent*Math.max(1,n),o=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-r),a=i||e.flowLevel>-1&&n>=e.flowLevel;switch(chooseScalarStyle(t,a,e.indent,o,function(t){return testImplicitResolving(e,t)})){case STYLE_PLAIN:return t;case STYLE_SINGLE:return"'"+t.replace(/'/g,"''")+"'";case STYLE_LITERAL:return"|"+blockHeader(t,e.indent)+dropEndingNewline(indentString(t,r));case STYLE_FOLDED:return">"+blockHeader(t,e.indent)+dropEndingNewline(indentString(foldString(t,o),r));case STYLE_DOUBLE:return'"'+escapeString(t,o)+'"';default:throw new YAMLException("impossible error: invalid scalar style")}}()}function blockHeader(e,t){var n=needIndentIndicator(e)?String(t):"",i="\n"===e[e.length-1];return n+(i&&("\n"===e[e.length-2]||"\n"===e)?"+":i?"":"-")+"\n"}function dropEndingNewline(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function foldString(e,t){for(var n,i,r,o=/(\n+)([^\n]*)/g,a=(n=-1!==(n=e.indexOf("\n"))?n:e.length,o.lastIndex=n,foldLine(e.slice(0,n),t)),l="\n"===e[0]||" "===e[0];r=o.exec(e);){var s=r[1],c=r[2];i=" "===c[0],a+=s+(l||i||""===c?"":"\n")+foldLine(c,t),l=i}return a}function foldLine(e,t){if(""===e||" "===e[0])return e;for(var n,i,r=/ [^ ]/g,o=0,a=0,l=0,s="";n=r.exec(e);)(l=n.index)-o>t&&(i=a>o?a:l,s+="\n"+e.slice(o,i),o=i+1),a=l;return s+="\n",e.length-o>t&&a>o?s+=e.slice(o,a)+"\n"+e.slice(a+1):s+=e.slice(o),s.slice(1)}function escapeString(e){for(var t,n,i,r="",o=0;o=55296&&t<=56319&&(n=e.charCodeAt(o+1))>=56320&&n<=57343?(r+=encodeHex(1024*(t-55296)+n-56320+65536),o++):r+=!(i=ESCAPE_SEQUENCES[t])&&isPrintable(t)?e[o]:i||encodeHex(t);return r}function writeFlowSequence(e,t,n){var i,r,o="",a=e.tag;for(i=0,r=n.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),writeNode(e,t,a,!1,!1)&&(s+=l+=e.dump));e.tag=c,e.dump="{"+s+"}"}function writeBlockMapping(e,t,n,i){var r,o,a,l,s,c,u="",d=e.tag,p=Object.keys(n);if(!0===e.sortKeys)p.sort();else if("function"==typeof e.sortKeys)p.sort(e.sortKeys);else if(e.sortKeys)throw new YAMLException("sortKeys must be a boolean or a function");for(r=0,o=p.length;r1024)&&(e.dump&&CHAR_LINE_FEED===e.dump.charCodeAt(0)?c+="?":c+="? "),c+=e.dump,s&&(c+=generateNextLine(e,t)),writeNode(e,t+1,l,!0,s)&&(e.dump&&CHAR_LINE_FEED===e.dump.charCodeAt(0)?c+=":":c+=": ",u+=c+=e.dump));e.tag=d,e.dump=u||"{}"}function detectType(e,t,n){var i,r,o,a,l,s;for(o=0,a=(r=n?e.explicitTypes:e.implicitTypes).length;o tag resolver accepts not "'+s+'" style');i=l.represent[s](t,s)}e.dump=i}return!0}return!1}function writeNode(e,t,n,i,r,o){e.tag=null,e.dump=n,detectType(e,n,!1)||detectType(e,n,!0);var a=_toString.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var l,s,c="[object Object]"===a||"[object Array]"===a;if(c&&(s=-1!==(l=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||s||2!==e.indent&&t>0)&&(r=!1),s&&e.usedDuplicates[l])e.dump="*ref_"+l;else{if(c&&s&&!e.usedDuplicates[l]&&(e.usedDuplicates[l]=!0),"[object Object]"===a)i&&0!==Object.keys(e.dump).length?(writeBlockMapping(e,t,e.dump,r),s&&(e.dump="&ref_"+l+e.dump)):(writeFlowMapping(e,t,e.dump),s&&(e.dump="&ref_"+l+" "+e.dump));else if("[object Array]"===a){var u=e.noArrayIndent?t-1:t;i&&0!==e.dump.length?(writeBlockSequence(e,u,e.dump,r),s&&(e.dump="&ref_"+l+e.dump)):(writeFlowSequence(e,u,e.dump),s&&(e.dump="&ref_"+l+" "+e.dump))}else{if("[object String]"!==a){if(e.skipInvalid)return!1;throw new YAMLException("unacceptable kind of an object to dump "+a)}"?"!==e.tag&&writeScalar(e,e.dump,t,o)}null!==e.tag&&"?"!==e.tag&&(e.dump="!<"+e.tag+"> "+e.dump)}return!0}function getDuplicateReferences(e,t){var n,i,r=[],o=[];for(inspectNode(e,r,o),n=0,i=o.length;n>10),56320+(e-65536&1023))}for(var simpleEscapeCheck=new Array(256),simpleEscapeMap=new Array(256),i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);function State(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||DEFAULT_FULL_SCHEMA,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function generateError(e,t){return new YAMLException(t,new Mark(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function throwError(e,t){throw generateError(e,t)}function throwWarning(e,t){e.onWarning&&e.onWarning.call(null,generateError(e,t))}var directiveHandlers={YAML:function(e,t,n){var i,o,r;null!==e.version&&throwError(e,"duplication of %YAML directive"),1!==n.length&&throwError(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&throwError(e,"ill-formed argument of the YAML directive"),o=parseInt(i[1],10),r=parseInt(i[2],10),1!==o&&throwError(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=r<2,1!==r&&2!==r&&throwWarning(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,o;2!==n.length&&throwError(e,"TAG directive accepts exactly two arguments"),i=n[0],o=n[1],PATTERN_TAG_HANDLE.test(i)||throwError(e,"ill-formed tag handle (first argument) of the TAG directive"),_hasOwnProperty.call(e.tagMap,i)&&throwError(e,'there is a previously declared suffix for "'+i+'" tag handle'),PATTERN_TAG_URI.test(o)||throwError(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagMap[i]=o}};function captureSegment(e,t,n,i){var o,r,a,s;if(t1&&(e.result+=common.repeat("\n",t-1))}function readPlainScalar(e,t,n){var i,o,r,a,s,p,c,l,u=e.kind,d=e.result;if(is_WS_OR_EOL(l=e.input.charCodeAt(e.position))||is_FLOW_INDICATOR(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(is_WS_OR_EOL(i=e.input.charCodeAt(e.position+1))||n&&is_FLOW_INDICATOR(i)))return!1;for(e.kind="scalar",e.result="",o=r=e.position,a=!1;0!==l;){if(58===l){if(is_WS_OR_EOL(i=e.input.charCodeAt(e.position+1))||n&&is_FLOW_INDICATOR(i))break}else if(35===l){if(is_WS_OR_EOL(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&testDocumentSeparator(e)||n&&is_FLOW_INDICATOR(l))break;if(is_EOL(l)){if(s=e.line,p=e.lineStart,c=e.lineIndent,skipSeparationSpace(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=r,e.line=s,e.lineStart=p,e.lineIndent=c;break}}a&&(captureSegment(e,o,r,!1),writeFoldedLines(e,e.line-s),o=r=e.position,a=!1),is_WHITE_SPACE(l)||(r=e.position+1),l=e.input.charCodeAt(++e.position)}return captureSegment(e,o,r,!1),!!e.result||(e.kind=u,e.result=d,!1)}function readSingleQuotedScalar(e,t){var n,i,o;if(39!==(n=e.input.charCodeAt(e.position)))return!1;for(e.kind="scalar",e.result="",e.position++,i=o=e.position;0!==(n=e.input.charCodeAt(e.position));)if(39===n){if(captureSegment(e,i,e.position,!0),39!==(n=e.input.charCodeAt(++e.position)))return!0;i=e.position,e.position++,o=e.position}else is_EOL(n)?(captureSegment(e,i,o,!0),writeFoldedLines(e,skipSeparationSpace(e,!1,t)),i=o=e.position):e.position===e.lineStart&&testDocumentSeparator(e)?throwError(e,"unexpected end of the document within a single quoted scalar"):(e.position++,o=e.position);throwError(e,"unexpected end of the stream within a single quoted scalar")}function readDoubleQuotedScalar(e,t){var n,i,o,r,a,s;if(34!==(s=e.input.charCodeAt(e.position)))return!1;for(e.kind="scalar",e.result="",e.position++,n=i=e.position;0!==(s=e.input.charCodeAt(e.position));){if(34===s)return captureSegment(e,n,e.position,!0),e.position++,!0;if(92===s){if(captureSegment(e,n,e.position,!0),is_EOL(s=e.input.charCodeAt(++e.position)))skipSeparationSpace(e,!1,t);else if(s<256&&simpleEscapeCheck[s])e.result+=simpleEscapeMap[s],e.position++;else if((a=escapedHexLen(s))>0){for(o=a,r=0;o>0;o--)(a=fromHexCode(s=e.input.charCodeAt(++e.position)))>=0?r=(r<<4)+a:throwError(e,"expected hexadecimal character");e.result+=charFromCodepoint(r),e.position++}else throwError(e,"unknown escape sequence");n=i=e.position}else is_EOL(s)?(captureSegment(e,n,i,!0),writeFoldedLines(e,skipSeparationSpace(e,!1,t)),n=i=e.position):e.position===e.lineStart&&testDocumentSeparator(e)?throwError(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}throwError(e,"unexpected end of the stream within a double quoted scalar")}function readFlowCollection(e,t){var n,i,o,r,a,s,p,c,l,u,d=!0,h=e.tag,f=e.anchor,_={};if(91===(u=e.input.charCodeAt(e.position)))o=93,s=!1,i=[];else{if(123!==u)return!1;o=125,s=!0,i={}}for(null!==e.anchor&&(e.anchorMap[e.anchor]=i),u=e.input.charCodeAt(++e.position);0!==u;){if(skipSeparationSpace(e,!0,t),(u=e.input.charCodeAt(e.position))===o)return e.position++,e.tag=h,e.anchor=f,e.kind=s?"mapping":"sequence",e.result=i,!0;d||throwError(e,"missed comma between flow collection entries"),l=null,r=a=!1,63===u&&is_WS_OR_EOL(e.input.charCodeAt(e.position+1))&&(r=a=!0,e.position++,skipSeparationSpace(e,!0,t)),n=e.line,composeNode(e,t,CONTEXT_FLOW_IN,!1,!0),c=e.tag,p=e.result,skipSeparationSpace(e,!0,t),u=e.input.charCodeAt(e.position),!a&&e.line!==n||58!==u||(r=!0,u=e.input.charCodeAt(++e.position),skipSeparationSpace(e,!0,t),composeNode(e,t,CONTEXT_FLOW_IN,!1,!0),l=e.result),s?storeMappingPair(e,i,_,c,p,l):r?i.push(storeMappingPair(e,null,_,c,p,l)):i.push(p),skipSeparationSpace(e,!0,t),44===(u=e.input.charCodeAt(e.position))?(d=!0,u=e.input.charCodeAt(++e.position)):d=!1}throwError(e,"unexpected end of the stream within a flow collection")}function readBlockScalar(e,t){var n,i,o,r,a=CHOMPING_CLIP,s=!1,p=!1,c=t,l=0,u=!1;if(124===(r=e.input.charCodeAt(e.position)))i=!1;else{if(62!==r)return!1;i=!0}for(e.kind="scalar",e.result="";0!==r;)if(43===(r=e.input.charCodeAt(++e.position))||45===r)CHOMPING_CLIP===a?a=43===r?CHOMPING_KEEP:CHOMPING_STRIP:throwError(e,"repeat of a chomping mode identifier");else{if(!((o=fromDecimalCode(r))>=0))break;0===o?throwError(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):p?throwError(e,"repeat of an indentation width identifier"):(c=t+o-1,p=!0)}if(is_WHITE_SPACE(r)){do{r=e.input.charCodeAt(++e.position)}while(is_WHITE_SPACE(r));if(35===r)do{r=e.input.charCodeAt(++e.position)}while(!is_EOL(r)&&0!==r)}for(;0!==r;){for(readLineBreak(e),e.lineIndent=0,r=e.input.charCodeAt(e.position);(!p||e.lineIndentc&&(c=e.lineIndent),is_EOL(r))l++;else{if(e.lineIndentt)&&0!==i)throwError(e,"bad indentation of a sequence entry");else if(e.lineIndentt)&&(composeNode(e,t,CONTEXT_BLOCK_OUT,!0,o)&&(_?h=e.result:f=e.result),_||(storeMappingPair(e,l,u,d,h,f,r,a),d=h=f=null),skipSeparationSpace(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)throwError(e,"bad indentation of a mapping entry");else if(e.lineIndentt?h=1:e.lineIndent===t?h=0:e.lineIndentt?h=1:e.lineIndent===t?h=0:e.lineIndent tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):throwError(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):throwError(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||_}function readDocument(e){var t,n,i,o,r=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(o=e.input.charCodeAt(e.position))&&(skipSeparationSpace(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==o));){for(a=!0,o=e.input.charCodeAt(++e.position),t=e.position;0!==o&&!is_WS_OR_EOL(o);)o=e.input.charCodeAt(++e.position);for(i=[],(n=e.input.slice(t,e.position)).length<1&&throwError(e,"directive name must not be less than one character in length");0!==o;){for(;is_WHITE_SPACE(o);)o=e.input.charCodeAt(++e.position);if(35===o){do{o=e.input.charCodeAt(++e.position)}while(0!==o&&!is_EOL(o));break}if(is_EOL(o))break;for(t=e.position;0!==o&&!is_WS_OR_EOL(o);)o=e.input.charCodeAt(++e.position);i.push(e.input.slice(t,e.position))}0!==o&&readLineBreak(e),_hasOwnProperty.call(directiveHandlers,n)?directiveHandlers[n](e,n,i):throwWarning(e,'unknown document directive "'+n+'"')}skipSeparationSpace(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,skipSeparationSpace(e,!0,-1)):a&&throwError(e,"directives end mark is expected"),composeNode(e,e.lineIndent-1,CONTEXT_BLOCK_OUT,!1,!0),skipSeparationSpace(e,!0,-1),e.checkLineBreaks&&PATTERN_NON_ASCII_LINE_BREAKS.test(e.input.slice(r,e.position))&&throwWarning(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&testDocumentSeparator(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,skipSeparationSpace(e,!0,-1)):e.position0&&-1==="\0\r\n…\u2028\u2029".indexOf(this.buffer.charAt(e-1));)if(e-=1,this.position-e>i/2-1){n=" ... ",e+=5;break}for(r="",o=this.position;oi/2-1){r=" ... ",o-=5;break}return s=this.buffer.slice(e,o),common.repeat(" ",t)+n+s+r+"\n"+common.repeat(" ",t+this.position-e+n.length)+"^"},Mark.prototype.toString=function(t){var i,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),t||(i=this.getSnippet())&&(n+=":\n"+i),n},module.exports=Mark},{"./common":36}],41:[function(require,module,exports){"use strict";var common=require("./common"),YAMLException=require("./exception"),Type=require("./type");function compileList(i,e,t){var c=[];return i.include.forEach(function(i){t=compileList(i,e,t)}),i[e].forEach(function(i){t.forEach(function(e,t){e.tag===i.tag&&e.kind===i.kind&&c.push(t)}),t.push(i)}),t.filter(function(i,e){return-1===c.indexOf(e)})}function compileMap(){var i,e,t={scalar:{},sequence:{},mapping:{},fallback:{}};function c(i){t[i.kind][i.tag]=t.fallback[i.tag]=i}for(i=0,e=arguments.length;i64)){if(e<0)return!1;u+=6}return u%8==0}function constructYamlBinary(r){var e,n,u=r.replace(/[\r\n=]/g,""),f=u.length,t=BASE64_MAP,a=0,i=[];for(e=0;e>16&255),i.push(a>>8&255),i.push(255&a)),a=a<<6|t.indexOf(u.charAt(e));return 0===(n=f%4*6)?(i.push(a>>16&255),i.push(a>>8&255),i.push(255&a)):18===n?(i.push(a>>10&255),i.push(a>>2&255)):12===n&&i.push(a>>4&255),NodeBuffer?NodeBuffer.from?NodeBuffer.from(i):new NodeBuffer(i):i}function representYamlBinary(r){var e,n,u="",f=0,t=r.length,a=BASE64_MAP;for(e=0;e>18&63],u+=a[f>>12&63],u+=a[f>>6&63],u+=a[63&f]),f=(f<<8)+r[e];return 0===(n=t%3)?(u+=a[f>>18&63],u+=a[f>>12&63],u+=a[f>>6&63],u+=a[63&f]):2===n?(u+=a[f>>10&63],u+=a[f>>4&63],u+=a[f<<2&63],u+=a[64]):1===n&&(u+=a[f>>2&63],u+=a[f<<4&63],u+=a[64],u+=a[64]),u}function isBinary(r){return NodeBuffer&&NodeBuffer.isBuffer(r)}module.exports=new Type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary})},{"../type":47}],49:[function(require,module,exports){"use strict";var Type=require("../type");function resolveYamlBoolean(e){if(null===e)return!1;var r=e.length;return 4===r&&("true"===e||"True"===e||"TRUE"===e)||5===r&&("false"===e||"False"===e||"FALSE"===e)}function constructYamlBoolean(e){return"true"===e||"True"===e||"TRUE"===e}function isBoolean(e){return"[object Boolean]"===Object.prototype.toString.call(e)}module.exports=new Type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":47}],50:[function(require,module,exports){"use strict";var common=require("../common"),Type=require("../type"),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function resolveYamlFloat(e){return null!==e&&!(!YAML_FLOAT_PATTERN.test(e)||"_"===e[e.length-1])}function constructYamlFloat(e){var r,t,a,n;return t="-"===(r=e.replace(/_/g,"").toLowerCase())[0]?-1:1,n=[],"+-".indexOf(r[0])>=0&&(r=r.slice(1)),".inf"===r?1===t?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===r?NaN:r.indexOf(":")>=0?(r.split(":").forEach(function(e){n.unshift(parseFloat(e,10))}),r=0,a=1,n.forEach(function(e){r+=e*a,a*=60}),t*r):t*parseFloat(r,10)}var SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;function representYamlFloat(e,r){var t;if(isNaN(e))switch(r){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(r){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(r){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(common.isNegativeZero(e))return"-0.0";return t=e.toString(10),SCIENTIFIC_WITHOUT_DOT.test(t)?t.replace("e",".e"):t}function isFloat(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||common.isNegativeZero(e))}module.exports=new Type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"})},{"../common":36,"../type":47}],51:[function(require,module,exports){"use strict";var common=require("../common"),Type=require("../type");function isHexCode(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function isOctCode(e){return 48<=e&&e<=55}function isDecCode(e){return 48<=e&&e<=57}function resolveYamlInteger(e){if(null===e)return!1;var r,t=e.length,n=0,i=!1;if(!t)return!1;if("-"!==(r=e[n])&&"+"!==r||(r=e[++n]),"0"===r){if(n+1===t)return!0;if("b"===(r=e[++n])){for(n++;n=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0"+e.toString(8):"-0"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})},{"../common":36,"../type":47}],52:[function(require,module,exports){"use strict";var esprima;try{var _require=require;esprima=_require("esprima")}catch(e){"undefined"!=typeof window&&(esprima=window.esprima)}var Type=require("../../type");function resolveJavascriptFunction(e){if(null===e)return!1;try{var r="("+e+")",n=esprima.parse(r,{range:!0});return"Program"===n.type&&1===n.body.length&&"ExpressionStatement"===n.body[0].type&&("ArrowFunctionExpression"===n.body[0].expression.type||"FunctionExpression"===n.body[0].expression.type)}catch(e){return!1}}function constructJavascriptFunction(e){var r,n="("+e+")",t=esprima.parse(n,{range:!0}),o=[];if("Program"!==t.type||1!==t.body.length||"ExpressionStatement"!==t.body[0].type||"ArrowFunctionExpression"!==t.body[0].expression.type&&"FunctionExpression"!==t.body[0].expression.type)throw new Error("Failed to resolve function");return t.body[0].expression.params.forEach(function(e){o.push(e.name)}),r=t.body[0].expression.body.range,"BlockStatement"===t.body[0].expression.body.type?new Function(o,n.slice(r[0]+1,r[1]-1)):new Function(o,"return "+n.slice(r[0],r[1]))}function representJavascriptFunction(e){return e.toString()}function isFunction(e){return"[object Function]"===Object.prototype.toString.call(e)}module.exports=new Type("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:resolveJavascriptFunction,construct:constructJavascriptFunction,predicate:isFunction,represent:representJavascriptFunction})},{"../../type":47}],53:[function(require,module,exports){"use strict";var Type=require("../../type");function resolveJavascriptRegExp(e){if(null===e)return!1;if(0===e.length)return!1;var r=e,t=/\/([gim]*)$/.exec(e),n="";if("/"===r[0]){if(t&&(n=t[1]),n.length>3)return!1;if("/"!==r[r.length-n.length-1])return!1}return!0}function constructJavascriptRegExp(e){var r=e,t=/\/([gim]*)$/.exec(e),n="";return"/"===r[0]&&(t&&(n=t[1]),r=r.slice(1,r.length-n.length-1)),new RegExp(r,n)}function representJavascriptRegExp(e){var r="/"+e.source+"/";return e.global&&(r+="g"),e.multiline&&(r+="m"),e.ignoreCase&&(r+="i"),r}function isRegExp(e){return"[object RegExp]"===Object.prototype.toString.call(e)}module.exports=new Type("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:resolveJavascriptRegExp,construct:constructJavascriptRegExp,predicate:isRegExp,represent:representJavascriptRegExp})},{"../../type":47}],54:[function(require,module,exports){"use strict";var Type=require("../../type");function resolveJavascriptUndefined(){return!0}function constructJavascriptUndefined(){}function representJavascriptUndefined(){return""}function isUndefined(e){return void 0===e}module.exports=new Type("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:resolveJavascriptUndefined,construct:constructJavascriptUndefined,predicate:isUndefined,represent:representJavascriptUndefined})},{"../../type":47}],55:[function(require,module,exports){"use strict";var Type=require("../type");module.exports=new Type("tag:yaml.org,2002:map",{kind:"mapping",construct:function(e){return null!==e?e:{}}})},{"../type":47}],56:[function(require,module,exports){"use strict";var Type=require("../type");function resolveYamlMerge(e){return"<<"===e||null===e}module.exports=new Type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge})},{"../type":47}],57:[function(require,module,exports){"use strict";var Type=require("../type");function resolveYamlNull(l){if(null===l)return!0;var e=l.length;return 1===e&&"~"===l||4===e&&("null"===l||"Null"===l||"NULL"===l)}function constructYamlNull(){return null}function isNull(l){return null===l}module.exports=new Type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},{"../type":47}],58:[function(require,module,exports){"use strict";var Type=require("../type"),_hasOwnProperty=Object.prototype.hasOwnProperty,_toString=Object.prototype.toString;function resolveYamlOmap(r){if(null===r)return!0;var t,e,n,o,u,a=[],l=r;for(t=0,e=l.length;t0&&(c=module.exports.formatter.apply(null,a)),r&&r.message&&(c+=(c?" \n":"")+r.message);var i=new e(c);return extendError(i,r),extendToJSON(i),extend(i,t),i}}function extendError(e,r){extendStack(e,r),extend(e,r)}function extendToJSON(e){e.toJSON=errorToJSON,e.inspect=errorToString}function extend(e,r){if(r&&"object"==typeof r)for(var t=Object.keys(r),o=0;o=0))try{e[n]=r[n]}catch(e){}}}function errorToJSON(){var e={},r=Object.keys(this);r=r.concat(errorPrototypeProperties);for(var t=0;t=0)return r.splice(t,1),r.join("\n")}return e}}module.exports=create(Error),module.exports.error=create(Error),module.exports.eval=create(EvalError),module.exports.range=create(RangeError),module.exports.reference=create(ReferenceError),module.exports.syntax=create(SyntaxError),module.exports.type=create(TypeError),module.exports.uri=create(URIError),module.exports.formatter=format;var supportsLazyStack=!(!Object.getOwnPropertyDescriptor||!Object.defineProperty||"undefined"!=typeof navigator&&/Android/.test(navigator.userAgent));function hasLazyStack(e){if(!supportsLazyStack)return!1;var r=Object.getOwnPropertyDescriptor(e,"stack");return!!r&&"function"==typeof r.get}function lazyJoinStacks(e,r){var t=Object.getOwnPropertyDescriptor(e,"stack");Object.defineProperty(e,"stack",{get:function(){return joinStacks(t.get.apply(e),r.stack)},enumerable:!1,configurable:!0})}function lazyPopStack(e){var r=Object.getOwnPropertyDescriptor(e,"stack");Object.defineProperty(e,"stack",{get:function(){return popStack(r.get.apply(e))},enumerable:!1,configurable:!0})}},{"format-util":28}],65:[function(require,module,exports){(function(process){"use strict";function nextTick(e,n,c,r){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var s,t,o=arguments.length;switch(o){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,n)});case 3:return process.nextTick(function(){e.call(null,n,c)});case 4:return process.nextTick(function(){e.call(null,n,c,r)});default:for(s=new Array(o-1),t=0;t1)for(var r=1;r0&&p>s&&(p=s);for(var y=0;y=0?(u=f.substr(0,v),c=f.substr(v+1)):(u=f,c=""),i=decodeURIComponent(u),l=decodeURIComponent(c),hasOwnProperty(o,i)?isArray(o[i])?o[i].push(l):o[i]=[o[i],l]:o[i]=l}return o};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)}},{}],68:[function(require,module,exports){"use strict";var stringifyPrimitive=function(r){switch(typeof r){case"string":return r;case"boolean":return r?"true":"false";case"number":return isFinite(r)?r:"";default:return""}};module.exports=function(r,e,t,n){return e=e||"&",t=t||"=",null===r&&(r=void 0),"object"==typeof r?map(objectKeys(r),function(n){var i=encodeURIComponent(stringifyPrimitive(n))+t;return isArray(r[n])?map(r[n],function(r){return i+encodeURIComponent(stringifyPrimitive(r))}).join(e):i+encodeURIComponent(stringifyPrimitive(r[n]))}).join(e):n?encodeURIComponent(stringifyPrimitive(n))+t+encodeURIComponent(stringifyPrimitive(r)):""};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)};function map(r,e){if(r.map)return r.map(e);for(var t=[],n=0;n0?("string"==typeof t||d.objectMode||Object.getPrototypeOf(t)===Buffer.prototype||(t=_uint8ArrayToBuffer(t)),n?d.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):addChunk(e,d,t,!0):d.ended?e.emit("error",new Error("stream.push() after EOF")):(d.reading=!1,d.decoder&&!r?(t=d.decoder.write(t),d.objectMode||0!==t.length?addChunk(e,d,t,!1):maybeReadMore(e,d)):addChunk(e,d,t,!1))):n||(d.reading=!1));return needMoreData(d)}function addChunk(e,t,r,n){t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&emitReadable(e)),maybeReadMore(e,t)}function chunkInvalid(e,t){var r;return _isUint8Array(t)||"string"==typeof t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=MAX_HWM?e=MAX_HWM:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function howMuchToRead(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=computeNewHighWaterMark(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function onEofChunk(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,emitReadable(e)}}function emitReadable(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(debug("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?pna.nextTick(emitReadable_,e):emitReadable_(e))}function emitReadable_(e){debug("emit readable"),e.emit("readable"),flow(e)}function maybeReadMore(e,t){t.readingMore||(t.readingMore=!0,pna.nextTick(maybeReadMore_,e,t))}function maybeReadMore_(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=fromListPartial(e,t.buffer,t.decoder),r);var r}function fromListPartial(e,t,r){var n;return ei.length?i.length:e;if(d===i.length?a+=i:a+=i.slice(0,e),0===(e-=d)){d===i.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=i.slice(d));break}++n}return t.length-=n,a}function copyFromBuffer(e,t){var r=Buffer.allocUnsafe(e),n=t.head,a=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var i=n.data,d=e>i.length?i.length:e;if(i.copy(r,r.length-e,0,d),0===(e-=d)){d===i.length?(++a,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=i.slice(d));break}++a}return t.length-=a,r}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,pna.nextTick(endReadableNT,t,e))}function endReadableNT(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function indexOf(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return debug("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?endReadable(this):emitReadable(this),null;if(0===(e=howMuchToRead(e,t))&&t.ended)return 0===t.length&&endReadable(this),null;var n,a=t.needReadable;return debug("need readable",a),(0===t.length||t.length-e0?fromList(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&endReadable(this)),null!==n&&this.emit("data",n),n},Readable.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,debug("pipe count=%d opts=%j",n.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?d:b;function i(t,a){debug("onunpipe"),t===r&&a&&!1===a.hasUnpiped&&(a.hasUnpiped=!0,debug("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",o),e.removeListener("error",h),e.removeListener("unpipe",i),r.removeListener("end",d),r.removeListener("end",b),r.removeListener("data",s),u=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||o())}function d(){debug("onend"),e.end()}n.endEmitted?pna.nextTick(a):r.once("end",a),e.on("unpipe",i);var o=pipeOnDrain(r);e.on("drain",o);var u=!1;var l=!1;function s(t){debug("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==indexOf(n.pipes,e))&&!u&&(debug("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function h(t){debug("onerror",t),b(),e.removeListener("error",h),0===EElistenerCount(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",p),b()}function p(){debug("onfinish"),e.removeListener("close",f),b()}function b(){debug("unpipe"),r.unpipe(e)}return r.on("data",s),prependListener(e,"error",h),e.once("close",f),e.once("finish",p),e.emit("pipe",r),n.flowing||(debug("pipe resume"),r.resume()),e},Readable.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:pna.nextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return Buffer.from(e)}function _isUint8Array(e){return Buffer.isBuffer(e)||e instanceof OurUint8Array}var realHasInstance,destroyImpl=require("./internal/streams/destroy");function nop(){}function WritableState(e,t){Duplex=Duplex||require("./_stream_duplex"),e=e||{};var r=t instanceof Duplex;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var i=e.highWaterMark,n=e.writableHighWaterMark,o=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(n||0===n)?n:o,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===e.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){onwrite(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(e){if(Duplex=Duplex||require("./_stream_duplex"),!(realHasInstance.call(Writable,this)||this instanceof Duplex))return new Writable(e);this._writableState=new WritableState(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),Stream.call(this)}function writeAfterEnd(e,t){var r=new Error("write after end");e.emit("error",r),pna.nextTick(t,r)}function validChunk(e,t,r,i){var n=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(e.emit("error",o),pna.nextTick(i,o),n=!1),n}function decodeChunk(e,t,r){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=Buffer.from(t,r)),t}function writeOrBuffer(e,t,r,i,n,o){if(!r){var a=decodeChunk(t,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=t.objectMode?1:i.length;t.length+=s;var f=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(e,t,r){var i=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||endWritable(this,i,r)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{"./_stream_duplex":70,"./internal/streams/destroy":76,"./internal/streams/stream":77,_process:66,"core-util-is":26,inherits:31,"process-nextick-args":65,"safe-buffer":79,timers:85,"util-deprecate":89}],75:[function(require,module,exports){"use strict";function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var Buffer=require("safe-buffer").Buffer,util=require("util");function copyBuffer(t,e,i){t.copy(e,i)}module.exports=function(){function t(){_classCallCheck(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,i=""+e.data;e=e.next;)i+=t+e.data;return i},t.prototype.concat=function(t){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var e=Buffer.allocUnsafe(t>>>0),i=this.head,n=0;i;)copyBuffer(i.data,e,n),n+=i.data.length,i=i.next;return e},t}(),util&&util.inspect&&util.inspect.custom&&(module.exports.prototype[util.inspect.custom]=function(){var t=util.inspect({length:this.length});return this.constructor.name+" "+t})},{"safe-buffer":79,util:21}],76:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(t,e){var r=this,a=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return a||i?(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||pna.nextTick(emitErrorNT,this,t),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(pna.nextTick(emitErrorNT,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)}),this)}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(t,e){t.emit("error",e)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":65}],77:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:27}],78:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":70,"./lib/_stream_passthrough.js":71,"./lib/_stream_readable.js":72,"./lib/_stream_transform.js":73,"./lib/_stream_writable.js":74}],79:[function(require,module,exports){var buffer=require("buffer"),Buffer=buffer.Buffer;function copyProps(f,r){for(var e in f)r[e]=f[e]}function SafeBuffer(f,r,e){return Buffer(f,r,e)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(f,r,e){if("number"==typeof f)throw new TypeError("Argument must not be a number");return Buffer(f,r,e)},SafeBuffer.alloc=function(f,r,e){if("number"!=typeof f)throw new TypeError("Argument must be a number");var u=Buffer(f);return void 0!==r?"string"==typeof e?u.fill(r,e):u.fill(r):u.fill(0),u},SafeBuffer.allocUnsafe=function(f){if("number"!=typeof f)throw new TypeError("Argument must be a number");return Buffer(f)},SafeBuffer.allocUnsafeSlow=function(f){if("number"!=typeof f)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(f)}},{buffer:23}],80:[function(require,module,exports){(function(global){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(e,t){e="string"==typeof e?url.parse(e):extend(e);var r=-1===global.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||r,n=e.hostname||e.host,o=e.port,p=e.path||"/";n&&-1!==n.indexOf(":")&&(n="["+n+"]"),e.url=(n?s+"//"+n:"")+(o?":"+o:"")+p,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var u=new ClientRequest(e);return t&&u.on("response",t),u},http.get=function(e,t){var r=http.request(e,t);return r.end(),r},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lib/request":82,"./lib/response":83,"builtin-status-codes":24,url:87,xtend:90}],81:[function(require,module,exports){(function(global){exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController),exports.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),exports.blobConstructor=!0}catch(r){}var xhr;function getXHR(){if(void 0!==xhr)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(r){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(r){var e=getXHR();if(!e)return!1;try{return e.responseType=r,e.responseType===r}catch(r){}return!1}var haveArrayBuffer=void 0!==global.ArrayBuffer,haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);function isFunction(r){return"function"==typeof r}exports.arraybuffer=exports.fetch||haveArrayBuffer&&checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&haveSlice&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&haveArrayBuffer&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),exports.vbArray=isFunction(global.VBArray),xhr=null}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],82:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),toArrayBuffer=require("to-arraybuffer"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates;function decideMode(e,t){return capability.fetch&&t?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&e?"arraybuffer":capability.vbArray&&e?"text:vbarray":"text"}var ClientRequest=module.exports=function(e){var t,r=this;stream.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+new Buffer(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var o=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!capability.abortController)o=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!capability.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=decideMode(t,o),r._fetchTimer=null,r.on("finish",function(){r._onFinish()})};function statusValid(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}}inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===unsafeHeaders.indexOf(r)&&(this._headers[r]={name:e,value:t})},ClientRequest.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},ClientRequest.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,r=e._headers,o=null;"GET"!==t.method&&"HEAD"!==t.method&&(o=capability.arraybuffer?toArrayBuffer(Buffer.concat(e._body)):capability.blobConstructor?new global.Blob(e._body.map(function(e){return toArrayBuffer(e)}),{type:(r["content-type"]||{}).value||""}):Buffer.concat(e._body).toString());var n=[];if(Object.keys(r).forEach(function(e){var t=r[e].name,o=r[e].value;Array.isArray(o)?o.forEach(function(e){n.push([t,e])}):n.push([t,o])}),"fetch"===e._mode){var i=null;if(capability.abortController){var s=new AbortController;i=s.signal,e._fetchAbortController=s,"requestTimeout"in t&&0!==t.requestTimeout&&(e._fetchTimer=global.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout))}global.fetch(e._opts.url,{method:e._opts.method,headers:n,body:o||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:i}).then(function(t){e._fetchResponse=t,e._connect()},function(t){global.clearTimeout(e._fetchTimer),e._destroyed||e.emit("error",t)})}else{var a=e._xhr=new global.XMLHttpRequest;try{a.open(e._opts.method,e._opts.url,!0)}catch(t){return void process.nextTick(function(){e.emit("error",t)})}"responseType"in a&&(a.responseType=e._mode.split(":")[0]),"withCredentials"in a&&(a.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in a&&a.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(a.timeout=t.requestTimeout,a.ontimeout=function(){e.emit("requestTimeout")}),n.forEach(function(e){a.setRequestHeader(e[0],e[1])}),e._response=null,a.onreadystatechange=function(){switch(a.readyState){case rStates.LOADING:case rStates.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(a.onprogress=function(){e._onXHRProgress()}),a.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{a.send(o)}catch(t){return void process.nextTick(function(){e.emit("error",t)})}}}},ClientRequest.prototype._onXHRProgress=function(){statusValid(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},ClientRequest.prototype._connect=function(){var e=this;e._destroyed||(e._response=new IncomingMessage(e._xhr,e._fetchResponse,e._mode,e._fetchTimer),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},ClientRequest.prototype._write=function(e,t,r){this._body.push(e),r()},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){this._destroyed=!0,global.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},ClientRequest.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),stream.Writable.prototype.end.call(this,e,t,r)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setTimeout=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":81,"./response":83,_process:66,buffer:23,inherits:31,"readable-stream":78,"to-arraybuffer":86}],83:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(e,r,t,a){var s=this;if(stream.Readable.call(s),s._mode=t,s.headers={},s.rawHeaders=[],s.trailers={},s.rawTrailers=[],s.on("end",function(){process.nextTick(function(){s.emit("close")})}),"fetch"===t){if(s._fetchResponse=r,s.url=r.url,s.statusCode=r.status,s.statusMessage=r.statusText,r.headers.forEach(function(e,r){s.headers[r.toLowerCase()]=e,s.rawHeaders.push(r,e)}),capability.writableStream){var o=new WritableStream({write:function(e){return new Promise(function(r,t){s._destroyed?t():s.push(new Buffer(e))?r():s._resumeFetch=r})},close:function(){global.clearTimeout(a),s._destroyed||s.push(null)},abort:function(e){s._destroyed||s.emit("error",e)}});try{return void r.body.pipeTo(o).catch(function(e){global.clearTimeout(a),s._destroyed||s.emit("error",e)})}catch(e){}}var n=r.body.getReader();!function e(){n.read().then(function(r){if(!s._destroyed){if(r.done)return global.clearTimeout(a),void s.push(null);s.push(new Buffer(r.value)),e()}}).catch(function(e){global.clearTimeout(a),s._destroyed||s.emit("error",e)})}()}else{if(s._xhr=e,s._pos=0,s.url=e.responseURL,s.statusCode=e.status,s.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var r=e.match(/^([^:]+):\s*(.*)/);if(r){var t=r[1].toLowerCase();"set-cookie"===t?(void 0===s.headers[t]&&(s.headers[t]=[]),s.headers[t].push(r[2])):void 0!==s.headers[t]?s.headers[t]+=", "+r[2]:s.headers[t]=r[2],s.rawHeaders.push(r[1],r[2])}}),s._charset="x-user-defined",!capability.overrideMimeType){var i=s.rawHeaders["mime-type"];if(i){var u=i.match(/;\s*charset=([^;])(;|$)/);u&&(s._charset=u[1].toLowerCase())}s._charset||(s._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},IncomingMessage.prototype._onXHRProgress=function(){var e=this,r=e._xhr,t=null;switch(e._mode){case"text:vbarray":if(r.readyState!==rStates.DONE)break;try{t=new global.VBArray(r.responseBody).toArray()}catch(e){}if(null!==t){e.push(new Buffer(t));break}case"text":try{t=r.responseText}catch(r){e._mode="text:vbarray";break}if(t.length>e._pos){var a=t.substr(e._pos);if("x-user-defined"===e._charset){for(var s=new Buffer(a.length),o=0;oe._pos&&(e.push(new Buffer(new Uint8Array(n.result.slice(e._pos)))),e._pos=n.result.byteLength)},n.onload=function(){e.push(null)},n.readAsArrayBuffer(t)}e._xhr.readyState===rStates.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":81,_process:66,buffer:23,inherits:31,"readable-stream":78}],84:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(t){switch((t=""+t)&&t.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!0;default:return!1}};function _normalizeEncoding(t){if(!t)return"utf8";for(var e;;)switch(t){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 t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function normalizeEncoding(t){var e=_normalizeEncoding(t);if("string"!=typeof e&&(Buffer.isEncoding===isEncoding||!isEncoding(t)))throw new Error("Unknown encoding: "+t);return e||t}function StringDecoder(t){var e;switch(this.encoding=normalizeEncoding(t),this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,e=4;break;case"utf8":this.fillLast=utf8FillLast,e=4;break;case"base64":this.text=base64Text,this.end=base64End,e=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(e)}function utf8CheckByte(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function utf8CheckIncomplete(t,e,s){var i=e.length-1;if(i=0?(n>0&&(t.lastNeed=n-1),n):--i=0?(n>0&&(t.lastNeed=n-2),n):--i=0?(n>0&&(2===n?n=0:t.lastNeed=n-3),n):0}function utf8CheckExtraBytes(t,e,s){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}function utf8FillLast(t){var e=this.lastTotal-this.lastNeed,s=utf8CheckExtraBytes(this,t,e);return void 0!==s?s:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function utf8Text(t,e){var s=utf8CheckIncomplete(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=s;var i=t.length-(s-this.lastNeed);return t.copy(this.lastChar,0,i),t.toString("utf8",e,i)}function utf8End(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e}function utf16Text(t,e){if((t.length-e)%2==0){var s=t.toString("utf16le",e);if(s){var i=s.charCodeAt(s.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],s.slice(0,-1)}return s}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function utf16End(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var s=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,s)}return e}function base64Text(t,e){var s=(t.length-e)%3;return 0===s?t.toString("base64",e):(this.lastNeed=3-s,this.lastTotal=3,1===s?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-s))}function base64End(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function simpleWrite(t){return t.toString(this.encoding)}function simpleEnd(t){return t&&t.length?this.write(t):""}exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(t){if(0===t.length)return"";var e,s;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";s=this.lastNeed,this.lastNeed=0}else s=0;return s=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(e){var t=nextImmediateId++,i=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[t]=!0,nextTick(function(){immediateIds[t]&&(i?e.apply(null,i):e.call(null),exports.clearImmediate(t))}),t},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(e){delete immediateIds[e]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":66,timers:85}],86:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(Buffer.isBuffer(e)){for(var f=new Uint8Array(e.length),r=e.length,t=0;t",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");function urlParse(t,s,e){if(t&&util.isObject(t)&&t instanceof Url)return t;var h=new Url;return h.parse(t,s,e),h}function urlFormat(t){return util.isString(t)&&(t=urlParse(t)),t instanceof Url?t.format():Url.prototype.format.call(t)}function urlResolve(t,s){return urlParse(t,!1,!0).resolve(s)}function urlResolveObject(t,s){return t?urlParse(t,!1,!0).resolveObject(s):s}Url.prototype.parse=function(t,s,e){if(!util.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var h=t.indexOf("?"),r=-1!==h&&h127?b+="x":b+=d[q];if(!b.match(hostnamePartPattern)){var j=y.slice(0,m),x=y.slice(m+1),U=d.match(hostnamePartStart);U&&(j.push(U[1]),x.unshift(U[2])),x.length&&(o="/"+x.join(".")+o),this.hostname=j.join(".");break}}}this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),g||(this.hostname=punycode.toASCII(this.hostname));var C=this.port?":"+this.port:"",A=this.hostname||"";this.host=A+C,this.href+=this.host,g&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==o[0]&&(o="/"+o))}if(!unsafeProtocol[l])for(m=0,P=autoEscape.length;m0)&&e.host.split("@"))&&(e.auth=U.shift(),e.host=e.hostname=U.shift());return e.search=t.search,e.query=t.query,util.isNull(e.pathname)&&util.isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.href=e.format(),e}if(!d.length)return e.pathname=null,e.search?e.path="/"+e.search:e.path=null,e.href=e.format(),e;for(var q=d.slice(-1)[0],O=(e.host||t.host||d.length>1)&&("."===q||".."===q)||""===q,j=0,x=d.length;x>=0;x--)"."===(q=d[x])?d.splice(x,1):".."===q?(d.splice(x,1),j++):j&&(d.splice(x,1),j--);if(!y&&!P)for(;j--;j)d.unshift("..");!y||""===d[0]||d[0]&&"/"===d[0].charAt(0)||d.unshift(""),O&&"/"!==d.join("/").substr(-1)&&d.push("");var U,C=""===d[0]||d[0]&&"/"===d[0].charAt(0);b&&(e.hostname=e.host=C?"":d.length?d.shift():"",(U=!!(e.host&&e.host.indexOf("@")>0)&&e.host.split("@"))&&(e.auth=U.shift(),e.host=e.hostname=U.shift()));return(y=y||e.host&&d.length)&&!C&&d.unshift(""),d.length?e.pathname=d.join("/"):(e.pathname=null,e.path=null),util.isNull(e.pathname)&&util.isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.auth=t.auth||e.auth,e.slashes=e.slashes||t.slashes,e.href=e.format(),e},Url.prototype.parseHost=function(){var t=this.host,s=portPattern.exec(t);s&&(":"!==(s=s[0])&&(this.port=s.substr(1)),t=t.substr(0,t.length-s.length)),t&&(this.hostname=t)}},{"./util":88,punycode:22,querystring:69}],88:[function(require,module,exports){"use strict";module.exports={isString:function(n){return"string"==typeof n},isObject:function(n){return"object"==typeof n&&null!==n},isNull:function(n){return null===n},isNullOrUndefined:function(n){return null==n}}},{}],89:[function(require,module,exports){(function(global){function deprecate(r,e){if(config("noDeprecation"))return r;var o=!1;return function(){if(!o){if(config("throwDeprecation"))throw new Error(e);config("traceDeprecation")?console.trace(e):console.warn(e),o=!0}return r.apply(this,arguments)}}function config(r){try{if(!global.localStorage)return!1}catch(r){return!1}var e=global.localStorage[r];return null!=e&&"true"===String(e).toLowerCase()}module.exports=deprecate}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],90:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){for(var r={},e=0;et.length)&&(r=t.length);for(var e=0,n=new Array(r);e1&&s.shift(),this._hasParentSelector=null;var f=this._trace(s,e,["$"],u,i,n).filter((function(t){return t&&!t.isParentSelector}));return f.length?l||1!==f.length||f[0].hasArrExpr?f.reduce((function(t,r){var e=o._getPreferredOutput(r);return c&&Array.isArray(e)?t=t.concat(e):t.push(e),t}),[]):this._getPreferredOutput(f[0]):l?[]:void 0}},v.prototype._getPreferredOutput=function(t){var r=this.currResultType;switch(r){case"all":var e=Array.isArray(t.path)?t.path:v.toPathArray(t.path);return t.pointer=v.toPointer(e),t.path="string"==typeof t.path?t.path:v.toPathString(t.path),t;case"value":case"parent":case"parentProperty":return t[r];case"path":return v.toPathString(t[r]);case"pointer":return v.toPointer(t.path);default:throw new TypeError("Unknown result type")}},v.prototype._handleCallback=function(t,r,e){if(r){var n=this._getPreferredOutput(t);t.path="string"==typeof t.path?t.path:v.toPathString(t.path),r(n,e,t)}},v.prototype._trace=function(t,e,n,a,o,u,i,c){var s,y=this;if(!t.length)return s={path:n,value:e,parent:a,parentProperty:o,hasArrExpr:i},this._handleCallback(s,u,"value"),s;var v=t[0],b=t.slice(1),F=[];function d(t){Array.isArray(t)?t.forEach((function(t){F.push(t)})):F.push(t)}if(("string"!=typeof v||c)&&e&&p.call(e,v))d(this._trace(b,e[v],f(n,v),e,v,u,i));else if("*"===v)this._walk(v,b,e,n,a,o,u,(function(t,r,e,n,a,o,u,i){d(y._trace(h(t,e),n,a,o,u,i,!0,!0))}));else if(".."===v)d(this._trace(b,e,n,a,o,u,i)),this._walk(v,b,e,n,a,o,u,(function(t,e,n,a,o,u,i,c){"object"===r(a[t])&&d(y._trace(h(e,n),a[t],f(o,t),a,t,c,!0))}));else{if("^"===v)return this._hasParentSelector=!0,{path:n.slice(0,-1),expr:b,isParentSelector:!0};if("~"===v)return s={path:f(n,v),value:o,parent:a,parentProperty:null},this._handleCallback(s,u,"property"),s;if("$"===v)d(this._trace(b,e,n,null,null,u,i));else if(/^(\x2D?[0-9]*):(\x2D?[0-9]*):?([0-9]*)$/.test(v))d(this._slice(v,b,e,n,a,o,u));else if(0===v.indexOf("?(")){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");this._walk(v,b,e,n,a,o,u,(function(t,r,e,n,a,o,u,i){y._eval(r.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/,"$1"),n[t],t,a,o,u)&&d(y._trace(h(t,e),n,a,o,u,i,!0))}))}else if("("===v[0]){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");d(this._trace(h(this._eval(v,e,n[n.length-1],n.slice(0,-1),a,o),b),e,n,a,o,u,i))}else if("@"===v[0]){var g=!1,_=v.slice(1,-2);switch(_){case"scalar":e&&["object","function"].includes(r(e))||(g=!0);break;case"boolean":case"string":case"undefined":case"function":r(e)===_&&(g=!0);break;case"integer":!Number.isFinite(e)||e%1||(g=!0);break;case"number":Number.isFinite(e)&&(g=!0);break;case"nonFinite":"number"!=typeof e||Number.isFinite(e)||(g=!0);break;case"object":e&&r(e)===_&&(g=!0);break;case"array":Array.isArray(e)&&(g=!0);break;case"other":g=this.currOtherTypeCallback(e,n,a,o);break;case"null":null===e&&(g=!0);break;default:throw new TypeError("Unknown value type "+_)}if(g)return s={path:n,value:e,parent:a,parentProperty:o},this._handleCallback(s,u,"value"),s}else if("`"===v[0]&&e&&p.call(e,v.slice(1))){var w=v.slice(1);d(this._trace(b,e[w],f(n,w),e,w,u,i,!0))}else if(v.includes(",")){var m,P=function(t,r){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=l(t))||r&&t&&"number"==typeof t.length){e&&(t=e);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,u=!0,i=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return u=t.done,t},e:function(t){i=!0,o=t},f:function(){try{u||null==e.return||e.return()}finally{if(i)throw o}}}}(v.split(","));try{for(P.s();!(m=P.n()).done;){var D=m.value;d(this._trace(h(D,b),e,n,a,o,u,!0))}}catch(t){P.e(t)}finally{P.f()}}else!c&&e&&p.call(e,v)&&d(this._trace(b,e[v],f(n,v),e,v,u,i,!0))}if(this._hasParentSelector)for(var x=0;x-1?t.slice(0,i+1)+" return "+t.slice(i+1):" return "+t;return o(Function,c(e).concat([l])).apply(void 0,c(a))}},t.JSONPath=v,Object.defineProperty(t,"__esModule",{value:!0})})); +//# sourceMappingURL=index-browser-umd.min.js.map + +var JSONSchemaFaker = (() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __defProps = Object.defineProperties; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropDescs = Object.getOwnPropertyDescriptors; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getOwnPropSymbols = Object.getOwnPropertySymbols; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __propIsEnum = Object.prototype.propertyIsEnumerable; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; + }; + var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); + var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); + var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + }; + var __reExport = (target, module, desc) => { + if (module && typeof module === "object" || typeof module === "function") { + for (let key of __getOwnPropNames(module)) + if (!__hasOwnProp.call(target, key) && key !== "default") + __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable }); + } + return target; + }; + var __toModule = (module) => { + return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module); + }; + + // src/lib/vendor.js + var require_vendor = __commonJS({ + "src/lib/vendor.js"(exports, module) { + var DEPENDENCIES = {}; + var getDependencies = () => { + return DEPENDENCIES; + }; + var setDependencies = (value) => { + Object.assign(DEPENDENCIES, value); + }; + Object.assign(module.exports, { getDependencies, setDependencies }); + } + }); + + // node_modules/lodash/lodash.js + var require_lodash = __commonJS({ + "node_modules/lodash/lodash.js"(exports, module) { + (function() { + var undefined2; + var VERSION2 = "4.17.21"; + var LARGE_ARRAY_SIZE = 200; + var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var MAX_MEMOIZE_SIZE = 500; + var PLACEHOLDER = "__lodash_placeholder__"; + var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; + var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; + var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; + var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; + var HOT_COUNT = 800, HOT_SPAN = 16; + var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; + var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; + var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + var wrapFlags = [ + ["ary", WRAP_ARY_FLAG], + ["bind", WRAP_BIND_FLAG], + ["bindKey", WRAP_BIND_KEY_FLAG], + ["curry", WRAP_CURRY_FLAG], + ["curryRight", WRAP_CURRY_RIGHT_FLAG], + ["flip", WRAP_FLIP_FLAG], + ["partial", WRAP_PARTIAL_FLAG], + ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], + ["rearg", WRAP_REARG_FLAG] + ]; + var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; + var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; + var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); + var reTrimStart = /^\s+/; + var reWhitespace = /\s/; + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + var reEscapeChar = /\\(\\)?/g; + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + var reFlags = /\w*$/; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsOctal = /^0o[0-7]+$/i; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var reNoMatch = /($^)/; + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; + var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ + rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", + rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", + rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, + rsUpper + "+" + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var contextProps = [ + "Array", + "Buffer", + "DataView", + "Date", + "Error", + "Float32Array", + "Float64Array", + "Function", + "Int8Array", + "Int16Array", + "Int32Array", + "Map", + "Math", + "Object", + "Promise", + "RegExp", + "Set", + "String", + "Symbol", + "TypeError", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "WeakMap", + "_", + "clearTimeout", + "isFinite", + "parseInt", + "setTimeout" + ]; + var templateCounter = -1; + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; + var deburredLetters = { + "\xC0": "A", + "\xC1": "A", + "\xC2": "A", + "\xC3": "A", + "\xC4": "A", + "\xC5": "A", + "\xE0": "a", + "\xE1": "a", + "\xE2": "a", + "\xE3": "a", + "\xE4": "a", + "\xE5": "a", + "\xC7": "C", + "\xE7": "c", + "\xD0": "D", + "\xF0": "d", + "\xC8": "E", + "\xC9": "E", + "\xCA": "E", + "\xCB": "E", + "\xE8": "e", + "\xE9": "e", + "\xEA": "e", + "\xEB": "e", + "\xCC": "I", + "\xCD": "I", + "\xCE": "I", + "\xCF": "I", + "\xEC": "i", + "\xED": "i", + "\xEE": "i", + "\xEF": "i", + "\xD1": "N", + "\xF1": "n", + "\xD2": "O", + "\xD3": "O", + "\xD4": "O", + "\xD5": "O", + "\xD6": "O", + "\xD8": "O", + "\xF2": "o", + "\xF3": "o", + "\xF4": "o", + "\xF5": "o", + "\xF6": "o", + "\xF8": "o", + "\xD9": "U", + "\xDA": "U", + "\xDB": "U", + "\xDC": "U", + "\xF9": "u", + "\xFA": "u", + "\xFB": "u", + "\xFC": "u", + "\xDD": "Y", + "\xFD": "y", + "\xFF": "y", + "\xC6": "Ae", + "\xE6": "ae", + "\xDE": "Th", + "\xFE": "th", + "\xDF": "ss", + "\u0100": "A", + "\u0102": "A", + "\u0104": "A", + "\u0101": "a", + "\u0103": "a", + "\u0105": "a", + "\u0106": "C", + "\u0108": "C", + "\u010A": "C", + "\u010C": "C", + "\u0107": "c", + "\u0109": "c", + "\u010B": "c", + "\u010D": "c", + "\u010E": "D", + "\u0110": "D", + "\u010F": "d", + "\u0111": "d", + "\u0112": "E", + "\u0114": "E", + "\u0116": "E", + "\u0118": "E", + "\u011A": "E", + "\u0113": "e", + "\u0115": "e", + "\u0117": "e", + "\u0119": "e", + "\u011B": "e", + "\u011C": "G", + "\u011E": "G", + "\u0120": "G", + "\u0122": "G", + "\u011D": "g", + "\u011F": "g", + "\u0121": "g", + "\u0123": "g", + "\u0124": "H", + "\u0126": "H", + "\u0125": "h", + "\u0127": "h", + "\u0128": "I", + "\u012A": "I", + "\u012C": "I", + "\u012E": "I", + "\u0130": "I", + "\u0129": "i", + "\u012B": "i", + "\u012D": "i", + "\u012F": "i", + "\u0131": "i", + "\u0134": "J", + "\u0135": "j", + "\u0136": "K", + "\u0137": "k", + "\u0138": "k", + "\u0139": "L", + "\u013B": "L", + "\u013D": "L", + "\u013F": "L", + "\u0141": "L", + "\u013A": "l", + "\u013C": "l", + "\u013E": "l", + "\u0140": "l", + "\u0142": "l", + "\u0143": "N", + "\u0145": "N", + "\u0147": "N", + "\u014A": "N", + "\u0144": "n", + "\u0146": "n", + "\u0148": "n", + "\u014B": "n", + "\u014C": "O", + "\u014E": "O", + "\u0150": "O", + "\u014D": "o", + "\u014F": "o", + "\u0151": "o", + "\u0154": "R", + "\u0156": "R", + "\u0158": "R", + "\u0155": "r", + "\u0157": "r", + "\u0159": "r", + "\u015A": "S", + "\u015C": "S", + "\u015E": "S", + "\u0160": "S", + "\u015B": "s", + "\u015D": "s", + "\u015F": "s", + "\u0161": "s", + "\u0162": "T", + "\u0164": "T", + "\u0166": "T", + "\u0163": "t", + "\u0165": "t", + "\u0167": "t", + "\u0168": "U", + "\u016A": "U", + "\u016C": "U", + "\u016E": "U", + "\u0170": "U", + "\u0172": "U", + "\u0169": "u", + "\u016B": "u", + "\u016D": "u", + "\u016F": "u", + "\u0171": "u", + "\u0173": "u", + "\u0174": "W", + "\u0175": "w", + "\u0176": "Y", + "\u0177": "y", + "\u0178": "Y", + "\u0179": "Z", + "\u017B": "Z", + "\u017D": "Z", + "\u017A": "z", + "\u017C": "z", + "\u017E": "z", + "\u0132": "IJ", + "\u0133": "ij", + "\u0152": "Oe", + "\u0153": "oe", + "\u0149": "'n", + "\u017F": "s" + }; + var htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + var htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: '"', + "'": "'" + }; + var stringEscapes = { + "\\": "\\", + "'": "'", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029" + }; + var freeParseFloat = parseFloat, freeParseInt = parseInt; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; + var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + var types = freeModule && freeModule.require && freeModule.require("util").types; + if (types) { + return types; + } + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e) { + } + }(); + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function apply(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); + case 1: + return func.call(thisArg, args[0]); + case 2: + return func.call(thisArg, args[0], args[1]); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + function arrayEach(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + function arrayEvery(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + function arrayFilter(array, predicate) { + var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + function arrayIncludesWith(array, value, comparator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + function arrayMap(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + function arrayPush(array, values) { + var index = -1, length = values.length, offset = array.length; + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + function arraySome(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + var asciiSize = baseProperty("length"); + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection2) { + if (predicate(value, key, collection2)) { + result = key; + return false; + } + }); + return result; + } + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + function baseIndexOf(array, value, fromIndex) { + return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); + } + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + function baseIsNaN(value) { + return value !== value; + } + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? baseSum(array, iteratee) / length : NAN; + } + function baseProperty(key) { + return function(object) { + return object == null ? undefined2 : object[key]; + }; + } + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined2 : object[key]; + }; + } + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection2) { + accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2); + }); + return accumulator; + } + function baseSortBy(array, comparer) { + var length = array.length; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + function baseSum(array, iteratee) { + var result, index = -1, length = array.length; + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined2) { + result = result === undefined2 ? current : result + current; + } + } + return result; + } + function baseTimes(n, iteratee) { + var index = -1, result = Array(n); + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + function baseTrim(string) { + return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; + } + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + function cacheHas(cache, key) { + return cache.has(key); + } + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, length = strSymbols.length; + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function countHolders(array, placeholder) { + var length = array.length, result = 0; + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + var deburrLetter = basePropertyOf(deburredLetters); + var escapeHtmlChar = basePropertyOf(htmlEscapes); + function escapeStringChar(chr) { + return "\\" + stringEscapes[chr]; + } + function getValue(object, key) { + return object == null ? undefined2 : object[key]; + } + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function iteratorToArray(iterator) { + var data, result = []; + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + function mapToArray(map) { + var index = -1, result = Array(map.size); + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + function replaceHolders(array, placeholder) { + var index = -1, length = array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + function setToArray(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + function setToPairs(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + function stringSize(string) { + return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); + } + function stringToArray(string) { + return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); + } + function trimmedEndIndex(string) { + var index = string.length; + while (index-- && reWhitespace.test(string.charAt(index))) { + } + return index; + } + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + var runInContext = function runInContext2(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError; + var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; + var coreJsData = context["__core-js_shared__"]; + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var idCounter = 0; + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + var nativeObjectToString = objectProto.toString; + var objectCtorString = funcToString.call(Object2); + var oldDash = root._; + var reIsNative = RegExp2("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); + var Buffer2 = moduleExports ? context.Buffer : undefined2, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : undefined2, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined2, symIterator = Symbol2 ? Symbol2.iterator : undefined2, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined2; + var defineProperty = function() { + try { + var func = getNative(Object2, "defineProperty"); + func({}, "", {}); + return func; + } catch (e) { + } + }(); + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined2, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse; + var DataView = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create"); + var metaMap = WeakMap && new WeakMap(); + var realNames = {}; + var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap); + var symbolProto = Symbol2 ? Symbol2.prototype : undefined2, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined2, symbolToString = symbolProto ? symbolProto.toString : undefined2; + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, "__wrapped__")) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + var baseCreate = function() { + function object() { + } + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result2 = new object(); + object.prototype = undefined2; + return result2; + }; + }(); + function baseLodash() { + } + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined2; + } + lodash.templateSettings = { + "escape": reEscape, + "evaluate": reEvaluate, + "interpolate": reInterpolate, + "variable": "", + "imports": { + "_": lodash + } + }; + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + function lazyClone() { + var result2 = new LazyWrapper(this.__wrapped__); + result2.__actions__ = copyArray(this.__actions__); + result2.__dir__ = this.__dir__; + result2.__filtered__ = this.__filtered__; + result2.__iteratees__ = copyArray(this.__iteratees__); + result2.__takeCount__ = this.__takeCount__; + result2.__views__ = copyArray(this.__views__); + return result2; + } + function lazyReverse() { + if (this.__filtered__) { + var result2 = new LazyWrapper(this); + result2.__dir__ = -1; + result2.__filtered__ = true; + } else { + result2 = this.clone(); + result2.__dir__ *= -1; + } + return result2; + } + function lazyValue() { + var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); + if (!isArr || !isRight && arrLength == length && takeCount == length) { + return baseWrapperValue(array, this.__actions__); + } + var result2 = []; + outer: + while (length-- && resIndex < takeCount) { + index += dir; + var iterIndex = -1, value = array[index]; + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value); + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result2[resIndex++] = value; + } + return result2; + } + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + function Hash(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + function hashDelete(key) { + var result2 = this.has(key) && delete this.__data__[key]; + this.size -= result2 ? 1 : 0; + return result2; + } + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result2 = data[key]; + return result2 === HASH_UNDEFINED ? undefined2 : result2; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined2; + } + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined2 : hasOwnProperty.call(data, key); + } + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === undefined2 ? HASH_UNDEFINED : value; + return this; + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + function ListCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? undefined2 : data[index][1]; + } + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + function MapCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + function mapCacheDelete(key) { + var result2 = getMapData(this, key)["delete"](key); + this.size -= result2 ? 1 : 0; + return result2; + } + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + function mapCacheSet(key, value) { + var data = getMapData(this, key), size2 = data.size; + data.set(key, value); + this.size += data.size == size2 ? 0 : 1; + return this; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + function SetCache(values2) { + var index = -1, length = values2 == null ? 0 : values2.length; + this.__data__ = new MapCache(); + while (++index < length) { + this.add(values2[index]); + } + } + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + function setCacheHas(value) { + return this.__data__.has(value); + } + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + function stackClear() { + this.__data__ = new ListCache(); + this.size = 0; + } + function stackDelete(key) { + var data = this.__data__, result2 = data["delete"](key); + this.size = data.size; + return result2; + } + function stackGet(key) { + return this.__data__.get(key); + } + function stackHas(key) { + return this.__data__.has(key); + } + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + Stack.prototype.clear = stackClear; + Stack.prototype["delete"] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { + result2.push(key); + } + } + return result2; + } + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined2; + } + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + function assignMergeValue(object, key, value) { + if (value !== undefined2 && !eq(object[key], value) || value === undefined2 && !(key in object)) { + baseAssignValue(object, key, value); + } + } + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined2 && !(key in object)) { + baseAssignValue(object, key, value); + } + } + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + function baseAggregator(collection, setter, iteratee2, accumulator) { + baseEach(collection, function(value, key, collection2) { + setter(accumulator, value, iteratee2(value), collection2); + }); + return accumulator; + } + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + function baseAssignValue(object, key, value) { + if (key == "__proto__" && defineProperty) { + defineProperty(object, key, { + "configurable": true, + "enumerable": true, + "value": value, + "writable": true + }); + } else { + object[key] = value; + } + } + function baseAt(object, paths) { + var index = -1, length = paths.length, result2 = Array2(length), skip = object == null; + while (++index < length) { + result2[index] = skip ? undefined2 : get(object, paths[index]); + } + return result2; + } + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined2) { + number = number <= upper ? number : upper; + } + if (lower !== undefined2) { + number = number >= lower ? number : lower; + } + } + return number; + } + function baseClone(value, bitmask, customizer, key, object, stack) { + var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; + if (customizer) { + result2 = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result2 !== undefined2) { + return result2; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result2 = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result2); + } + } else { + var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || isFunc && !object) { + result2 = isFlat || isFunc ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result2 = initCloneByTag(value, tag, isDeep); + } + } + stack || (stack = new Stack()); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result2); + if (isSet(value)) { + value.forEach(function(subValue) { + result2.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key2) { + result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); + }); + } + var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; + var props = isArr ? undefined2 : keysFunc(value); + arrayEach(props || value, function(subValue, key2) { + if (props) { + key2 = subValue; + subValue = value[key2]; + } + assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); + }); + return result2; + } + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object2(object); + while (length--) { + var key = props[length], predicate = source[key], value = object[key]; + if (value === undefined2 && !(key in object) || !predicate(value)) { + return false; + } + } + return true; + } + function baseDelay(func, wait, args) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return setTimeout(function() { + func.apply(undefined2, args); + }, wait); + } + function baseDifference(array, values2, iteratee2, comparator) { + var index = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values2.length; + if (!length) { + return result2; + } + if (iteratee2) { + values2 = arrayMap(values2, baseUnary(iteratee2)); + } + if (comparator) { + includes2 = arrayIncludesWith; + isCommon = false; + } else if (values2.length >= LARGE_ARRAY_SIZE) { + includes2 = cacheHas; + isCommon = false; + values2 = new SetCache(values2); + } + outer: + while (++index < length) { + var value = array[index], computed = iteratee2 == null ? value : iteratee2(value); + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values2[valuesIndex] === computed) { + continue outer; + } + } + result2.push(value); + } else if (!includes2(values2, computed, comparator)) { + result2.push(value); + } + } + return result2; + } + var baseEach = createBaseEach(baseForOwn); + var baseEachRight = createBaseEach(baseForOwnRight, true); + function baseEvery(collection, predicate) { + var result2 = true; + baseEach(collection, function(value, index, collection2) { + result2 = !!predicate(value, index, collection2); + return result2; + }); + return result2; + } + function baseExtremum(array, iteratee2, comparator) { + var index = -1, length = array.length; + while (++index < length) { + var value = array[index], current = iteratee2(value); + if (current != null && (computed === undefined2 ? current === current && !isSymbol(current) : comparator(current, computed))) { + var computed = current, result2 = value; + } + } + return result2; + } + function baseFill(array, value, start, end) { + var length = array.length; + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end === undefined2 || end > length ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + function baseFilter(collection, predicate) { + var result2 = []; + baseEach(collection, function(value, index, collection2) { + if (predicate(value, index, collection2)) { + result2.push(value); + } + }); + return result2; + } + function baseFlatten(array, depth, predicate, isStrict, result2) { + var index = -1, length = array.length; + predicate || (predicate = isFlattenable); + result2 || (result2 = []); + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + baseFlatten(value, depth - 1, predicate, isStrict, result2); + } else { + arrayPush(result2, value); + } + } else if (!isStrict) { + result2[result2.length] = value; + } + } + return result2; + } + var baseFor = createBaseFor(); + var baseForRight = createBaseFor(true); + function baseForOwn(object, iteratee2) { + return object && baseFor(object, iteratee2, keys); + } + function baseForOwnRight(object, iteratee2) { + return object && baseForRight(object, iteratee2, keys); + } + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + function baseGet(object, path) { + path = castPath(path, object); + var index = 0, length = path.length; + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return index && index == length ? object : undefined2; + } + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result2 = keysFunc(object); + return isArray(object) ? result2 : arrayPush(result2, symbolsFunc(object)); + } + function baseGetTag(value) { + if (value == null) { + return value === undefined2 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object2(value) ? getRawTag(value) : objectToString(value); + } + function baseGt(value, other) { + return value > other; + } + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + function baseHasIn(object, key) { + return object != null && key in Object2(object); + } + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + function baseIntersection(arrays, iteratee2, comparator) { + var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee2) { + array = arrayMap(array, baseUnary(iteratee2)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined2; + } + array = arrays[0]; + var index = -1, seen = caches[0]; + outer: + while (++index < length && result2.length < maxLength) { + var value = array[index], computed = iteratee2 ? iteratee2(value) : value; + value = comparator || value !== 0 ? value : 0; + if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache ? cacheHas(cache, computed) : includes2(arrays[othIndex], computed, comparator))) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result2.push(value); + } + } + return result2; + } + function baseInverter(object, setter, iteratee2, accumulator) { + baseForOwn(object, function(value, key, object2) { + setter(accumulator, iteratee2(value), key, object2); + }); + return accumulator; + } + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined2 : apply(func, object, args); + } + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()); + return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack()); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, length = index, noCustomizer = !customizer; + if (object == null) { + return !length; + } + object = Object2(object); + while (index--) { + var data = matchData[index]; + if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], objValue = object[key], srcValue = data[1]; + if (noCustomizer && data[2]) { + if (objValue === undefined2 && !(key in object)) { + return false; + } + } else { + var stack = new Stack(); + if (customizer) { + var result2 = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result2 === undefined2 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) { + return false; + } + } + } + return true; + } + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + function baseIteratee(value) { + if (typeof value == "function") { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == "object") { + return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); + } + return property(value); + } + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result2 = []; + for (var key in Object2(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result2.push(key); + } + } + return result2; + } + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), result2 = []; + for (var key in object) { + if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { + result2.push(key); + } + } + return result2; + } + function baseLt(value, other) { + return value < other; + } + function baseMap(collection, iteratee2) { + var index = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : []; + baseEach(collection, function(value, key, collection2) { + result2[++index] = iteratee2(value, key, collection2); + }); + return result2; + } + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return objValue === undefined2 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack()); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } else { + var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source, stack) : undefined2; + if (newValue === undefined2) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined2; + var isCommon = newValue === undefined2; + if (isCommon) { + var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } else { + newValue = []; + } + } else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } else { + isCommon = false; + } + } + if (isCommon) { + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack["delete"](srcValue); + } + assignMergeValue(object, key, newValue); + } + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined2; + } + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee2) { + if (isArray(iteratee2)) { + return function(value) { + return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2); + }; + } + return iteratee2; + }); + } else { + iteratees = [identity]; + } + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + var result2 = baseMap(collection, function(value, key, collection2) { + var criteria = arrayMap(iteratees, function(iteratee2) { + return iteratee2(value); + }); + return { "criteria": criteria, "index": ++index, "value": value }; + }); + return baseSortBy(result2, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + function basePickBy(object, paths, predicate) { + var index = -1, length = paths.length, result2 = {}; + while (++index < length) { + var path = paths[index], value = baseGet(object, path); + if (predicate(value, path)) { + baseSet(result2, castPath(path, object), value); + } + } + return result2; + } + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + function basePullAll(array, values2, iteratee2, comparator) { + var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values2.length, seen = array; + if (array === values2) { + values2 = copyArray(values2); + } + if (iteratee2) { + seen = arrayMap(array, baseUnary(iteratee2)); + } + while (++index < length) { + var fromIndex = 0, value = values2[index], computed = iteratee2 ? iteratee2(value) : value; + while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, lastIndex = length - 1; + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + function baseRange(start, end, step, fromRight) { + var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result2 = Array2(length); + while (length--) { + result2[fromRight ? length : ++index] = start; + start += step; + } + return result2; + } + function baseRepeat(string, n) { + var result2 = ""; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result2; + } + do { + if (n % 2) { + result2 += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + return result2; + } + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ""); + } + function baseSample(collection) { + return arraySample(values(collection)); + } + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + var index = -1, length = path.length, lastIndex = length - 1, nested = object; + while (nested != null && ++index < length) { + var key = toKey(path[index]), newValue = value; + if (key === "__proto__" || key === "constructor" || key === "prototype") { + return object; + } + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined2; + if (newValue === undefined2) { + newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, "toString", { + "configurable": true, + "enumerable": false, + "value": constant(string), + "writable": true + }); + }; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result2 = Array2(length); + while (++index < length) { + result2[index] = array[index + start]; + } + return result2; + } + function baseSome(collection, predicate) { + var result2; + baseEach(collection, function(value, index, collection2) { + result2 = predicate(value, index, collection2); + return !result2; + }); + return !!result2; + } + function baseSortedIndex(array, value, retHighest) { + var low = 0, high = array == null ? low : array.length; + if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = low + high >>> 1, computed = array[mid]; + if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + function baseSortedIndexBy(array, value, iteratee2, retHighest) { + var low = 0, high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + value = iteratee2(value); + var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined2; + while (low < high) { + var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined2, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? computed <= value : computed < value; + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + function baseSortedUniq(array, iteratee2) { + var index = -1, length = array.length, resIndex = 0, result2 = []; + while (++index < length) { + var value = array[index], computed = iteratee2 ? iteratee2(value) : value; + if (!index || !eq(computed, seen)) { + var seen = computed; + result2[resIndex++] = value === 0 ? 0 : value; + } + } + return result2; + } + function baseToNumber(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + function baseToString(value) { + if (typeof value == "string") { + return value; + } + if (isArray(value)) { + return arrayMap(value, baseToString) + ""; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ""; + } + var result2 = value + ""; + return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; + } + function baseUniq(array, iteratee2, comparator) { + var index = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2; + if (comparator) { + isCommon = false; + includes2 = arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE) { + var set2 = iteratee2 ? null : createSet(array); + if (set2) { + return setToArray(set2); + } + isCommon = false; + includes2 = cacheHas; + seen = new SetCache(); + } else { + seen = iteratee2 ? [] : result2; + } + outer: + while (++index < length) { + var value = array[index], computed = iteratee2 ? iteratee2(value) : value; + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee2) { + seen.push(computed); + } + result2.push(value); + } else if (!includes2(seen, computed, comparator)) { + if (seen !== result2) { + seen.push(computed); + } + result2.push(value); + } + } + return result2; + } + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, index = fromRight ? length : -1; + while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) { + } + return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); + } + function baseWrapperValue(value, actions) { + var result2 = value; + if (result2 instanceof LazyWrapper) { + result2 = result2.value(); + } + return arrayReduce(actions, function(result3, action) { + return action.func.apply(action.thisArg, arrayPush([result3], action.args)); + }, result2); + } + function baseXor(arrays, iteratee2, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, result2 = Array2(length); + while (++index < length) { + var array = arrays[index], othIndex = -1; + while (++othIndex < length) { + if (othIndex != index) { + result2[index] = baseDifference(result2[index] || array, arrays[othIndex], iteratee2, comparator); + } + } + } + return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); + } + function baseZipObject(props, values2, assignFunc) { + var index = -1, length = props.length, valsLength = values2.length, result2 = {}; + while (++index < length) { + var value = index < valsLength ? values2[index] : undefined2; + assignFunc(result2, props[index], value); + } + return result2; + } + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + function castFunction(value) { + return typeof value == "function" ? value : identity; + } + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + var castRest = baseRest; + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined2 ? length : end; + return !start && end >= length ? array : baseSlice(array, start, end); + } + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + buffer.copy(result2); + return result2; + } + function cloneArrayBuffer(arrayBuffer) { + var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer)); + return result2; + } + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + function cloneRegExp(regexp) { + var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result2.lastIndex = regexp.lastIndex; + return result2; + } + function cloneSymbol(symbol) { + return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {}; + } + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined2, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); + var othIsDefined = other !== undefined2, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); + if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { + return 1; + } + if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { + return -1; + } + } + return 0; + } + function compareMultiple(object, other, orders) { + var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; + while (++index < length) { + var result2 = compareAscending(objCriteria[index], othCriteria[index]); + if (result2) { + if (index >= ordersLength) { + return result2; + } + var order = orders[index]; + return result2 * (order == "desc" ? -1 : 1); + } + } + return object.index - other.index; + } + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried; + while (++leftIndex < leftLength) { + result2[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result2[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result2[leftIndex++] = args[argsIndex++]; + } + return result2; + } + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried; + while (++argsIndex < rangeLength) { + result2[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result2[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result2[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result2; + } + function copyArray(source, array) { + var index = -1, length = source.length; + array || (array = Array2(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + var index = -1, length = props.length; + while (++index < length) { + var key = props[index]; + var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined2; + if (newValue === undefined2) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + function createAggregator(setter, initializer) { + return function(collection, iteratee2) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; + return func(collection, setter, getIteratee(iteratee2, 2), accumulator); + }; + } + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined2, guard = length > 2 ? sources[2] : undefined2; + customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined2; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined2 : customizer; + length = 1; + } + object = Object2(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee2) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee2); + } + var length = collection.length, index = fromRight ? length : -1, iterable = Object2(collection); + while (fromRight ? index-- : ++index < length) { + if (iteratee2(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + function createBaseFor(fromRight) { + return function(object, iteratee2, keysFunc) { + var index = -1, iterable = Object2(object), props = keysFunc(object), length = props.length; + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee2(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined2; + var chr = strSymbols ? strSymbols[0] : string.charAt(0); + var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); + return chr[methodName]() + trailing; + }; + } + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); + }; + } + function createCtor(Ctor) { + return function() { + var args = arguments; + switch (args.length) { + case 0: + return new Ctor(); + case 1: + return new Ctor(args[0]); + case 2: + return new Ctor(args[0], args[1]); + case 3: + return new Ctor(args[0], args[1], args[2]); + case 4: + return new Ctor(args[0], args[1], args[2], args[3]); + case 5: + return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); + return isObject(result2) ? result2 : thisBinding; + }; + } + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + function wrapper() { + var length = arguments.length, args = Array2(length), index = length, placeholder = getHolder(wrapper); + while (index--) { + args[index] = arguments[index]; + } + var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); + length -= holders.length; + if (length < arity) { + return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined2, args, holders, undefined2, undefined2, arity - length); + } + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object2(collection); + if (!isArrayLike(collection)) { + var iteratee2 = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { + return iteratee2(iterable[key], key, iterable); + }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee2 ? collection[index] : index] : undefined2; + }; + } + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == "wrapper") { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined2; + if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); + } + } + return function() { + var args = arguments, value = args[0]; + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value; + while (++index2 < length) { + result2 = funcs[index2].call(this, result2); + } + return result2; + }; + }); + } + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined2 : createCtor(func); + function wrapper() { + var length = arguments.length, args = Array2(length), index = length; + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary2, arity - length); + } + var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary2 < length) { + args.length = ary2; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + function createInverter(setter, toIteratee) { + return function(object, iteratee2) { + return baseInverter(object, setter, toIteratee(iteratee2), {}); + }; + } + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result2; + if (value === undefined2 && other === undefined2) { + return defaultValue; + } + if (value !== undefined2) { + result2 = value; + } + if (other !== undefined2) { + if (result2 === undefined2) { + return other; + } + if (typeof value == "string" || typeof other == "string") { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result2 = operator(value, other); + } + return result2; + }; + } + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee2) { + return apply(iteratee2, thisArg, args); + }); + }); + }); + } + function createPadding(length, chars) { + chars = chars === undefined2 ? " " : baseToString(chars); + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); + } + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != "number" && isIterateeCall(start, end, step)) { + end = step = undefined2; + } + start = toFinite(start); + if (end === undefined2) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined2 ? start < end ? 1 : -1 : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == "string" && typeof other == "string")) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined2, newHoldersRight = isCurry ? undefined2 : holders, newPartials = isCurry ? partials : undefined2, newPartialsRight = isCurry ? undefined2 : partials; + bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, + bitmask, + thisArg, + newPartials, + newHolders, + newPartialsRight, + newHoldersRight, + argPos, + ary2, + arity + ]; + var result2 = wrapFunc.apply(undefined2, newData); + if (isLaziable(func)) { + setData(result2, newData); + } + result2.placeholder = placeholder; + return setWrapToString(result2, func, bitmask); + } + function createRound(methodName) { + var func = Math2[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); + pair = (toString(value) + "e").split("e"); + return +(pair[0] + "e" + (+pair[1] - precision)); + } + return func(number); + }; + } + var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values2) { + return new Set2(values2); + }; + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined2; + } + ary2 = ary2 === undefined2 ? ary2 : nativeMax(toInteger(ary2), 0); + arity = arity === undefined2 ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, holdersRight = holders; + partials = holders = undefined2; + } + var data = isBindKey ? undefined2 : getData(func); + var newData = [ + func, + bitmask, + thisArg, + partials, + holders, + partialsRight, + holdersRight, + argPos, + ary2, + arity + ]; + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined2 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result2 = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result2 = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result2 = createPartial(func, bitmask, thisArg, partials); + } else { + result2 = createHybrid.apply(undefined2, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result2, newData), func, bitmask); + } + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined2 || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { + return srcValue; + } + return objValue; + } + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined2, customDefaultsMerge, stack); + stack["delete"](srcValue); + } + return objValue; + } + function customOmitClone(value) { + return isPlainObject(value) ? undefined2 : value; + } + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined2; + stack.set(array, other); + stack.set(other, array); + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined2) { + if (compared) { + continue; + } + result2 = false; + break; + } + if (seen) { + if (!arraySome(other, function(othValue2, othIndex) { + if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result2 = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result2 = false; + break; + } + } + stack["delete"](array); + stack["delete"](other); + return result2; + } + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + object = object.buffer; + other = other.buffer; + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { + return false; + } + return true; + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + case errorTag: + return object.name == other.name && object.message == other.message; + case regexpTag: + case stringTag: + return object == other + ""; + case mapTag: + var convert = mapToArray; + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + if (object.size != other.size && !isPartial) { + return false; + } + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + stack.set(object, other); + var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack["delete"](object); + return result2; + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result2 = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } + if (!(compared === undefined2 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result2 = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result2 && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result2 = false; + } + } + stack["delete"](object); + stack["delete"](other); + return result2; + } + function flatRest(func) { + return setToString(overRest(func, undefined2, flatten), func + ""); + } + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + function getFuncName(func) { + var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty.call(realNames, result2) ? array.length : 0; + while (length--) { + var data = array[length], otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result2; + } + function getHolder(func) { + var object = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; + return object.placeholder; + } + function getIteratee() { + var result2 = lodash.iteratee || iteratee; + result2 = result2 === iteratee ? baseIteratee : result2; + return arguments.length ? result2(arguments[0], arguments[1]) : result2; + } + function getMapData(map2, key) { + var data = map2.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + function getMatchData(object) { + var result2 = keys(object), length = result2.length; + while (length--) { + var key = result2[length], value = object[key]; + result2[length] = [key, value, isStrictComparable(value)]; + } + return result2; + } + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined2; + } + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + try { + value[symToStringTag] = undefined2; + var unmasked = true; + } catch (e) { + } + var result2 = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result2; + } + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object2(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result2 = []; + while (object) { + arrayPush(result2, getSymbols(object)); + object = getPrototype(object); + } + return result2; + }; + var getTag = baseGetTag; + if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { + getTag = function(value) { + var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : undefined2, ctorString = Ctor ? toSource(Ctor) : ""; + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag; + case mapCtorString: + return mapTag; + case promiseCtorString: + return promiseTag; + case setCtorString: + return setTag; + case weakMapCtorString: + return weakMapTag; + } + } + return result2; + }; + } + function getView(start, end, transforms) { + var index = -1, length = transforms.length; + while (++index < length) { + var data = transforms[index], size2 = data.size; + switch (data.type) { + case "drop": + start += size2; + break; + case "dropRight": + end -= size2; + break; + case "take": + end = nativeMin(end, start + size2); + break; + case "takeRight": + start = nativeMax(start, end - size2); + break; + } + } + return { "start": start, "end": end }; + } + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + var index = -1, length = path.length, result2 = false; + while (++index < length) { + var key = toKey(path[index]); + if (!(result2 = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result2 || ++index != length) { + return result2; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); + } + function initCloneArray(array) { + var length = array.length, result2 = new array.constructor(length); + if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) { + result2.index = array.index; + result2.input = array.input; + } + return result2; + } + function initCloneObject(object) { + return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {}; + } + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + case boolTag: + case dateTag: + return new Ctor(+object); + case dataViewTag: + return cloneDataView(object, isDeep); + case float32Tag: + case float64Tag: + case int8Tag: + case int16Tag: + case int32Tag: + case uint8Tag: + case uint8ClampedTag: + case uint16Tag: + case uint32Tag: + return cloneTypedArray(object, isDeep); + case mapTag: + return new Ctor(); + case numberTag: + case stringTag: + return new Ctor(object); + case regexpTag: + return cloneRegExp(object); + case setTag: + return new Ctor(); + case symbolTag: + return cloneSymbol(object); + } + } + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; + details = details.join(length > 2 ? ", " : " "); + return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); + } + function isFlattenable(value) { + return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); + } + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); + } + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { + return eq(object[index], value); + } + return false; + } + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object2(object); + } + function isKeyable(value) { + var type = typeof value; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + } + function isLaziable(func) { + var funcName = getFuncName(func), other = lodash[funcName]; + if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + var isMaskable = coreJsData ? isFunction : stubFalse; + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + function isStrictComparable(value) { + return value === value && !isObject(value); + } + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && (srcValue !== undefined2 || key in Object2(object)); + }; + } + function memoizeCapped(func) { + var result2 = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + var cache = result2.cache; + return result2; + } + function mergeData(data, source) { + var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; + if (!(isCommon || isCombo)) { + return data; + } + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + value = source[7]; + if (value) { + data[7] = value; + } + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + if (data[9] == null) { + data[9] = source[9]; + } + data[0] = source[0]; + data[1] = newBitmask; + return data; + } + function nativeKeysIn(object) { + var result2 = []; + if (object != null) { + for (var key in Object2(object)) { + result2.push(key); + } + } + return result2; + } + function objectToString(value) { + return nativeObjectToString.call(value); + } + function overRest(func, start, transform2) { + start = nativeMax(start === undefined2 ? func.length - 1 : start, 0); + return function() { + var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array2(length); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array2(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform2(array); + return apply(func, this, otherArgs); + }; + } + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + function reorder(array, indexes) { + var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined2; + } + return array; + } + function safeGet(object, key) { + if (key === "constructor" && typeof object[key] === "function") { + return; + } + if (key == "__proto__") { + return; + } + return object[key]; + } + var setData = shortOut(baseSetData); + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + var setToString = shortOut(baseSetToString); + function setWrapToString(wrapper, reference, bitmask) { + var source = reference + ""; + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + function shortOut(func) { + var count = 0, lastCalled = 0; + return function() { + var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined2, arguments); + }; + } + function shuffleSelf(array, size2) { + var index = -1, length = array.length, lastIndex = length - 1; + size2 = size2 === undefined2 ? length : size2; + while (++index < size2) { + var rand = baseRandom(index, lastIndex), value = array[rand]; + array[rand] = array[index]; + array[index] = value; + } + array.length = size2; + return array; + } + var stringToPath = memoizeCapped(function(string) { + var result2 = []; + if (string.charCodeAt(0) === 46) { + result2.push(""); + } + string.replace(rePropName, function(match, number, quote, subString) { + result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); + }); + return result2; + }); + function toKey(value) { + if (typeof value == "string" || isSymbol(value)) { + return value; + } + var result2 = value + ""; + return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; + } + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) { + } + try { + return func + ""; + } catch (e) { + } + } + return ""; + } + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = "_." + pair[0]; + if (bitmask & pair[1] && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result2.__actions__ = copyArray(wrapper.__actions__); + result2.__index__ = wrapper.__index__; + result2.__values__ = wrapper.__values__; + return result2; + } + function chunk(array, size2, guard) { + if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined2) { + size2 = 1; + } else { + size2 = nativeMax(toInteger(size2), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size2 < 1) { + return []; + } + var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); + while (index < length) { + result2[resIndex++] = baseSlice(array, index, index += size2); + } + return result2; + } + function compact(array) { + var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = []; + while (++index < length) { + var value = array[index]; + if (value) { + result2[resIndex++] = value; + } + } + return result2; + } + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array2(length - 1), array = arguments[0], index = length; + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + var difference = baseRest(function(array, values2) { + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; + }); + var differenceBy = baseRest(function(array, values2) { + var iteratee2 = last(values2); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined2; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : []; + }); + var differenceWith = baseRest(function(array, values2) { + var comparator = last(values2); + if (isArrayLikeObject(comparator)) { + comparator = undefined2; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined2, comparator) : []; + }); + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = guard || n === undefined2 ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = guard || n === undefined2 ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + function dropRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; + } + function dropWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; + } + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != "number" && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined2) { + index = toInteger(fromIndex); + index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined2 ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + function fromPairs(pairs) { + var index = -1, length = pairs == null ? 0 : pairs.length, result2 = {}; + while (++index < length) { + var pair = pairs[index]; + result2[pair[0]] = pair[1]; + } + return result2; + } + function head(array) { + return array && array.length ? array[0] : undefined2; + } + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; + }); + var intersectionBy = baseRest(function(arrays) { + var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + if (iteratee2 === last(mapped)) { + iteratee2 = undefined2; + } else { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : []; + }); + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + comparator = typeof comparator == "function" ? comparator : undefined2; + if (comparator) { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined2, comparator) : []; + }); + function join(array, separator) { + return array == null ? "" : nativeJoin.call(array, separator); + } + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined2; + } + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined2) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); + } + function nth(array, n) { + return array && array.length ? baseNth(array, toInteger(n)) : undefined2; + } + var pull = baseRest(pullAll); + function pullAll(array, values2) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array; + } + function pullAllBy(array, values2, iteratee2) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array; + } + function pullAllWith(array, values2, comparator) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined2, comparator) : array; + } + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes); + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + return result2; + }); + function remove(array, predicate) { + var result2 = []; + if (!(array && array.length)) { + return result2; + } + var index = -1, indexes = [], length = array.length; + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result2.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result2; + } + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != "number" && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } else { + start = start == null ? 0 : toInteger(start); + end = end === undefined2 ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + function sortedIndexBy(array, value, iteratee2) { + return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2)); + } + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + function sortedLastIndexBy(array, value, iteratee2) { + return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2), true); + } + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + function sortedUniq(array) { + return array && array.length ? baseSortedUniq(array) : []; + } + function sortedUniqBy(array, iteratee2) { + return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : []; + } + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = guard || n === undefined2 ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = guard || n === undefined2 ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + function takeRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; + } + function takeWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; + } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + var unionBy = baseRest(function(arrays) { + var iteratee2 = last(arrays); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined2; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)); + }); + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == "function" ? comparator : undefined2; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined2, comparator); + }); + function uniq(array) { + return array && array.length ? baseUniq(array) : []; + } + function uniqBy(array, iteratee2) { + return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : []; + } + function uniqWith(array, comparator) { + comparator = typeof comparator == "function" ? comparator : undefined2; + return array && array.length ? baseUniq(array, undefined2, comparator) : []; + } + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + function unzipWith(array, iteratee2) { + if (!(array && array.length)) { + return []; + } + var result2 = unzip(array); + if (iteratee2 == null) { + return result2; + } + return arrayMap(result2, function(group) { + return apply(iteratee2, undefined2, group); + }); + } + var without = baseRest(function(array, values2) { + return isArrayLikeObject(array) ? baseDifference(array, values2) : []; + }); + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + var xorBy = baseRest(function(arrays) { + var iteratee2 = last(arrays); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined2; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2)); + }); + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == "function" ? comparator : undefined2; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined2, comparator); + }); + var zip = baseRest(unzip); + function zipObject(props, values2) { + return baseZipObject(props || [], values2 || [], assignValue); + } + function zipObjectDeep(props, values2) { + return baseZipObject(props || [], values2 || [], baseSet); + } + var zipWith = baseRest(function(arrays) { + var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined2; + iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined2; + return unzipWith(arrays, iteratee2); + }); + function chain(value) { + var result2 = lodash(value); + result2.__chain__ = true; + return result2; + } + function tap(value, interceptor) { + interceptor(value); + return value; + } + function thru(value, interceptor) { + return interceptor(value); + } + var wrapperAt = flatRest(function(paths) { + var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { + return baseAt(object, paths); + }; + if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + "func": thru, + "args": [interceptor], + "thisArg": undefined2 + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined2); + } + return array; + }); + }); + function wrapperChain() { + return chain(this); + } + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + function wrapperNext() { + if (this.__values__ === undefined2) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, value = done ? undefined2 : this.__values__[this.__index__++]; + return { "done": done, "value": value }; + } + function wrapperToIterator() { + return this; + } + function wrapperPlant(value) { + var result2, parent2 = this; + while (parent2 instanceof baseLodash) { + var clone2 = wrapperClone(parent2); + clone2.__index__ = 0; + clone2.__values__ = undefined2; + if (result2) { + previous.__wrapped__ = clone2; + } else { + result2 = clone2; + } + var previous = clone2; + parent2 = parent2.__wrapped__; + } + previous.__wrapped__ = value; + return result2; + } + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + "func": thru, + "args": [reverse], + "thisArg": undefined2 + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + var countBy = createAggregator(function(result2, value, key) { + if (hasOwnProperty.call(result2, key)) { + ++result2[key]; + } else { + baseAssignValue(result2, key, 1); + } + }); + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined2; + } + return func(collection, getIteratee(predicate, 3)); + } + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + var find = createFind(findIndex); + var findLast = createFind(findLastIndex); + function flatMap(collection, iteratee2) { + return baseFlatten(map(collection, iteratee2), 1); + } + function flatMapDeep(collection, iteratee2) { + return baseFlatten(map(collection, iteratee2), INFINITY); + } + function flatMapDepth(collection, iteratee2, depth) { + depth = depth === undefined2 ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee2), depth); + } + function forEach(collection, iteratee2) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee2, 3)); + } + function forEachRight(collection, iteratee2) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee2, 3)); + } + var groupBy = createAggregator(function(result2, value, key) { + if (hasOwnProperty.call(result2, key)) { + result2[key].push(value); + } else { + baseAssignValue(result2, key, [value]); + } + }); + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; + } + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, isFunc = typeof path == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : []; + baseEach(collection, function(value) { + result2[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result2; + }); + var keyBy = createAggregator(function(result2, value, key) { + baseAssignValue(result2, key, value); + }); + function map(collection, iteratee2) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee2, 3)); + } + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined2 : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + var partition = createAggregator(function(result2, value, key) { + result2[key ? 0 : 1].push(value); + }, function() { + return [[], []]; + }); + function reduce(collection, iteratee2, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); + } + function reduceRight(collection, iteratee2, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); + } + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + function sampleSize(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n === undefined2) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined2; + } + return func(collection, getIteratee(predicate, 3)); + } + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + var now = ctxNow || function() { + return root.Date.now(); + }; + function after(n, func) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + function ary(func, n, guard) { + n = guard ? undefined2 : n; + n = func && n == null ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined2, undefined2, undefined2, undefined2, n); + } + function before(n, func) { + var result2; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result2 = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined2; + } + return result2; + }; + } + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + function curry(func, arity, guard) { + arity = guard ? undefined2 : arity; + var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); + result2.placeholder = curry.placeholder; + return result2; + } + function curryRight(func, arity, guard) { + arity = guard ? undefined2 : arity; + var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); + result2.placeholder = curryRight.placeholder; + return result2; + } + function debounce(func, wait, options) { + var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = "maxWait" in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + function invokeFunc(time) { + var args = lastArgs, thisArg = lastThis; + lastArgs = lastThis = undefined2; + lastInvokeTime = time; + result2 = func.apply(thisArg, args); + return result2; + } + function leadingEdge(time) { + lastInvokeTime = time; + timerId = setTimeout(timerExpired, wait); + return leading ? invokeFunc(time) : result2; + } + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; + return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; + } + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; + return lastCallTime === undefined2 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; + } + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + timerId = setTimeout(timerExpired, remainingWait(time)); + } + function trailingEdge(time) { + timerId = undefined2; + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined2; + return result2; + } + function cancel() { + if (timerId !== undefined2) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined2; + } + function flush() { + return timerId === undefined2 ? result2 : trailingEdge(now()); + } + function debounced() { + var time = now(), isInvoking = shouldInvoke(time); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + if (isInvoking) { + if (timerId === undefined2) { + return leadingEdge(lastCallTime); + } + if (maxing) { + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined2) { + timerId = setTimeout(timerExpired, wait); + } + return result2; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + function memoize(func, resolver) { + if (typeof func != "function" || resolver != null && typeof resolver != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; + if (cache.has(key)) { + return cache.get(key); + } + var result2 = func.apply(this, args); + memoized.cache = cache.set(key, result2) || cache; + return result2; + }; + memoized.cache = new (memoize.Cache || MapCache)(); + return memoized; + } + memoize.Cache = MapCache; + function negate(predicate) { + if (typeof predicate != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: + return !predicate.call(this); + case 1: + return !predicate.call(this, args[0]); + case 2: + return !predicate.call(this, args[0], args[1]); + case 3: + return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + function once(func) { + return before(2, func); + } + var overArgs = castRest(function(func, transforms) { + transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, length = nativeMin(args.length, funcsLength); + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined2, partials, holders); + }); + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined2, partials, holders); + }); + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined2, undefined2, undefined2, indexes); + }); + function rest(func, start) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + start = start === undefined2 ? start : toInteger(start); + return baseRest(func, start); + } + function spread(func, start) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], otherArgs = castSlice(args, 0, start); + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + function throttle(func, wait, options) { + var leading = true, trailing = true; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = "leading" in options ? !!options.leading : leading; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + "leading": leading, + "maxWait": wait, + "trailing": trailing + }); + } + function unary(func) { + return ary(func, 1); + } + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + function cloneWith(value, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + function eq(value, other) { + return value === other || value !== value && other !== other; + } + var gt = createRelationalOperation(baseGt); + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + var isArguments = baseIsArguments(function() { + return arguments; + }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; + var isArray = Array2.isArray; + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + function isBoolean(value) { + return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag; + } + var isBuffer = nativeIsBuffer || stubFalse; + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + function isEqual(value, other) { + return baseIsEqual(value, other); + } + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + var result2 = customizer ? customizer(value, other) : undefined2; + return result2 === undefined2 ? baseIsEqual(value, other, undefined2, customizer) : !!result2; + } + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); + } + function isFinite2(value) { + return typeof value == "number" && nativeIsFinite(value); + } + function isFunction(value) { + if (!isObject(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + function isInteger(value) { + return typeof value == "number" && value == toInteger(value); + } + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + function isObject(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + function isNaN2(value) { + return isNumber(value) && value != +value; + } + function isNative(value) { + if (isMaskable(value)) { + throw new Error2(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + function isNull(value) { + return value === null; + } + function isNil(value) { + return value == null; + } + function isNumber(value) { + return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag; + } + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; + } + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function isString(value) { + return typeof value == "string" || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag; + } + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; + } + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function isUndefined(value) { + return value === undefined2; + } + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + var lt = createRelationalOperation(baseLt); + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; + return func(value); + } + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + function toInteger(value) { + var result2 = toFinite(value), remainder = result2 % 1; + return result2 === result2 ? remainder ? result2 - remainder : result2 : 0; + } + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + function toNumber(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + } + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + function toSafeInteger(value) { + return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0; + } + function toString(value) { + return value == null ? "" : baseToString(value); + } + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + var at = flatRest(baseAt); + function create(prototype, properties) { + var result2 = baseCreate(prototype); + return properties == null ? result2 : baseAssign(result2, properties); + } + var defaults = baseRest(function(object, sources) { + object = Object2(object); + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined2; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + if (value === undefined2 || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) { + object[key] = source[key]; + } + } + } + return object; + }); + var defaultsDeep = baseRest(function(args) { + args.push(undefined2, customDefaultsMerge); + return apply(mergeWith, undefined2, args); + }); + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + function forIn(object, iteratee2) { + return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn); + } + function forInRight(object, iteratee2) { + return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn); + } + function forOwn(object, iteratee2) { + return object && baseForOwn(object, getIteratee(iteratee2, 3)); + } + function forOwnRight(object, iteratee2) { + return object && baseForOwnRight(object, getIteratee(iteratee2, 3)); + } + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + function get(object, path, defaultValue) { + var result2 = object == null ? undefined2 : baseGet(object, path); + return result2 === undefined2 ? defaultValue : result2; + } + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + var invert = createInverter(function(result2, value, key) { + if (value != null && typeof value.toString != "function") { + value = nativeObjectToString.call(value); + } + result2[value] = key; + }, constant(identity)); + var invertBy = createInverter(function(result2, value, key) { + if (value != null && typeof value.toString != "function") { + value = nativeObjectToString.call(value); + } + if (hasOwnProperty.call(result2, value)) { + result2[value].push(key); + } else { + result2[value] = [key]; + } + }, getIteratee); + var invoke = baseRest(baseInvoke); + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + function mapKeys(object, iteratee2) { + var result2 = {}; + iteratee2 = getIteratee(iteratee2, 3); + baseForOwn(object, function(value, key, object2) { + baseAssignValue(result2, iteratee2(value, key, object2), value); + }); + return result2; + } + function mapValues(object, iteratee2) { + var result2 = {}; + iteratee2 = getIteratee(iteratee2, 3); + baseForOwn(object, function(value, key, object2) { + baseAssignValue(result2, key, iteratee2(value, key, object2)); + }); + return result2; + } + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + var omit = flatRest(function(object, paths) { + var result2 = {}; + if (object == null) { + return result2; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result2); + if (isDeep) { + result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result2, paths[length]); + } + return result2; + }); + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + function result(object, path, defaultValue) { + path = castPath(path, object); + var index = -1, length = path.length; + if (!length) { + length = 1; + object = undefined2; + } + while (++index < length) { + var value = object == null ? undefined2 : object[toKey(path[index])]; + if (value === undefined2) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + function setWith(object, path, value, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + return object == null ? object : baseSet(object, path, value, customizer); + } + var toPairs = createToPairs(keys); + var toPairsIn = createToPairs(keysIn); + function transform(object, iteratee2, accumulator) { + var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); + iteratee2 = getIteratee(iteratee2, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor() : []; + } else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object2) { + return iteratee2(accumulator, value, index, object2); + }); + return accumulator; + } + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined2; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + function clamp(number, lower, upper) { + if (upper === undefined2) { + upper = lower; + lower = undefined2; + } + if (upper !== undefined2) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined2) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined2) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + function random(lower, upper, floating) { + if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined2; + } + if (floating === undefined2) { + if (typeof upper == "boolean") { + floating = upper; + upper = undefined2; + } else if (typeof lower == "boolean") { + floating = lower; + lower = undefined2; + } + } + if (lower === undefined2 && upper === undefined2) { + lower = 0; + upper = 1; + } else { + lower = toFinite(lower); + if (upper === undefined2) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); + } + return baseRandom(lower, upper); + } + var camelCase = createCompounder(function(result2, word, index) { + word = word.toLowerCase(); + return result2 + (index ? capitalize(word) : word); + }); + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); + } + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + var length = string.length; + position = position === undefined2 ? length : baseClamp(toInteger(position), 0, length); + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + function escape(string) { + string = toString(string); + return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; + } + function escapeRegExp(string) { + string = toString(string); + return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; + } + var kebabCase = createCompounder(function(result2, word, index) { + return result2 + (index ? "-" : "") + word.toLowerCase(); + }); + var lowerCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + word.toLowerCase(); + }); + var lowerFirst = createCaseFirst("toLowerCase"); + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); + } + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? string + createPadding(length - strLength, chars) : string; + } + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? createPadding(length - strLength, chars) + string : string; + } + function parseInt2(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); + } + function repeat(string, n, guard) { + if (guard ? isIterateeCall(string, n, guard) : n === undefined2) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + function replace() { + var args = arguments, string = toString(args[0]); + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + var snakeCase = createCompounder(function(result2, word, index) { + return result2 + (index ? "_" : "") + word.toLowerCase(); + }); + function split(string, separator, limit) { + if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { + separator = limit = undefined2; + } + limit = limit === undefined2 ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + var startCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + upperFirst(word); + }); + function startsWith(string, target, position) { + string = toString(string); + position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + function template(string, options, guard) { + var settings = lodash.templateSettings; + if (guard && isIterateeCall(string, options, guard)) { + options = undefined2; + } + string = toString(string); + options = assignInWith({}, options, settings, customDefaultsAssignIn); + var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); + var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; + var reDelimiters = RegExp2((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); + var sourceURL = "//# sourceURL=" + (hasOwnProperty.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; + string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { + interpolateValue || (interpolateValue = esTemplateValue); + source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); + if (escapeValue) { + isEscaping = true; + source += "' +\n__e(" + escapeValue + ") +\n'"; + } + if (evaluateValue) { + isEvaluating = true; + source += "';\n" + evaluateValue + ";\n__p += '"; + } + if (interpolateValue) { + source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + var variable = hasOwnProperty.call(options, "variable") && options.variable; + if (!variable) { + source = "with (obj) {\n" + source + "\n}\n"; + } else if (reForbiddenIdentifierChars.test(variable)) { + throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT); + } + source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); + source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; + var result2 = attempt(function() { + return Function2(importsKeys, sourceURL + "return " + source).apply(undefined2, importsValues); + }); + result2.source = source; + if (isError(result2)) { + throw result2; + } + return result2; + } + function toLower(value) { + return toString(value).toLowerCase(); + } + function toUpper(value) { + return toString(value).toUpperCase(); + } + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined2)) { + return baseTrim(string); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; + return castSlice(strSymbols, start, end).join(""); + } + function trimEnd(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined2)) { + return string.slice(0, trimmedEndIndex(string) + 1); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; + return castSlice(strSymbols, 0, end).join(""); + } + function trimStart(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined2)) { + return string.replace(reTrimStart, ""); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); + return castSlice(strSymbols, start).join(""); + } + function truncate(string, options) { + var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; + if (isObject(options)) { + var separator = "separator" in options ? options.separator : separator; + length = "length" in options ? toInteger(options.length) : length; + omission = "omission" in options ? baseToString(options.omission) : omission; + } + string = toString(string); + var strLength = string.length; + if (hasUnicode(string)) { + var strSymbols = stringToArray(string); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result2 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end); + if (separator === undefined2) { + return result2 + omission; + } + if (strSymbols) { + end += result2.length - end; + } + if (isRegExp(separator)) { + if (string.slice(end).search(separator)) { + var match, substring = result2; + if (!separator.global) { + separator = RegExp2(separator.source, toString(reFlags.exec(separator)) + "g"); + } + separator.lastIndex = 0; + while (match = separator.exec(substring)) { + var newEnd = match.index; + } + result2 = result2.slice(0, newEnd === undefined2 ? end : newEnd); + } + } else if (string.indexOf(baseToString(separator), end) != end) { + var index = result2.lastIndexOf(separator); + if (index > -1) { + result2 = result2.slice(0, index); + } + } + return result2 + omission; + } + function unescape(string) { + string = toString(string); + return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; + } + var upperCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + word.toUpperCase(); + }); + var upperFirst = createCaseFirst("toUpperCase"); + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined2 : pattern; + if (pattern === undefined2) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } + var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined2, args); + } catch (e) { + return isError(e) ? e : new Error2(e); + } + }); + var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; + }); + function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return [toIteratee(pair[0]), pair[1]]; + }); + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); + } + function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); + } + function constant(value) { + return function() { + return value; + }; + } + function defaultTo(value, defaultValue) { + return value == null || value !== value ? defaultValue : value; + } + var flow = createFlow(); + var flowRight = createFlow(true); + function identity(value) { + return value; + } + function iteratee(func) { + return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)); + } + function matches(source) { + return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); + } + function matchesProperty(path, srcValue) { + return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); + } + var method = baseRest(function(path, args) { + return function(object) { + return baseInvoke(object, path, args); + }; + }); + var methodOf = baseRest(function(object, args) { + return function(path) { + return baseInvoke(object, path, args); + }; + }); + function mixin(object, source, options) { + var props = keys(source), methodNames = baseFunctions(source, props); + if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain2 = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction(object); + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain2 || chainAll) { + var result2 = object(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__); + actions.push({ "func": func, "args": arguments, "thisArg": object }); + result2.__chain__ = chainAll; + return result2; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + return object; + } + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + function noop() { + } + function nthArg(n) { + n = toInteger(n); + return baseRest(function(args) { + return baseNth(args, n); + }); + } + var over = createOver(arrayMap); + var overEvery = createOver(arrayEvery); + var overSome = createOver(arraySome); + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + function propertyOf(object) { + return function(path) { + return object == null ? undefined2 : baseGet(object, path); + }; + } + var range = createRange(); + var rangeRight = createRange(true); + function stubArray() { + return []; + } + function stubFalse() { + return false; + } + function stubObject() { + return {}; + } + function stubString() { + return ""; + } + function stubTrue() { + return true; + } + function times(n, iteratee2) { + n = toInteger(n); + if (n < 1 || n > MAX_SAFE_INTEGER) { + return []; + } + var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); + iteratee2 = getIteratee(iteratee2); + n -= MAX_ARRAY_LENGTH; + var result2 = baseTimes(length, iteratee2); + while (++index < n) { + iteratee2(index); + } + return result2; + } + function toPath(value) { + if (isArray(value)) { + return arrayMap(value, toKey); + } + return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); + } + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + var add = createMathOperation(function(augend, addend) { + return augend + addend; + }, 0); + var ceil = createRound("ceil"); + var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; + }, 1); + var floor = createRound("floor"); + function max(array) { + return array && array.length ? baseExtremum(array, identity, baseGt) : undefined2; + } + function maxBy(array, iteratee2) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined2; + } + function mean(array) { + return baseMean(array, identity); + } + function meanBy(array, iteratee2) { + return baseMean(array, getIteratee(iteratee2, 2)); + } + function min(array) { + return array && array.length ? baseExtremum(array, identity, baseLt) : undefined2; + } + function minBy(array, iteratee2) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined2; + } + var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; + }, 1); + var round = createRound("round"); + var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; + }, 0); + function sum(array) { + return array && array.length ? baseSum(array, identity) : 0; + } + function sumBy(array, iteratee2) { + return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0; + } + lodash.after = after; + lodash.ary = ary; + lodash.assign = assign; + lodash.assignIn = assignIn; + lodash.assignInWith = assignInWith; + lodash.assignWith = assignWith; + lodash.at = at; + lodash.before = before; + lodash.bind = bind; + lodash.bindAll = bindAll; + lodash.bindKey = bindKey; + lodash.castArray = castArray; + lodash.chain = chain; + lodash.chunk = chunk; + lodash.compact = compact; + lodash.concat = concat; + lodash.cond = cond; + lodash.conforms = conforms; + lodash.constant = constant; + lodash.countBy = countBy; + lodash.create = create; + lodash.curry = curry; + lodash.curryRight = curryRight; + lodash.debounce = debounce; + lodash.defaults = defaults; + lodash.defaultsDeep = defaultsDeep; + lodash.defer = defer; + lodash.delay = delay; + lodash.difference = difference; + lodash.differenceBy = differenceBy; + lodash.differenceWith = differenceWith; + lodash.drop = drop; + lodash.dropRight = dropRight; + lodash.dropRightWhile = dropRightWhile; + lodash.dropWhile = dropWhile; + lodash.fill = fill; + lodash.filter = filter; + lodash.flatMap = flatMap; + lodash.flatMapDeep = flatMapDeep; + lodash.flatMapDepth = flatMapDepth; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.flattenDepth = flattenDepth; + lodash.flip = flip; + lodash.flow = flow; + lodash.flowRight = flowRight; + lodash.fromPairs = fromPairs; + lodash.functions = functions; + lodash.functionsIn = functionsIn; + lodash.groupBy = groupBy; + lodash.initial = initial; + lodash.intersection = intersection; + lodash.intersectionBy = intersectionBy; + lodash.intersectionWith = intersectionWith; + lodash.invert = invert; + lodash.invertBy = invertBy; + lodash.invokeMap = invokeMap; + lodash.iteratee = iteratee; + lodash.keyBy = keyBy; + lodash.keys = keys; + lodash.keysIn = keysIn; + lodash.map = map; + lodash.mapKeys = mapKeys; + lodash.mapValues = mapValues; + lodash.matches = matches; + lodash.matchesProperty = matchesProperty; + lodash.memoize = memoize; + lodash.merge = merge; + lodash.mergeWith = mergeWith; + lodash.method = method; + lodash.methodOf = methodOf; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.nthArg = nthArg; + lodash.omit = omit; + lodash.omitBy = omitBy; + lodash.once = once; + lodash.orderBy = orderBy; + lodash.over = over; + lodash.overArgs = overArgs; + lodash.overEvery = overEvery; + lodash.overSome = overSome; + lodash.partial = partial; + lodash.partialRight = partialRight; + lodash.partition = partition; + lodash.pick = pick; + lodash.pickBy = pickBy; + lodash.property = property; + lodash.propertyOf = propertyOf; + lodash.pull = pull; + lodash.pullAll = pullAll; + lodash.pullAllBy = pullAllBy; + lodash.pullAllWith = pullAllWith; + lodash.pullAt = pullAt; + lodash.range = range; + lodash.rangeRight = rangeRight; + lodash.rearg = rearg; + lodash.reject = reject; + lodash.remove = remove; + lodash.rest = rest; + lodash.reverse = reverse; + lodash.sampleSize = sampleSize; + lodash.set = set; + lodash.setWith = setWith; + lodash.shuffle = shuffle; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.sortedUniq = sortedUniq; + lodash.sortedUniqBy = sortedUniqBy; + lodash.split = split; + lodash.spread = spread; + lodash.tail = tail; + lodash.take = take; + lodash.takeRight = takeRight; + lodash.takeRightWhile = takeRightWhile; + lodash.takeWhile = takeWhile; + lodash.tap = tap; + lodash.throttle = throttle; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.toPairs = toPairs; + lodash.toPairsIn = toPairsIn; + lodash.toPath = toPath; + lodash.toPlainObject = toPlainObject; + lodash.transform = transform; + lodash.unary = unary; + lodash.union = union; + lodash.unionBy = unionBy; + lodash.unionWith = unionWith; + lodash.uniq = uniq; + lodash.uniqBy = uniqBy; + lodash.uniqWith = uniqWith; + lodash.unset = unset; + lodash.unzip = unzip; + lodash.unzipWith = unzipWith; + lodash.update = update; + lodash.updateWith = updateWith; + lodash.values = values; + lodash.valuesIn = valuesIn; + lodash.without = without; + lodash.words = words; + lodash.wrap = wrap; + lodash.xor = xor; + lodash.xorBy = xorBy; + lodash.xorWith = xorWith; + lodash.zip = zip; + lodash.zipObject = zipObject; + lodash.zipObjectDeep = zipObjectDeep; + lodash.zipWith = zipWith; + lodash.entries = toPairs; + lodash.entriesIn = toPairsIn; + lodash.extend = assignIn; + lodash.extendWith = assignInWith; + mixin(lodash, lodash); + lodash.add = add; + lodash.attempt = attempt; + lodash.camelCase = camelCase; + lodash.capitalize = capitalize; + lodash.ceil = ceil; + lodash.clamp = clamp; + lodash.clone = clone; + lodash.cloneDeep = cloneDeep; + lodash.cloneDeepWith = cloneDeepWith; + lodash.cloneWith = cloneWith; + lodash.conformsTo = conformsTo; + lodash.deburr = deburr; + lodash.defaultTo = defaultTo; + lodash.divide = divide; + lodash.endsWith = endsWith; + lodash.eq = eq; + lodash.escape = escape; + lodash.escapeRegExp = escapeRegExp; + lodash.every = every; + lodash.find = find; + lodash.findIndex = findIndex; + lodash.findKey = findKey; + lodash.findLast = findLast; + lodash.findLastIndex = findLastIndex; + lodash.findLastKey = findLastKey; + lodash.floor = floor; + lodash.forEach = forEach; + lodash.forEachRight = forEachRight; + lodash.forIn = forIn; + lodash.forInRight = forInRight; + lodash.forOwn = forOwn; + lodash.forOwnRight = forOwnRight; + lodash.get = get; + lodash.gt = gt; + lodash.gte = gte; + lodash.has = has; + lodash.hasIn = hasIn; + lodash.head = head; + lodash.identity = identity; + lodash.includes = includes; + lodash.indexOf = indexOf; + lodash.inRange = inRange; + lodash.invoke = invoke; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isArrayBuffer = isArrayBuffer; + lodash.isArrayLike = isArrayLike; + lodash.isArrayLikeObject = isArrayLikeObject; + lodash.isBoolean = isBoolean; + lodash.isBuffer = isBuffer; + lodash.isDate = isDate; + lodash.isElement = isElement; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isEqualWith = isEqualWith; + lodash.isError = isError; + lodash.isFinite = isFinite2; + lodash.isFunction = isFunction; + lodash.isInteger = isInteger; + lodash.isLength = isLength; + lodash.isMap = isMap; + lodash.isMatch = isMatch; + lodash.isMatchWith = isMatchWith; + lodash.isNaN = isNaN2; + lodash.isNative = isNative; + lodash.isNil = isNil; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isObjectLike = isObjectLike; + lodash.isPlainObject = isPlainObject; + lodash.isRegExp = isRegExp; + lodash.isSafeInteger = isSafeInteger; + lodash.isSet = isSet; + lodash.isString = isString; + lodash.isSymbol = isSymbol; + lodash.isTypedArray = isTypedArray; + lodash.isUndefined = isUndefined; + lodash.isWeakMap = isWeakMap; + lodash.isWeakSet = isWeakSet; + lodash.join = join; + lodash.kebabCase = kebabCase; + lodash.last = last; + lodash.lastIndexOf = lastIndexOf; + lodash.lowerCase = lowerCase; + lodash.lowerFirst = lowerFirst; + lodash.lt = lt; + lodash.lte = lte; + lodash.max = max; + lodash.maxBy = maxBy; + lodash.mean = mean; + lodash.meanBy = meanBy; + lodash.min = min; + lodash.minBy = minBy; + lodash.stubArray = stubArray; + lodash.stubFalse = stubFalse; + lodash.stubObject = stubObject; + lodash.stubString = stubString; + lodash.stubTrue = stubTrue; + lodash.multiply = multiply; + lodash.nth = nth; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.now = now; + lodash.pad = pad; + lodash.padEnd = padEnd; + lodash.padStart = padStart; + lodash.parseInt = parseInt2; + lodash.random = random; + lodash.reduce = reduce; + lodash.reduceRight = reduceRight; + lodash.repeat = repeat; + lodash.replace = replace; + lodash.result = result; + lodash.round = round; + lodash.runInContext = runInContext2; + lodash.sample = sample; + lodash.size = size; + lodash.snakeCase = snakeCase; + lodash.some = some; + lodash.sortedIndex = sortedIndex; + lodash.sortedIndexBy = sortedIndexBy; + lodash.sortedIndexOf = sortedIndexOf; + lodash.sortedLastIndex = sortedLastIndex; + lodash.sortedLastIndexBy = sortedLastIndexBy; + lodash.sortedLastIndexOf = sortedLastIndexOf; + lodash.startCase = startCase; + lodash.startsWith = startsWith; + lodash.subtract = subtract; + lodash.sum = sum; + lodash.sumBy = sumBy; + lodash.template = template; + lodash.times = times; + lodash.toFinite = toFinite; + lodash.toInteger = toInteger; + lodash.toLength = toLength; + lodash.toLower = toLower; + lodash.toNumber = toNumber; + lodash.toSafeInteger = toSafeInteger; + lodash.toString = toString; + lodash.toUpper = toUpper; + lodash.trim = trim; + lodash.trimEnd = trimEnd; + lodash.trimStart = trimStart; + lodash.truncate = truncate; + lodash.unescape = unescape; + lodash.uniqueId = uniqueId; + lodash.upperCase = upperCase; + lodash.upperFirst = upperFirst; + lodash.each = forEach; + lodash.eachRight = forEachRight; + lodash.first = head; + mixin(lodash, function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }(), { "chain": false }); + lodash.VERSION = VERSION2; + arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { + lodash[methodName].placeholder = lodash; + }); + arrayEach(["drop", "take"], function(methodName, index) { + LazyWrapper.prototype[methodName] = function(n) { + n = n === undefined2 ? 1 : nativeMax(toInteger(n), 0); + var result2 = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone(); + if (result2.__filtered__) { + result2.__takeCount__ = nativeMin(n, result2.__takeCount__); + } else { + result2.__views__.push({ + "size": nativeMin(n, MAX_ARRAY_LENGTH), + "type": methodName + (result2.__dir__ < 0 ? "Right" : "") + }); + } + return result2; + }; + LazyWrapper.prototype[methodName + "Right"] = function(n) { + return this.reverse()[methodName](n).reverse(); + }; + }); + arrayEach(["filter", "map", "takeWhile"], function(methodName, index) { + var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + LazyWrapper.prototype[methodName] = function(iteratee2) { + var result2 = this.clone(); + result2.__iteratees__.push({ + "iteratee": getIteratee(iteratee2, 3), + "type": type + }); + result2.__filtered__ = result2.__filtered__ || isFilter; + return result2; + }; + }); + arrayEach(["head", "last"], function(methodName, index) { + var takeName = "take" + (index ? "Right" : ""); + LazyWrapper.prototype[methodName] = function() { + return this[takeName](1).value()[0]; + }; + }); + arrayEach(["initial", "tail"], function(methodName, index) { + var dropName = "drop" + (index ? "" : "Right"); + LazyWrapper.prototype[methodName] = function() { + return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); + }; + }); + LazyWrapper.prototype.compact = function() { + return this.filter(identity); + }; + LazyWrapper.prototype.find = function(predicate) { + return this.filter(predicate).head(); + }; + LazyWrapper.prototype.findLast = function(predicate) { + return this.reverse().find(predicate); + }; + LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + if (typeof path == "function") { + return new LazyWrapper(this); + } + return this.map(function(value) { + return baseInvoke(value, path, args); + }); + }); + LazyWrapper.prototype.reject = function(predicate) { + return this.filter(negate(getIteratee(predicate))); + }; + LazyWrapper.prototype.slice = function(start, end) { + start = toInteger(start); + var result2 = this; + if (result2.__filtered__ && (start > 0 || end < 0)) { + return new LazyWrapper(result2); + } + if (start < 0) { + result2 = result2.takeRight(-start); + } else if (start) { + result2 = result2.drop(start); + } + if (end !== undefined2) { + end = toInteger(end); + result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start); + } + return result2; + }; + LazyWrapper.prototype.takeRightWhile = function(predicate) { + return this.reverse().takeWhile(predicate).reverse(); + }; + LazyWrapper.prototype.toArray = function() { + return this.take(MAX_ARRAY_LENGTH); + }; + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); + if (!lodashFunc) { + return; + } + lodash.prototype[methodName] = function() { + var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray(value); + var interceptor = function(value2) { + var result3 = lodashFunc.apply(lodash, arrayPush([value2], args)); + return isTaker && chainAll ? result3[0] : result3; + }; + if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) { + isLazy = useLazy = false; + } + var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; + if (!retUnwrapped && useLazy) { + value = onlyLazy ? value : new LazyWrapper(this); + var result2 = func.apply(value, args); + result2.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined2 }); + return new LodashWrapper(result2, chainAll); + } + if (isUnwrapped && onlyLazy) { + return func.apply(this, args); + } + result2 = this.thru(interceptor); + return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2; + }; + }); + arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { + var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value2) { + return func.apply(isArray(value2) ? value2 : [], args); + }); + }; + }); + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var lodashFunc = lodash[methodName]; + if (lodashFunc) { + var key = lodashFunc.name + ""; + if (!hasOwnProperty.call(realNames, key)) { + realNames[key] = []; + } + realNames[key].push({ "name": methodName, "func": lodashFunc }); + } + }); + realNames[createHybrid(undefined2, WRAP_BIND_KEY_FLAG).name] = [{ + "name": "wrapper", + "func": undefined2 + }]; + LazyWrapper.prototype.clone = lazyClone; + LazyWrapper.prototype.reverse = lazyReverse; + LazyWrapper.prototype.value = lazyValue; + lodash.prototype.at = wrapperAt; + lodash.prototype.chain = wrapperChain; + lodash.prototype.commit = wrapperCommit; + lodash.prototype.next = wrapperNext; + lodash.prototype.plant = wrapperPlant; + lodash.prototype.reverse = wrapperReverse; + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + lodash.prototype.first = lodash.prototype.head; + if (symIterator) { + lodash.prototype[symIterator] = wrapperToIterator; + } + return lodash; + }; + var _ = runInContext(); + if (typeof define == "function" && typeof define.amd == "object" && define.amd) { + root._ = _; + define(function() { + return _; + }); + } else if (freeModule) { + (freeModule.exports = _)._ = _; + freeExports._ = _; + } else { + root._ = _; + } + }).call(exports); + } + }); + + // src/lib/class/Registry.js + var require_Registry = __commonJS({ + "src/lib/class/Registry.js"(exports, module) { + var Registry = class { + constructor() { + this.data = {}; + } + unregister(name) { + if (!name) { + this.data = {}; + } else { + delete this.data[name]; + } + } + register(name, callback) { + this.data[name] = callback; + } + registerMany(formats) { + Object.keys(formats).forEach((name) => { + this.data[name] = formats[name]; + }); + } + get(name) { + const format = this.data[name]; + return format; + } + list() { + return this.data; + } + }; + var Registry_default = Registry; + module.exports = Registry_default; + } + }); + + // src/lib/api/defaults.js + var require_defaults = __commonJS({ + "src/lib/api/defaults.js"(exports, module) { + var defaults = {}; + var defaults_default = defaults; + defaults.defaultInvalidTypeProduct = void 0; + defaults.defaultRandExpMax = 10; + defaults.pruneProperties = []; + defaults.ignoreProperties = []; + defaults.ignoreMissingRefs = false; + defaults.failOnInvalidTypes = true; + defaults.failOnInvalidFormat = true; + defaults.alwaysFakeOptionals = false; + defaults.optionalsProbability = null; + defaults.fixedProbabilities = true; + defaults.useExamplesValue = false; + defaults.avoidExampleItemsLength = false; + defaults.useDefaultValue = false; + defaults.requiredOnly = false; + defaults.minItems = 0; + defaults.maxItems = null; + defaults.minLength = 0; + defaults.maxLength = null; + defaults.resolveJsonPath = false; + defaults.reuseProperties = false; + defaults.fillProperties = true; + defaults.replaceEmptyByRandomValue = false; + defaults.random = Math.random; + defaults.renderTitle = true; + defaults.renderDescription = true; + defaults.renderComment = false; + defaults.validationOptions = {}; + defaults.pickFirstFromExamples = false; + module.exports = defaults_default; + } + }); + + // src/lib/class/OptionRegistry.js + var require_OptionRegistry = __commonJS({ + "src/lib/class/OptionRegistry.js"(exports, module) { + var Registry = require_Registry(); + var defaults = require_defaults(); + var OptionRegistry = class extends Registry { + constructor() { + super(); + this.data = __spreadValues({}, defaults); + this._defaults = defaults; + } + get defaults() { + return __spreadValues({}, this._defaults); + } + }; + var OptionRegistry_default = OptionRegistry; + module.exports = OptionRegistry_default; + } + }); + + // src/lib/api/option.js + var require_option = __commonJS({ + "src/lib/api/option.js"(exports, module) { + var OptionRegistry = require_OptionRegistry(); + var registry = new OptionRegistry(); + function optionAPI(nameOrOptionMap, optionalValue) { + if (typeof nameOrOptionMap === "string") { + if (typeof optionalValue !== "undefined") { + return registry.register(nameOrOptionMap, optionalValue); + } + return registry.get(nameOrOptionMap); + } + return registry.registerMany(nameOrOptionMap); + } + optionAPI.getDefaults = () => registry.defaults; + var option_default = optionAPI; + module.exports = option_default; + } + }); + + // src/lib/core/constants.js + var require_constants = __commonJS({ + "src/lib/core/constants.js"(exports, module) { + var ALLOWED_TYPES = ["integer", "number", "string", "boolean"]; + var SCALAR_TYPES = ALLOWED_TYPES.concat(["null"]); + var ALL_TYPES = ["array", "object"].concat(SCALAR_TYPES); + var MOST_NEAR_DATETIME = 2524608e6; + var MIN_INTEGER = -1e8; + var MAX_INTEGER = 1e8; + var MIN_NUMBER = -100; + var MAX_NUMBER = 100; + var constants_default = { + ALLOWED_TYPES, + SCALAR_TYPES, + ALL_TYPES, + MIN_NUMBER, + MAX_NUMBER, + MIN_INTEGER, + MAX_INTEGER, + MOST_NEAR_DATETIME + }; + module.exports = constants_default; + } + }); + + // node_modules/ret/lib/types.js + var require_types = __commonJS({ + "node_modules/ret/lib/types.js"(exports, module) { + module.exports = { + ROOT: 0, + GROUP: 1, + POSITION: 2, + SET: 3, + RANGE: 4, + REPETITION: 5, + REFERENCE: 6, + CHAR: 7 + }; + } + }); + + // node_modules/ret/lib/sets.js + var require_sets = __commonJS({ + "node_modules/ret/lib/sets.js"(exports) { + var types = require_types(); + var INTS = () => [{ type: types.RANGE, from: 48, to: 57 }]; + var WORDS = () => { + return [ + { type: types.CHAR, value: 95 }, + { type: types.RANGE, from: 97, to: 122 }, + { type: types.RANGE, from: 65, to: 90 } + ].concat(INTS()); + }; + var WHITESPACE = () => { + 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.RANGE, from: 8192, to: 8202 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + { type: types.CHAR, value: 8239 }, + { type: types.CHAR, value: 8287 }, + { type: types.CHAR, value: 12288 }, + { type: types.CHAR, value: 65279 } + ]; + }; + var NOTANYCHAR = () => { + return [ + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 } + ]; + }; + exports.words = () => ({ type: types.SET, set: WORDS(), not: false }); + exports.notWords = () => ({ type: types.SET, set: WORDS(), not: true }); + exports.ints = () => ({ type: types.SET, set: INTS(), not: false }); + exports.notInts = () => ({ type: types.SET, set: INTS(), not: true }); + exports.whitespace = () => ({ type: types.SET, set: WHITESPACE(), not: false }); + exports.notWhitespace = () => ({ type: types.SET, set: WHITESPACE(), not: true }); + exports.anyChar = () => ({ type: types.SET, set: NOTANYCHAR(), not: true }); + } + }); + + // node_modules/ret/lib/util.js + var require_util = __commonJS({ + "node_modules/ret/lib/util.js"(exports) { + var types = require_types(); + var sets = require_sets(); + var CTRL = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?"; + var SLSH = { "0": 0, "t": 9, "n": 10, "v": 11, "f": 12, "r": 13 }; + exports.strToChars = function(str) { + 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); + if (/[[\]{}^$.|?*+()]/.test(c)) { + c = "\\" + c; + } + return c; + }); + return str; + }; + exports.tokenizeClass = (str, regexpStr) => { + var tokens = []; + var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?([^])/g; + var rs, c; + while ((rs = regexp.exec(str)) != null) { + if (rs[1]) { + tokens.push(sets.words()); + } else if (rs[2]) { + tokens.push(sets.ints()); + } else if (rs[3]) { + tokens.push(sets.whitespace()); + } else if (rs[4]) { + tokens.push(sets.notWords()); + } else if (rs[5]) { + tokens.push(sets.notInts()); + } else if (rs[6]) { + tokens.push(sets.notWhitespace()); + } else if (rs[7]) { + tokens.push({ + type: types.RANGE, + from: (rs[8] || rs[9]).charCodeAt(0), + to: rs[10].charCodeAt(0) + }); + } else if (c = rs[12]) { + tokens.push({ + type: types.CHAR, + value: c.charCodeAt(0) + }); + } else { + return [tokens, regexp.lastIndex]; + } + } + exports.error(regexpStr, "Unterminated character class"); + }; + exports.error = (regexp, msg) => { + throw new SyntaxError("Invalid regular expression: /" + regexp + "/: " + msg); + }; + } + }); + + // node_modules/ret/lib/positions.js + var require_positions = __commonJS({ + "node_modules/ret/lib/positions.js"(exports) { + var types = require_types(); + exports.wordBoundary = () => ({ type: types.POSITION, value: "b" }); + exports.nonWordBoundary = () => ({ type: types.POSITION, value: "B" }); + exports.begin = () => ({ type: types.POSITION, value: "^" }); + exports.end = () => ({ type: types.POSITION, value: "$" }); + } + }); + + // node_modules/ret/lib/index.js + var require_lib = __commonJS({ + "node_modules/ret/lib/index.js"(exports, module) { + var util = require_util(); + var types = require_types(); + var sets = require_sets(); + var positions = require_positions(); + module.exports = (regexpStr) => { + var i = 0, l, c, start = { type: types.ROOT, stack: [] }, lastGroup = start, last = start.stack, groupStack = []; + var repeatErr = (i2) => { + util.error(regexpStr, `Nothing to repeat at column ${i2 - 1}`); + }; + var str = util.strToChars(regexpStr); + l = str.length; + while (i < l) { + c = str[i++]; + switch (c) { + case "\\": + c = str[i++]; + switch (c) { + case "b": + last.push(positions.wordBoundary()); + break; + case "B": + last.push(positions.nonWordBoundary()); + break; + case "w": + last.push(sets.words()); + break; + case "W": + last.push(sets.notWords()); + break; + case "d": + last.push(sets.ints()); + break; + case "D": + last.push(sets.notInts()); + break; + case "s": + last.push(sets.whitespace()); + break; + case "S": + last.push(sets.notWhitespace()); + break; + default: + if (/\d/.test(c)) { + last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); + } else { + last.push({ type: types.CHAR, value: c.charCodeAt(0) }); + } + } + break; + case "^": + last.push(positions.begin()); + break; + case "$": + last.push(positions.end()); + break; + case "[": + var not; + if (str[i] === "^") { + not = true; + i++; + } else { + not = false; + } + var classTokens = util.tokenizeClass(str.slice(i), regexpStr); + i += classTokens[1]; + last.push({ + type: types.SET, + set: classTokens[0], + not + }); + break; + case ".": + last.push(sets.anyChar()); + break; + case "(": + var group = { + type: types.GROUP, + stack: [], + remember: true + }; + c = str[i]; + if (c === "?") { + c = str[i + 1]; + i += 2; + if (c === "=") { + group.followedBy = true; + } else if (c === "!") { + group.notFollowedBy = true; + } else if (c !== ":") { + util.error(regexpStr, `Invalid group, character '${c}' after '?' at column ${i - 1}`); + } + group.remember = false; + } + last.push(group); + groupStack.push(lastGroup); + lastGroup = group; + last = group.stack; + break; + case ")": + if (groupStack.length === 0) { + util.error(regexpStr, `Unmatched ) at column ${i - 1}`); + } + lastGroup = groupStack.pop(); + last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; + break; + case "|": + if (!lastGroup.options) { + lastGroup.options = [lastGroup.stack]; + delete lastGroup.stack; + } + var stack = []; + lastGroup.options.push(stack); + last = stack; + break; + 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, + max, + value: last.pop() + }); + } else { + last.push({ + type: types.CHAR, + value: 123 + }); + } + break; + case "?": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: 1, + value: last.pop() + }); + break; + case "+": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 1, + max: Infinity, + value: last.pop() + }); + break; + case "*": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: Infinity, + value: last.pop() + }); + break; + default: + last.push({ + type: types.CHAR, + value: c.charCodeAt(0) + }); + } + } + if (groupStack.length !== 0) { + util.error(regexpStr, "Unterminated group"); + } + return start; + }; + module.exports.types = types; + } + }); + + // node_modules/drange/lib/index.js + var require_lib2 = __commonJS({ + "node_modules/drange/lib/index.js"(exports, module) { + "use strict"; + var SubRange = class { + constructor(low, high) { + this.low = low; + this.high = high; + this.length = 1 + high - low; + } + overlaps(range) { + return !(this.high < range.low || this.low > range.high); + } + touches(range) { + return !(this.high + 1 < range.low || this.low - 1 > range.high); + } + add(range) { + return new SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high)); + } + subtract(range) { + if (range.low <= this.low && range.high >= this.high) { + return []; + } else if (range.low > this.low && range.high < this.high) { + return [ + new SubRange(this.low, range.low - 1), + new SubRange(range.high + 1, this.high) + ]; + } else if (range.low <= this.low) { + return [new SubRange(range.high + 1, this.high)]; + } else { + return [new SubRange(this.low, range.low - 1)]; + } + } + toString() { + return this.low == this.high ? this.low.toString() : this.low + "-" + this.high; + } + }; + var DRange = class { + constructor(a, b) { + this.ranges = []; + this.length = 0; + if (a != null) + this.add(a, b); + } + _update_length() { + this.length = this.ranges.reduce((previous, range) => { + return previous + range.length; + }, 0); + } + add(a, b) { + var _add = (subrange) => { + var i = 0; + while (i < this.ranges.length && !subrange.touches(this.ranges[i])) { + i++; + } + var newRanges = this.ranges.slice(0, i); + while (i < this.ranges.length && subrange.touches(this.ranges[i])) { + subrange = subrange.add(this.ranges[i]); + i++; + } + newRanges.push(subrange); + this.ranges = newRanges.concat(this.ranges.slice(i)); + this._update_length(); + }; + if (a instanceof DRange) { + a.ranges.forEach(_add); + } else { + if (b == null) + b = a; + _add(new SubRange(a, b)); + } + return this; + } + subtract(a, b) { + var _subtract = (subrange) => { + var i = 0; + while (i < this.ranges.length && !subrange.overlaps(this.ranges[i])) { + i++; + } + var newRanges = this.ranges.slice(0, i); + while (i < this.ranges.length && subrange.overlaps(this.ranges[i])) { + newRanges = newRanges.concat(this.ranges[i].subtract(subrange)); + i++; + } + this.ranges = newRanges.concat(this.ranges.slice(i)); + this._update_length(); + }; + if (a instanceof DRange) { + a.ranges.forEach(_subtract); + } else { + if (b == null) + b = a; + _subtract(new SubRange(a, b)); + } + return this; + } + intersect(a, b) { + var newRanges = []; + var _intersect = (subrange) => { + var i = 0; + while (i < this.ranges.length && !subrange.overlaps(this.ranges[i])) { + i++; + } + while (i < this.ranges.length && subrange.overlaps(this.ranges[i])) { + var low = Math.max(this.ranges[i].low, subrange.low); + var high = Math.min(this.ranges[i].high, subrange.high); + newRanges.push(new SubRange(low, high)); + i++; + } + }; + if (a instanceof DRange) { + a.ranges.forEach(_intersect); + } else { + if (b == null) + b = a; + _intersect(new SubRange(a, b)); + } + this.ranges = newRanges; + this._update_length(); + return this; + } + index(index) { + var i = 0; + while (i < this.ranges.length && this.ranges[i].length <= index) { + index -= this.ranges[i].length; + i++; + } + return this.ranges[i].low + index; + } + toString() { + return "[ " + this.ranges.join(", ") + " ]"; + } + clone() { + return new DRange(this); + } + numbers() { + return this.ranges.reduce((result, subrange) => { + var i = subrange.low; + while (i <= subrange.high) { + result.push(i); + i++; + } + return result; + }, []); + } + subranges() { + return this.ranges.map((subrange) => ({ + low: subrange.low, + high: subrange.high, + length: 1 + subrange.high - subrange.low + })); + } + }; + module.exports = DRange; + } + }); + + // node_modules/randexp/lib/randexp.js + var require_randexp = __commonJS({ + "node_modules/randexp/lib/randexp.js"(exports, module) { + var ret = require_lib(); + var DRange = require_lib2(); + var types = ret.types; + module.exports = class RandExp { + constructor(regexp, m) { + this._setDefaults(regexp); + if (regexp instanceof RegExp) { + this.ignoreCase = regexp.ignoreCase; + this.multiline = regexp.multiline; + regexp = regexp.source; + } else if (typeof regexp === "string") { + this.ignoreCase = m && m.indexOf("i") !== -1; + this.multiline = m && m.indexOf("m") !== -1; + } else { + throw new Error("Expected a regexp or string"); + } + this.tokens = ret(regexp); + } + _setDefaults(regexp) { + this.max = regexp.max != null ? regexp.max : RandExp.prototype.max != null ? RandExp.prototype.max : 100; + this.defaultRange = regexp.defaultRange ? regexp.defaultRange : this.defaultRange.clone(); + if (regexp.randInt) { + this.randInt = regexp.randInt; + } + } + gen() { + return this._gen(this.tokens, []); + } + _gen(token, groups) { + var stack, str, n, i, l; + switch (token.type) { + case types.ROOT: + case types.GROUP: + if (token.followedBy || token.notFollowedBy) { + return ""; + } + if (token.remember && token.groupNumber === void 0) { + token.groupNumber = groups.push(null) - 1; + } + stack = token.options ? this._randSelect(token.options) : token.stack; + str = ""; + for (i = 0, l = stack.length; i < l; i++) { + str += this._gen(stack[i], groups); + } + if (token.remember) { + groups[token.groupNumber] = str; + } + return str; + case types.POSITION: + return ""; + case types.SET: + var expandedSet = this._expand(token); + if (!expandedSet.length) { + return ""; + } + return String.fromCharCode(this._randSelect(expandedSet)); + case types.REPETITION: + n = this.randInt(token.min, token.max === Infinity ? token.min + this.max : token.max); + str = ""; + for (i = 0; i < n; i++) { + str += this._gen(token.value, groups); + } + return str; + case types.REFERENCE: + return groups[token.value - 1] || ""; + case types.CHAR: + var code = this.ignoreCase && this._randBool() ? this._toOtherCase(token.value) : token.value; + return String.fromCharCode(code); + } + } + _toOtherCase(code) { + return code + (97 <= code && code <= 122 ? -32 : 65 <= code && code <= 90 ? 32 : 0); + } + _randBool() { + return !this.randInt(0, 1); + } + _randSelect(arr) { + if (arr instanceof DRange) { + return arr.index(this.randInt(0, arr.length - 1)); + } + return arr[this.randInt(0, arr.length - 1)]; + } + _expand(token) { + if (token.type === ret.types.CHAR) { + return new DRange(token.value); + } else if (token.type === ret.types.RANGE) { + return new DRange(token.from, token.to); + } else { + let drange = new DRange(); + for (let i = 0; i < token.set.length; i++) { + let subrange = this._expand(token.set[i]); + drange.add(subrange); + if (this.ignoreCase) { + for (let j = 0; j < subrange.length; j++) { + let code = subrange.index(j); + let otherCaseCode = this._toOtherCase(code); + if (code !== otherCaseCode) { + drange.add(otherCaseCode); + } + } + } + } + if (token.not) { + return this.defaultRange.clone().subtract(drange); + } else { + return this.defaultRange.clone().intersect(drange); + } + } + } + randInt(a, b) { + return a + Math.floor(Math.random() * (1 + b - a)); + } + get defaultRange() { + return this._range = this._range || new DRange(32, 126); + } + set defaultRange(range) { + this._range = range; + } + static randexp(regexp, m) { + var randexp; + if (typeof regexp === "string") { + regexp = new RegExp(regexp, m); + } + if (regexp._randexp === void 0) { + randexp = new RandExp(regexp, m); + regexp._randexp = randexp; + } else { + randexp = regexp._randexp; + randexp._setDefaults(regexp); + } + return randexp.gen(); + } + static sugar() { + RegExp.prototype.gen = function() { + return RandExp.randexp(this); + }; + } + }; + } + }); + + // src/lib/core/random.js + var require_random = __commonJS({ + "src/lib/core/random.js"(exports, module) { + var RandExp = require_randexp(); + var optionAPI = require_option(); + var env = require_constants(); + function getRandomInteger(min, max) { + min = typeof min === "undefined" ? env.MIN_INTEGER : min; + max = typeof max === "undefined" ? env.MAX_INTEGER : max; + return Math.floor(optionAPI("random")() * (max - min + 1)) + min; + } + function _randexp(value) { + RandExp.prototype.max = optionAPI("defaultRandExpMax"); + RandExp.prototype.randInt = (a, b) => a + Math.floor(optionAPI("random")() * (1 + (b - a))); + const re = new RandExp(value); + return re.gen(); + } + function pick(collection) { + return collection[Math.floor(optionAPI("random")() * collection.length)]; + } + function shuffle(collection) { + let tmp; + let key; + let length = collection.length; + const copy = collection.slice(); + for (; length > 0; ) { + key = Math.floor(optionAPI("random")() * length); + length -= 1; + tmp = copy[length]; + copy[length] = copy[key]; + copy[key] = tmp; + } + return copy; + } + function getRandom(min, max) { + return optionAPI("random")() * (max - min) + min; + } + function number(min, max, defMin, defMax, hasPrecision = false) { + defMin = typeof defMin === "undefined" ? env.MIN_NUMBER : defMin; + defMax = typeof defMax === "undefined" ? env.MAX_NUMBER : defMax; + min = typeof min === "undefined" ? defMin : min; + max = typeof max === "undefined" ? defMax : max; + if (max < min) { + max += min; + } + if (hasPrecision) { + return getRandom(min, max); + } + return getRandomInteger(min, max); + } + function by(type) { + switch (type) { + case "seconds": + return number(0, 60) * 60; + case "minutes": + return number(15, 50) * 612; + case "hours": + return number(12, 72) * 36123; + case "days": + return number(7, 30) * 86412345; + case "weeks": + return number(4, 52) * 604812345; + case "months": + return number(2, 13) * 2592012345; + case "years": + return number(1, 20) * 31104012345; + default: + break; + } + } + function date(step) { + if (step) { + return by(step); + } + const now = new Date(); + const days = number(-1e3, env.MOST_NEAR_DATETIME); + now.setTime(now.getTime() - days); + return now; + } + var random_default = { + pick, + date, + shuffle, + number, + randexp: _randexp + }; + module.exports = random_default; + } + }); + + // src/lib/core/utils.js + var require_utils = __commonJS({ + "src/lib/core/utils.js"(exports, module) { + var _ = require_lodash(); + var optionAPI = require_option(); + var env = require_constants(); + var random = require_random(); + function getLocalRef(obj, path, refs) { + if (refs && refs[path]) + return clone(refs[path]); + const keyElements = path.replace("#/", "/").split("/"); + let schema = obj.$ref && refs && refs[obj.$ref] || obj; + if (!schema && !keyElements[0]) { + keyElements[0] = obj.$ref.split("#/")[0]; + } + if (refs && path.includes("#/") && refs[keyElements[0]]) { + schema = refs[keyElements.shift()]; + } + if (!keyElements[0]) + keyElements.shift(); + while (schema && keyElements.length > 0) { + const prop = keyElements.shift(); + if (!schema[prop]) { + throw new Error(`Prop not found: ${prop} (${path})`); + } + schema = schema[prop]; + } + return schema; + } + function hasProperties(obj, ...properties) { + return properties.filter((key) => { + return typeof obj[key] !== "undefined"; + }).length > 0; + } + function clampDate(value) { + if (value.includes(" ")) { + return new Date(value).toISOString().substr(0, 10); + } + let [year, month, day] = value.split("T")[0].split("-"); + month = `0${Math.max(1, Math.min(12, month))}`.slice(-2); + day = `0${Math.max(1, Math.min(31, day))}`.slice(-2); + return `${year}-${month}-${day}`; + } + function clampDateTime(value) { + if (value.includes(" ")) { + return new Date(value).toISOString().substr(0, 10); + } + let [year, month, day] = value.split("T")[0].split("-"); + let [hour, minute, second] = value.split("T")[1].split(".")[0].split(":"); + month = `0${Math.max(1, Math.min(12, month))}`.slice(-2); + day = `0${Math.max(1, Math.min(31, day))}`.slice(-2); + hour = `0${Math.max(1, Math.min(23, hour))}`.slice(-2); + minute = `0${Math.max(1, Math.min(59, minute))}`.slice(-2); + second = `0${Math.max(1, Math.min(59, second))}`.slice(-2); + return `${year}-${month}-${day}T${hour}:${minute}:${second}.000Z`; + } + function getPreviousMultiple(max, multipleOf) { + let res = max - 1; + while (res > -Number.MAX_VALUE) { + if (res % multipleOf === 0) { + return res; + } + res -= 1; + } + return res; + } + function getNextMultiple(min, multipleOf) { + let res = min + 1; + while (res < Number.MAX_VALUE) { + if (res % multipleOf === 0) { + return res; + } + res += 1; + } + return res; + } + function handleExclusiveMaximum(schema, max) { + max = _.has(schema, "maximum") && schema.maximum !== Number.MAX_VALUE ? schema.maximum : max; + if (_.has(schema, "exclusiveMaximum")) { + if (typeof schema.exclusiveMaximum === "boolean" && schema.exclusiveMaximum === true) { + return schema.multipleOf ? getPreviousMultiple(max, schema.multipleOf) : max - 1; + } + if (typeof schema.exclusiveMaximum === "number") { + return schema.multipleOf ? getPreviousMultiple(schema.exclusiveMaximum, schema.multipleOf) : schema.exclusiveMaximum - 1; + } + } + return max; + } + function handleExclusiveMinimum(schema, min) { + min = _.has(schema, "minimum") && schema.maximum !== -Number.MAX_VALUE ? schema.minimum : min; + if (_.has(schema, "exclusiveMinimum")) { + if (typeof schema.exclusiveMinimum === "boolean" && schema.exclusiveMinimum === true) { + return schema.multipleOf ? getNextMultiple(min, schema.multipleOf) : min + 1; + } + if (typeof schema.exclusiveMinimum === "number") { + return schema.multipleOf ? getNextMultiple(schema.exclusiveMinimum, schema.multipleOf) : schema.exclusiveMinimum + 1; + } + } + return min; + } + function typecast(type, schema, callback) { + const params = {}; + switch (type || schema.type) { + case "integer": + case "number": + if (typeof schema.minimum !== "undefined") { + params.minimum = schema.minimum; + } + if (typeof schema.maximum !== "undefined") { + params.maximum = schema.maximum; + } + if (schema.enum) { + let min = Math.max(params.minimum || 0, 0); + let max = Math.min(params.maximum || Infinity, Infinity); + min = handleExclusiveMinimum(schema, min); + max = handleExclusiveMaximum(schema, max); + if (min || max !== Infinity) { + schema.enum = schema.enum.filter((x) => { + if (x >= min && x <= max) { + return true; + } + return false; + }); + } + } + break; + case "string": { + params.minLength = optionAPI("minLength") || 0; + params.maxLength = optionAPI("maxLength") || Number.MAX_SAFE_INTEGER; + if (typeof schema.minLength !== "undefined") { + params.minLength = Math.max(params.minLength, schema.minLength); + } + if (typeof schema.maxLength !== "undefined") { + params.maxLength = Math.min(params.maxLength, schema.maxLength); + } + break; + } + default: + break; + } + let value = callback(params); + if (value === null || value === void 0) { + return null; + } + switch (type || schema.type) { + case "number": + value = parseFloat(value); + break; + case "integer": + value = parseInt(value, 10); + break; + case "boolean": + value = !!value; + break; + case "string": { + value = String(value); + const min = Math.max(params.minLength || 0, 0); + const max = Math.min(params.maxLength || Infinity, Infinity); + let prev; + let noChangeCount = 0; + while (value.length < min) { + prev = value; + if (!schema.pattern) { + value += `${random.pick([" ", "/", "_", "-", "+", "=", "@", "^"])}${value}`; + } else { + value += random.randexp(schema.pattern); + } + if (value === prev) { + noChangeCount += 1; + if (noChangeCount === 3) { + break; + } + } else { + noChangeCount = 0; + } + } + if (value.length > max) { + value = value.substr(0, max); + } + switch (schema.format) { + case "date-time": + case "datetime": + value = new Date(clampDateTime(value)).toISOString().replace(/([0-9])0+Z$/, "$1Z"); + break; + case "full-date": + case "date": + value = new Date(clampDate(value)).toISOString().substr(0, 10); + break; + case "time": + value = new Date(`1969-01-01 ${value}`).toISOString().substr(11); + break; + default: + break; + } + break; + } + default: + break; + } + return value; + } + function merge(a, b) { + Object.keys(b).forEach((key) => { + if (typeof b[key] !== "object" || b[key] === null) { + a[key] = b[key]; + } else if (Array.isArray(b[key])) { + a[key] = a[key] || []; + b[key].forEach((value) => { + if (Array.isArray(a[key]) && a[key].indexOf(value) === -1) { + a[key].push(value); + } + }); + } else if (typeof a[key] !== "object" || a[key] === null || Array.isArray(a[key])) { + a[key] = merge({}, b[key]); + } else { + a[key] = merge(a[key], b[key]); + } + }); + return a; + } + function clone(obj, cache = new Map()) { + if (!obj || typeof obj !== "object") { + return obj; + } + if (cache.has(obj)) { + return cache.get(obj); + } + if (Array.isArray(obj)) { + const arr = []; + cache.set(obj, arr); + arr.push(...obj.map((x) => clone(x, cache))); + return arr; + } + const clonedObj = {}; + cache.set(obj, clonedObj); + return Object.keys(obj).reduce((prev, cur) => { + prev[cur] = clone(obj[cur], cache); + return prev; + }, clonedObj); + } + function short(schema) { + const s = JSON.stringify(schema); + const l = JSON.stringify(schema, null, 2); + return s.length > 400 ? `${l.substr(0, 400)}...` : l; + } + function anyValue() { + return random.pick([ + false, + true, + null, + -1, + NaN, + Math.PI, + Infinity, + void 0, + [], + {}, + Math.random(), + Math.random().toString(36).substr(2) + ]); + } + function notValue(schema, parent) { + const copy = merge({}, parent); + if (typeof schema.minimum !== "undefined") { + copy.maximum = schema.minimum; + copy.exclusiveMaximum = true; + } + if (typeof schema.maximum !== "undefined") { + copy.minimum = schema.maximum > copy.maximum ? 0 : schema.maximum; + copy.exclusiveMinimum = true; + } + if (typeof schema.minLength !== "undefined") { + copy.maxLength = schema.minLength; + } + if (typeof schema.maxLength !== "undefined") { + copy.minLength = schema.maxLength > copy.maxLength ? 0 : schema.maxLength; + } + if (schema.type) { + copy.type = random.pick(env.SCALAR_TYPES.filter((x) => { + const types = Array.isArray(schema.type) ? schema.type : [schema.type]; + return types.every((type) => { + if (x === "number" || x === "integer") { + return type !== "number" && type !== "integer"; + } + return x !== type; + }); + })); + } else if (schema.enum) { + let value; + do { + value = anyValue(); + } while (schema.enum.indexOf(value) !== -1); + copy.enum = [value]; + } + if (schema.required && copy.properties) { + schema.required.forEach((prop) => { + delete copy.properties[prop]; + }); + } + return copy; + } + function validateValueForSchema(value, schema) { + const schemaHasMin = schema.minimum !== void 0; + const schemaHasMax = schema.maximum !== void 0; + return (schemaHasMin || schemaHasMax) && (!schemaHasMin || value >= schema.minimum) && (!schemaHasMax || value <= schema.maximum); + } + function validate(value, schemas) { + return !schemas.every((schema) => validateValueForSchema(value, schema)); + } + function validateValueForOneOf(value, oneOf) { + const validCount = oneOf.reduce((count, schema) => count + (validateValueForSchema(value, schema) ? 1 : 0), 0); + return validCount === 1; + } + function isKey(prop) { + return ["enum", "const", "default", "examples", "required", "definitions", "items", "properties"].includes(prop); + } + function omitProps(obj, props) { + return Object.keys(obj).filter((key) => !props.includes(key)).reduce((copy, k) => { + if (Array.isArray(obj[k])) { + copy[k] = obj[k].slice(); + } else { + copy[k] = obj[k] instanceof Object ? merge({}, obj[k]) : obj[k]; + } + return copy; + }, {}); + } + function template(value, schema) { + if (Array.isArray(value)) { + return value.map((x) => template(x, schema)); + } + if (typeof value === "string") { + value = value.replace(/#\{([\w.-]+)\}/g, (x, $1) => schema[$1]); + } + return value; + } + function isEmpty(value) { + return Object.prototype.toString.call(value) === "[object Object]" && !Object.keys(value).length; + } + function shouldClean(key, schema) { + const isRequired = Array.isArray(schema.required) && schema.required.includes(key); + const wasCleaned = typeof schema.thunk === "function" || schema.additionalProperties && typeof schema.additionalProperties.thunk === "function"; + return !isRequired && !wasCleaned; + } + function clean(obj, schema, isArray = false) { + if (!obj || typeof obj !== "object") { + return obj; + } + if (Array.isArray(obj)) { + return obj.map((value) => clean(value, schema, true)).filter((value) => typeof value !== "undefined"); + } + Object.keys(obj).forEach((k) => { + if (isEmpty(obj[k])) { + if (shouldClean(k, schema)) { + delete obj[k]; + } + } else { + const value = clean(obj[k], schema); + if (!isEmpty(value)) { + obj[k] = value; + } + } + if (typeof obj[k] === "undefined") { + delete obj[k]; + } + }); + if (!Object.keys(obj).length && isArray) { + return void 0; + } + return obj; + } + var utils_default = { + hasProperties, + getLocalRef, + omitProps, + typecast, + merge, + clone, + short, + notValue, + anyValue, + validate, + validateValueForSchema, + validateValueForOneOf, + isKey, + template, + shouldClean, + clean, + isEmpty, + clampDate, + handleExclusiveMaximum, + handleExclusiveMinimum, + getPreviousMultiple, + getNextMultiple + }; + module.exports = utils_default; + } + }); + + // src/lib/class/Container.js + var require_Container = __commonJS({ + "src/lib/class/Container.js"(exports, module) { + var import_utils = __toModule(require_utils()); + function proxy(gen) { + return (value, schema, property, rootSchema) => { + let fn = value; + let args = []; + if (typeof value === "object") { + fn = Object.keys(value)[0]; + if (Array.isArray(value[fn])) { + args = value[fn]; + } else { + args.push(value[fn]); + } + } + const props = fn.split("."); + let ctx = gen(); + while (props.length > 1) { + ctx = ctx[props.shift()]; + } + value = typeof ctx === "object" ? ctx[props[0]] : ctx; + if (typeof value === "function") { + value = value.apply(ctx, args.map((x) => import_utils.default.template(x, rootSchema))); + } + if (Object.prototype.toString.call(value) === "[object Object]") { + Object.keys(value).forEach((key) => { + if (typeof value[key] === "function") { + throw new Error(`Cannot resolve value for '${property}: ${fn}', given: ${value}`); + } + }); + } + return value; + }; + } + var Container = class { + constructor() { + this.registry = {}; + this.support = {}; + } + reset(name) { + if (!name) { + this.registry = {}; + this.support = {}; + } else { + delete this.registry[name]; + delete this.support[name]; + } + } + extend(name, callback) { + this.registry[name] = callback(this.registry[name]); + if (!this.support[name]) { + this.support[name] = proxy(() => this.registry[name]); + } + } + define(name, callback) { + this.support[name] = callback; + } + get(name) { + if (typeof this.registry[name] === "undefined") { + throw new ReferenceError(`'${name}' dependency doesn't exist.`); + } + return this.registry[name]; + } + wrap(schema) { + if (!("generate" in schema)) { + const keys = Object.keys(schema); + const context = {}; + let length = keys.length; + while (length--) { + const fn = keys[length].replace(/^x-/, ""); + const gen = this.support[fn]; + if (typeof gen === "function") { + Object.defineProperty(schema, "generate", { + configurable: false, + enumerable: false, + writable: false, + value: (rootSchema, key) => gen.call(context, schema[keys[length]], schema, keys[length], rootSchema, key.slice()) + }); + break; + } + } + } + return schema; + } + }; + var Container_default = Container; + module.exports = Container_default; + } + }); + + // src/lib/api/format.js + var require_format = __commonJS({ + "src/lib/api/format.js"(exports, module) { + var Registry = require_Registry(); + var registry = new Registry(); + function formatAPI(nameOrFormatMap, callback) { + if (typeof nameOrFormatMap === "undefined") { + return registry.list(); + } + if (typeof nameOrFormatMap === "string") { + if (typeof callback === "function") { + registry.register(nameOrFormatMap, callback); + } else if (callback === null || callback === false) { + registry.unregister(nameOrFormatMap); + } else { + return registry.get(nameOrFormatMap); + } + } else { + registry.registerMany(nameOrFormatMap); + } + } + var format_default = formatAPI; + module.exports = format_default; + } + }); + + // src/lib/core/error.js + var require_error = __commonJS({ + "src/lib/core/error.js"(exports, module) { + var ParseError = class extends Error { + constructor(message, path) { + super(); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "ParseError"; + this.message = message; + this.path = path; + } + }; + var error_default = ParseError; + module.exports = error_default; + } + }); + + // src/lib/core/infer.js + var require_infer = __commonJS({ + "src/lib/core/infer.js"(exports, module) { + var inferredProperties = { + array: [ + "additionalItems", + "items", + "maxItems", + "minItems", + "uniqueItems" + ], + integer: [ + "exclusiveMaximum", + "exclusiveMinimum", + "maximum", + "minimum", + "multipleOf" + ], + object: [ + "additionalProperties", + "dependencies", + "maxProperties", + "minProperties", + "patternProperties", + "properties", + "required" + ], + string: [ + "maxLength", + "minLength", + "pattern", + "format" + ] + }; + inferredProperties.number = inferredProperties.integer; + var subschemaProperties = [ + "additionalItems", + "items", + "additionalProperties", + "dependencies", + "patternProperties", + "properties" + ]; + function matchesType(obj, lastElementInPath, inferredTypeProperties) { + return Object.keys(obj).filter((prop) => { + const isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1; + const inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1; + if (inferredPropertyFound && !isSubschema) { + return true; + } + return false; + }).length > 0; + } + function inferType(obj, schemaPath) { + const keys = Object.keys(inferredProperties); + for (let i = 0; i < keys.length; i += 1) { + const typeName = keys[i]; + const lastElementInPath = schemaPath[schemaPath.length - 1]; + if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) { + return typeName; + } + } + } + var infer_default = inferType; + module.exports = infer_default; + } + }); + + // src/lib/generators/boolean.js + var require_boolean = __commonJS({ + "src/lib/generators/boolean.js"(exports, module) { + var optionAPI = require_option(); + function booleanGenerator() { + return optionAPI("random")() > 0.5; + } + var boolean_default = booleanGenerator; + module.exports = boolean_default; + } + }); + + // src/lib/types/boolean.js + var require_boolean2 = __commonJS({ + "src/lib/types/boolean.js"(exports, module) { + var booleanGenerator = require_boolean(); + var booleanType = booleanGenerator; + var boolean_default = booleanType; + module.exports = boolean_default; + } + }); + + // src/lib/generators/null.js + var require_null = __commonJS({ + "src/lib/generators/null.js"(exports, module) { + function nullGenerator() { + return null; + } + var null_default = nullGenerator; + module.exports = null_default; + } + }); + + // src/lib/types/null.js + var require_null2 = __commonJS({ + "src/lib/types/null.js"(exports, module) { + var nullGenerator = require_null(); + var nullType = nullGenerator; + var null_default = nullType; + module.exports = null_default; + } + }); + + // src/lib/types/array.js + var require_array = __commonJS({ + "src/lib/types/array.js"(exports, module) { + var random = require_random(); + var utils = require_utils(); + var ParseError = require_error(); + var optionAPI = require_option(); + function unique(path, items, value, sample, resolve, validateSchema, traverseCallback) { + const tmp = []; + const seen = []; + function walk(obj) { + const json = JSON.stringify(obj.value); + if (seen.indexOf(json) === -1) { + seen.push(json); + tmp.push(obj); + return true; + } + return false; + } + items.forEach(walk); + let limit = 10; + while (tmp.length !== items.length) { + if (!walk(traverseCallback(value.items || sample, path, resolve, void 0, validateSchema))) { + limit -= 1; + } + if (!limit) { + break; + } + } + return tmp; + } + function arrayType(value, path, resolve, validateSchema, traverseCallback) { + const items = []; + if (!(value.items || value.additionalItems)) { + if (utils.hasProperties(value, "minItems", "maxItems", "uniqueItems")) { + throw new ParseError(`missing items for ${utils.short(value)}`, path); + } + return items; + } + if (Array.isArray(value.items)) { + return value.items.map((item, key) => { + const itemSubpath = path.concat(["items", key]); + return traverseCallback(item, itemSubpath, resolve, void 0, validateSchema); + }); + } + let minItems = value.minItems; + let maxItems = value.maxItems; + const defaultMinItems = optionAPI("minItems"); + const defaultMaxItems = optionAPI("maxItems"); + if (defaultMinItems) { + minItems = typeof minItems === "undefined" ? defaultMinItems : Math.min(defaultMinItems, minItems); + } + if (defaultMaxItems) { + maxItems = typeof maxItems === "undefined" ? defaultMaxItems : Math.min(defaultMaxItems, maxItems); + if (maxItems && maxItems > defaultMaxItems) { + maxItems = defaultMaxItems; + } + if (minItems && minItems > defaultMaxItems) { + minItems = maxItems; + } + } + const optionalsProbability = optionAPI("alwaysFakeOptionals") === true ? 1 : optionAPI("optionalsProbability"); + const fixedProbabilities = optionAPI("alwaysFakeOptionals") || optionAPI("fixedProbabilities") || false; + let length = random.number(minItems, maxItems, 1, 5); + if (optionalsProbability !== null) { + length = Math.max(fixedProbabilities ? Math.round((maxItems || length) * optionalsProbability) : Math.abs(random.number(minItems, maxItems) * optionalsProbability), minItems || 0); + } + const sample = typeof value.additionalItems === "object" ? value.additionalItems : {}; + for (let current = items.length; current < length; current += 1) { + const itemSubpath = path.concat(["items", current]); + const element = traverseCallback(value.items || sample, itemSubpath, resolve, void 0, validateSchema); + items.push(element); + } + if (value.contains && length > 0) { + const idx = random.number(0, length - 1); + items[idx] = traverseCallback(value.contains, path.concat(["items", idx]), resolve, void 0, validateSchema); + } + if (value.uniqueItems) { + return unique(path.concat(["items"]), items, value, sample, resolve, validateSchema, traverseCallback); + } + return items; + } + var array_default = arrayType; + module.exports = array_default; + } + }); + + // src/lib/types/number.js + var require_number = __commonJS({ + "src/lib/types/number.js"(exports, module) { + var random = require_random(); + var env = require_constants(); + var utils = require_utils(); + function numberType(value) { + let min = typeof value.minimum === "undefined" || value.minimum === -Number.MAX_VALUE ? env.MIN_INTEGER : value.minimum; + let max = typeof value.maximum === "undefined" || value.maximum === Number.MAX_VALUE ? env.MAX_INTEGER : value.maximum; + const multipleOf = value.multipleOf; + const decimals = multipleOf && String(multipleOf).match(/e-(\d)|\.(\d+)$/); + if (decimals) { + const number = (Math.random() * random.number(0, 10) + 1) * multipleOf; + const truncate = decimals[1] || decimals[2].length; + const result = parseFloat(number.toFixed(truncate)); + const base = random.number(min, max - 1); + if (!String(result).includes(".")) { + return (base + result).toExponential(); + } + return base + result; + } + if (multipleOf) { + max = Math.floor(max / multipleOf) * multipleOf; + min = Math.ceil(min / multipleOf) * multipleOf; + } + min = utils.handleExclusiveMinimum(value, min); + max = utils.handleExclusiveMaximum(value, max); + if (min > max) { + return NaN; + } + if (multipleOf) { + let base = random.number(Math.floor(min / multipleOf), Math.floor(max / multipleOf)) * multipleOf; + while (base < min) { + base += multipleOf; + } + return base; + } + return random.number(min, max, void 0, void 0, true); + } + var number_default = numberType; + module.exports = number_default; + } + }); + + // src/lib/types/integer.js + var require_integer = __commonJS({ + "src/lib/types/integer.js"(exports, module) { + var number = require_number(); + function integerType(value) { + return Math.floor(number(__spreadValues({}, value))); + } + var integer_default = integerType; + module.exports = integer_default; + } + }); + + // src/lib/generators/words.js + var require_words = __commonJS({ + "src/lib/generators/words.js"(exports, module) { + var random = require_random(); + var LIPSUM_WORDS = `Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore +et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea +commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla +pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est +laborum`.split(/\W/); + function wordsGenerator(length) { + const words = random.shuffle(LIPSUM_WORDS); + return words.slice(0, length); + } + var words_default = wordsGenerator; + module.exports = words_default; + } + }); + + // src/lib/types/object.js + var require_object = __commonJS({ + "src/lib/types/object.js"(exports, module) { + var constants = require_constants(); + var random = require_random(); + var words = require_words(); + var utils = require_utils(); + var optionAPI = require_option(); + var anyType = { type: constants.ALLOWED_TYPES }; + function objectType(value, path, resolve, validateSchema, traverseCallback) { + const props = {}; + const properties = value.properties || {}; + const patternProperties = value.patternProperties || {}; + const requiredProperties = typeof value.required === "boolean" ? [] : (value.required || []).slice(); + const allowsAdditional = value.additionalProperties !== false; + const propertyKeys = Object.keys(properties); + const patternPropertyKeys = Object.keys(patternProperties); + const optionalProperties = propertyKeys.concat(patternPropertyKeys).reduce((_response, _key) => { + if (requiredProperties.indexOf(_key) === -1) + _response.push(_key); + return _response; + }, []); + const allProperties = requiredProperties.concat(optionalProperties); + const additionalProperties = allowsAdditional ? value.additionalProperties === true ? anyType : value.additionalProperties : value.additionalProperties; + if (!allowsAdditional && propertyKeys.length === 0 && patternPropertyKeys.length === 0 && utils.hasProperties(value, "minProperties", "maxProperties", "dependencies", "required")) { + return null; + } + if (optionAPI("requiredOnly") === true) { + requiredProperties.forEach((key) => { + if (properties[key]) { + props[key] = properties[key]; + } + }); + return traverseCallback(props, path.concat(["properties"]), resolve, value, validateSchema); + } + const optionalsProbability = optionAPI("alwaysFakeOptionals") === true ? 1 : optionAPI("optionalsProbability"); + const fixedProbabilities = optionAPI("alwaysFakeOptionals") || optionAPI("fixedProbabilities") || false; + const ignoreProperties = optionAPI("ignoreProperties") || []; + const reuseProps = optionAPI("reuseProperties"); + const fillProps = optionAPI("fillProperties"); + const max = value.maxProperties || allProperties.length + (allowsAdditional ? random.number(1, 5) : 0); + let min = Math.max(value.minProperties || 0, requiredProperties.length); + let neededExtras = Math.max(0, allProperties.length - min); + if (optionalsProbability !== null) { + if (fixedProbabilities === true) { + neededExtras = Math.round(min - requiredProperties.length + optionalsProbability * (allProperties.length - min)); + } else { + neededExtras = random.number(min - requiredProperties.length, optionalsProbability * (allProperties.length - min)); + } + } + const extraPropertiesRandomOrder = random.shuffle(optionalProperties).slice(0, neededExtras); + const extraProperties = optionalProperties.filter((_item) => { + return extraPropertiesRandomOrder.indexOf(_item) !== -1; + }); + const _props = requiredProperties.concat(extraProperties).slice(0, max); + const _defns = []; + if (value.dependencies) { + Object.keys(value.dependencies).forEach((prop) => { + const _required = value.dependencies[prop]; + if (_props.indexOf(prop) !== -1) { + if (Array.isArray(_required)) { + _required.forEach((sub) => { + if (_props.indexOf(sub) === -1) { + _props.push(sub); + } + }); + } else { + _defns.push(_required); + } + } + }); + if (_defns.length) { + delete value.dependencies; + return traverseCallback({ + allOf: _defns.concat(value) + }, path.concat(["properties"]), resolve, value, validateSchema); + } + } + const skipped = []; + const missing = []; + _props.forEach((key) => { + for (let i = 0; i < ignoreProperties.length; i += 1) { + if (ignoreProperties[i] instanceof RegExp && ignoreProperties[i].test(key) || typeof ignoreProperties[i] === "string" && ignoreProperties[i] === key || typeof ignoreProperties[i] === "function" && ignoreProperties[i](properties[key], key)) { + skipped.push(key); + return; + } + } + if (additionalProperties === false) { + if (requiredProperties.indexOf(key) !== -1) { + props[key] = properties[key]; + } + } + if (properties[key]) { + props[key] = properties[key]; + } + let found; + patternPropertyKeys.forEach((_key) => { + if (key.match(new RegExp(_key))) { + found = true; + if (props[key]) { + utils.merge(props[key], patternProperties[_key]); + } else { + props[random.randexp(key)] = patternProperties[_key]; + } + } + }); + if (!found) { + const subschema = patternProperties[key] || additionalProperties; + if (subschema && additionalProperties !== false) { + props[patternProperties[key] ? random.randexp(key) : key] = properties[key] || subschema; + } else { + missing.push(key); + } + } + }); + let current = Object.keys(props).length + (fillProps ? 0 : skipped.length); + const hash = (suffix) => random.randexp(`_?[_a-f\\d]{1,3}${suffix ? "\\$?" : ""}`); + function get(from) { + let one; + do { + if (!from.length) + break; + one = from.shift(); + } while (props[one]); + return one; + } + let minProps = min; + if (allowsAdditional && !requiredProperties.length) { + minProps = Math.max(optionalsProbability === null || additionalProperties ? random.number(fillProps ? 1 : 0, max) : 0, min); + } + while (fillProps) { + if (!(patternPropertyKeys.length || allowsAdditional)) { + break; + } + if (current >= minProps) { + break; + } + if (allowsAdditional) { + if (reuseProps && propertyKeys.length - current > minProps) { + let count = 0; + let key; + do { + count += 1; + if (count > 1e3) { + break; + } + key = get(requiredProperties) || random.pick(propertyKeys); + } while (typeof props[key] !== "undefined"); + if (typeof props[key] === "undefined") { + props[key] = properties[key]; + current += 1; + } + } else if (patternPropertyKeys.length && !additionalProperties) { + const prop = random.pick(patternPropertyKeys); + const word = random.randexp(prop); + if (!props[word]) { + props[word] = patternProperties[prop]; + current += 1; + } + } else { + const word = get(requiredProperties) || words(1) + hash(); + if (!props[word]) { + props[word] = additionalProperties || anyType; + current += 1; + } + } + } + for (let i = 0; current < min && i < patternPropertyKeys.length; i += 1) { + const _key = patternPropertyKeys[i]; + const word = random.randexp(_key); + if (!props[word]) { + props[word] = patternProperties[_key]; + current += 1; + } + } + } + if (requiredProperties.length === 0 && (!allowsAdditional || optionalsProbability === false)) { + const maximum = random.number(min, max); + for (; current < maximum; ) { + const word = get(propertyKeys); + if (word) { + props[word] = properties[word]; + } + current += 1; + } + } + return traverseCallback(props, path.concat(["properties"]), resolve, value, validateSchema); + } + var object_default = objectType; + module.exports = object_default; + } + }); + + // src/lib/generators/thunk.js + var require_thunk = __commonJS({ + "src/lib/generators/thunk.js"(exports, module) { + var words = require_words(); + var random = require_random(); + function produce() { + const length = random.number(1, 5); + return words(length).join(" "); + } + function thunkGenerator(min = 0, max = 140) { + const _min = Math.max(0, min); + const _max = random.number(_min, max); + let result = produce(); + while (result.length < _min) { + result += produce(); + } + if (result.length > _max) { + result = result.substr(0, _max); + } + return result; + } + var thunk_default = thunkGenerator; + module.exports = thunk_default; + } + }); + + // src/lib/generators/ipv4.js + var require_ipv4 = __commonJS({ + "src/lib/generators/ipv4.js"(exports, module) { + var random = require_random(); + function ipv4Generator() { + return [0, 0, 0, 0].map(() => { + return random.number(0, 255); + }).join("."); + } + var ipv4_default = ipv4Generator; + module.exports = ipv4_default; + } + }); + + // src/lib/generators/dateTime.js + var require_dateTime = __commonJS({ + "src/lib/generators/dateTime.js"(exports, module) { + var random = require_random(); + function dateTimeGenerator() { + return random.date().toISOString(); + } + var dateTime_default = dateTimeGenerator; + module.exports = dateTime_default; + } + }); + + // src/lib/generators/date.js + var require_date = __commonJS({ + "src/lib/generators/date.js"(exports, module) { + var dateTimeGenerator = require_dateTime(); + function dateGenerator() { + return dateTimeGenerator().slice(0, 10); + } + var date_default = dateGenerator; + module.exports = date_default; + } + }); + + // src/lib/generators/time.js + var require_time = __commonJS({ + "src/lib/generators/time.js"(exports, module) { + var dateTimeGenerator = require_dateTime(); + function timeGenerator() { + return dateTimeGenerator().slice(11); + } + var time_default = timeGenerator; + module.exports = time_default; + } + }); + + // src/lib/generators/coreFormat.js + var require_coreFormat = __commonJS({ + "src/lib/generators/coreFormat.js"(exports, module) { + var random = require_random(); + var FRAGMENT = "[a-zA-Z][a-zA-Z0-9+-.]*"; + var URI_PATTERN = `https?://{hostname}(?:${FRAGMENT})+`; + var PARAM_PATTERN = "(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?"; + var regexps = { + email: "[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}", + hostname: "[a-zA-Z]{1,33}\\.[a-z]{2,4}", + ipv6: "[a-f\\d]{4}(:[a-f\\d]{4}){7}", + uri: URI_PATTERN, + slug: "[a-zA-Z\\d_-]+", + "uri-reference": `${URI_PATTERN}${PARAM_PATTERN}`, + "uri-template": URI_PATTERN.replace("(?:", "(?:/\\{[a-z][:a-zA-Z0-9-]*\\}|"), + "json-pointer": `(/(?:${FRAGMENT.replace("]*", "/]*")}|~[01]))+`, + uuid: "^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$" + }; + regexps.iri = regexps["uri-reference"]; + regexps["iri-reference"] = regexps["uri-reference"]; + regexps["idn-email"] = regexps.email; + regexps["idn-hostname"] = regexps.hostname; + var ALLOWED_FORMATS = new RegExp(`\\{(${Object.keys(regexps).join("|")})\\}`); + function coreFormatGenerator(coreFormat) { + return random.randexp(regexps[coreFormat]).replace(ALLOWED_FORMATS, (match, key) => { + return random.randexp(regexps[key]); + }); + } + var coreFormat_default = coreFormatGenerator; + module.exports = coreFormat_default; + } + }); + + // src/lib/types/string.js + var require_string = __commonJS({ + "src/lib/types/string.js"(exports, module) { + var thunk = require_thunk(); + var ipv4 = require_ipv4(); + var dateTime = require_dateTime(); + var date = require_date(); + var time = require_time(); + var coreFormat = require_coreFormat(); + var optionAPI = require_option(); + var format = require_format(); + var random = require_random(); + var utils = require_utils(); + function generateFormat(value, invalid) { + const callback = format(value.format); + if (typeof callback === "function") { + return callback(value); + } + switch (value.format) { + case "date-time": + case "datetime": + return dateTime(); + case "date": + return date(); + case "time": + return time(); + case "ipv4": + return ipv4(); + case "regex": + return ".+?"; + case "email": + case "hostname": + case "ipv6": + case "uri": + case "uri-reference": + case "iri": + case "iri-reference": + case "idn-email": + case "idn-hostname": + case "json-pointer": + case "slug": + case "uri-template": + case "uuid": + return coreFormat(value.format); + default: + if (typeof callback === "undefined") { + if (optionAPI("failOnInvalidFormat")) { + throw new Error(`unknown registry key ${utils.short(value.format)}`); + } else { + return invalid(); + } + } + throw new Error(`unsupported format '${value.format}'`); + } + } + function stringType(value) { + const output = utils.typecast("string", value, (opts) => { + if (value.format) { + return generateFormat(value, () => thunk(opts.minLength, opts.maxLength)); + } + if (value.pattern) { + return random.randexp(value.pattern); + } + return thunk(opts.minLength, opts.maxLength); + }); + return output; + } + var string_default = stringType; + module.exports = string_default; + } + }); + + // src/lib/types/index.js + var require_types2 = __commonJS({ + "src/lib/types/index.js"(exports, module) { + var _boolean = require_boolean2(); + var _null = require_null2(); + var _array = require_array(); + var _integer = require_integer(); + var _number = require_number(); + var _object = require_object(); + var _string = require_string(); + var typeMap = { + boolean: _boolean, + null: _null, + array: _array, + integer: _integer, + number: _number, + object: _object, + string: _string + }; + var json_schema_faker_default = typeMap; + module.exports = json_schema_faker_default; + } + }); + + // src/lib/core/traverse.js + var require_traverse = __commonJS({ + "src/lib/core/traverse.js"(exports, module) { + var _ = require_lodash(); + var utils = require_utils(); + var random = require_random(); + var ParseError = require_error(); + var inferType = require_infer(); + var types = require_types2(); + var optionAPI = require_option(); + var ALL_TYPES = require_constants(); + function getMeta({ $comment: comment, title, description }) { + return Object.entries({ comment, title, description }).filter(([, value]) => value).reduce((memo, [k, v]) => { + memo[k] = v; + return memo; + }, {}); + } + function traverse(schema, path, resolve, rootSchema, validateSchema) { + schema = resolve(schema, null, path); + if (schema && (schema.oneOf || schema.anyOf || schema.allOf)) { + schema = resolve(schema, null, path); + } + if (!schema) { + throw new Error(`Cannot traverse at '${path.join(".")}', given '${JSON.stringify(rootSchema)}'`); + } + const context = __spreadProps(__spreadValues({}, getMeta(schema)), { + schemaPath: path + }); + if (path[path.length - 1] !== "properties") { + if (optionAPI("useExamplesValue") && Array.isArray(schema.examples)) { + let randomExample; + const fixedExamples = schema.examples.concat("default" in schema ? [schema.default] : []); + if (optionAPI("pickFirstFromExamples")) { + randomExample = fixedExamples[0]; + } else { + randomExample = random.pick(fixedExamples); + } + if (validateSchema) { + let result; + let clonedSchema; + if (optionAPI("avoidExampleItemsLength") && _.get(schema, "type") === "array") { + clonedSchema = _.clone(schema); + _.unset(clonedSchema, "minItems"); + _.unset(clonedSchema, "maxItems"); + result = validateSchema(clonedSchema, randomExample, optionAPI("validationOptions")); + } else { + result = validateSchema(schema, randomExample, optionAPI("validationOptions")); + } + if (result && result.length === 0) { + if (optionAPI("validationOptions") && optionAPI("validationOptions").ignoreUnresolvedVariables) { + return { + value: randomExample, + context + }; + } + return { + value: utils.typecast(null, schema, () => randomExample), + context + }; + } + } else { + console.warn("Taking example from schema without validation"); + return { + value: utils.typecast(null, schema, () => randomExample), + context + }; + } + } + if (optionAPI("useExamplesValue") && !_.isNil(schema.example)) { + if (validateSchema) { + let result; + let clonedSchema; + if (optionAPI("avoidExampleItemsLength") && _.get(schema, "type") === "array") { + clonedSchema = _.clone(schema); + _.unset(clonedSchema, "minItems"); + _.unset(clonedSchema, "maxItems"); + result = validateSchema(clonedSchema, schema.example, optionAPI("validationOptions")); + } else { + result = validateSchema(schema, schema.example, optionAPI("validationOptions")); + } + if (result && result.length === 0) { + if (optionAPI("validationOptions") && optionAPI("validationOptions").ignoreUnresolvedVariables) { + return { + value: schema.example, + context + }; + } + return { + value: utils.typecast(null, schema, () => schema.example), + context + }; + } + } else { + console.warn("Taking example from schema without validation"); + return { value: utils.typecast(null, schema, () => schema.example), context }; + } + } + if (optionAPI("useDefaultValue") && "default" in schema) { + if (!(_.has(schema.default, "type") && _.includes(ALL_TYPES, schema.default.type))) { + if (schema.default !== "" || !optionAPI("replaceEmptyByRandomValue")) { + return { value: schema.default, context }; + } + } + } + if ("template" in schema) { + return { value: utils.template(schema.template, rootSchema), context }; + } + if ("const" in schema) { + return { value: schema.const, context }; + } + } + if (schema.not && typeof schema.not === "object") { + schema = utils.notValue(schema.not, utils.omitProps(schema, ["not"])); + if (schema.type && schema.type === "object") { + const { value, context: innerContext } = traverse(schema, path.concat(["not"]), resolve, rootSchema, validateSchema); + return { value: utils.clean(value, schema, false), context: __spreadProps(__spreadValues({}, context), { items: innerContext }) }; + } + } + if (typeof schema.thunk === "function") { + const { value, context: innerContext } = traverse(schema.thunk(rootSchema), path, resolve, void 0, validateSchema); + return { value, context: __spreadProps(__spreadValues({}, context), { items: innerContext }) }; + } + if (schema.jsonPath) { + return { value: schema, context }; + } + let type = schema.type; + if (Array.isArray(type)) { + type = random.pick(type); + } else if (typeof type === "undefined") { + type = inferType(schema, path) || type; + if (type) { + schema.type = type; + } + } + if (typeof schema.generate === "function") { + const retVal = utils.typecast(null, schema, () => schema.generate(rootSchema, path)); + const retType = retVal === null ? "null" : typeof retVal; + if (retType === type || retType === "number" && type === "integer" || Array.isArray(retVal) && type === "array") { + return { value: retVal, context }; + } + } + if (typeof schema.pattern === "string") { + return { value: utils.typecast("string", schema, () => random.randexp(schema.pattern)), context }; + } + if (Array.isArray(schema.enum)) { + return { value: utils.typecast(null, schema, () => random.pick(schema.enum)), context }; + } + if (typeof type === "string") { + if (!types[type]) { + if (optionAPI("failOnInvalidTypes")) { + throw new ParseError(`unknown primitive ${utils.short(type)}`, path.concat(["type"])); + } else { + const value = optionAPI("defaultInvalidTypeProduct"); + if (typeof value === "string" && types[value]) { + return { value: types[value](schema, path, resolve, traverse), context }; + } + return { value, context }; + } + } else { + try { + const innerResult = types[type](schema, path, resolve, validateSchema, traverse); + if (type === "array") { + return { + value: innerResult.map(({ value }) => value), + context: __spreadProps(__spreadValues({}, context), { + items: innerResult.map(Array.isArray(schema.items) ? ({ context: c }) => c : ({ context: c }) => __spreadProps(__spreadValues({}, c), { + schemaPath: c.schemaPath.slice(0, -1) + })) + }) + }; + } + if (type === "object") { + return { value: innerResult.value, context: __spreadProps(__spreadValues({}, context), { items: innerResult.context }) }; + } + return { value: innerResult, context }; + } catch (e) { + if (typeof e.path === "undefined") { + throw new ParseError(e.stack, path); + } + throw e; + } + } + } + let valueCopy = {}; + let contextCopy = __spreadValues({}, context); + if (Array.isArray(schema)) { + valueCopy = []; + } + const pruneProperties = optionAPI("pruneProperties") || []; + Object.keys(schema).forEach((prop) => { + if (pruneProperties.includes(prop)) + return; + if (typeof schema[prop] === "object" && prop !== "definitions") { + const { value, context: innerContext } = traverse(schema[prop], path.concat([prop]), resolve, valueCopy, validateSchema); + valueCopy[prop] = utils.clean(value, schema[prop], false); + contextCopy[prop] = innerContext; + } else { + valueCopy[prop] = schema[prop]; + } + }); + return { value: valueCopy, context: contextCopy }; + } + var traverse_default = traverse; + module.exports = traverse_default; + } + }); + + // src/lib/core/buildResolveSchema.js + var require_buildResolveSchema = __commonJS({ + "src/lib/core/buildResolveSchema.js"(exports, module) { + var optionAPI = require_option(); + var random = require_random(); + var utils = require_utils(); + var buildResolveSchema = ({ + refs, + schema, + container, + synchronous, + refDepthMax, + refDepthMin + }) => { + const recursiveUtil = {}; + const seenRefs = {}; + let depth = 0; + let lastRef; + let lastPath; + recursiveUtil.resolveSchema = (sub, index, rootPath) => { + if (sub === null || sub === void 0) { + return null; + } + if (typeof sub.generate === "function") { + return sub; + } + const _id = sub.$id || sub.id; + if (typeof _id === "string") { + delete sub.id; + delete sub.$id; + delete sub.$schema; + } + if (typeof sub.$ref === "string") { + const maxDepth = Math.max(refDepthMin, refDepthMax) - 1; + if (sub.$ref === "#" || seenRefs[sub.$ref] < 0 || lastRef === sub.$ref && ++depth > maxDepth) { + if (sub.$ref !== "#" && lastPath && lastPath.length === rootPath.length) { + return utils.getLocalRef(schema, sub.$ref, synchronous && refs); + } + delete sub.$ref; + return sub; + } + if (typeof seenRefs[sub.$ref] === "undefined") { + seenRefs[sub.$ref] = random.number(refDepthMin, refDepthMax) - 1; + } + lastPath = rootPath; + lastRef = sub.$ref; + let ref; + if (sub.$ref.indexOf("#/") === -1) { + ref = refs[sub.$ref] || null; + } else { + ref = utils.getLocalRef(schema, sub.$ref, synchronous && refs) || null; + } + let fixed; + if (typeof ref !== "undefined") { + if (!ref && optionAPI("ignoreMissingRefs") !== true) { + throw new Error(`Reference not found: ${sub.$ref}`); + } + seenRefs[sub.$ref] -= 1; + utils.merge(sub, ref || {}); + fixed = synchronous && ref && ref.$ref; + } + if (!fixed) + delete sub.$ref; + return sub; + } + if (Array.isArray(sub.allOf)) { + const schemas = sub.allOf; + delete sub.allOf; + schemas.forEach((subSchema) => { + const _sub = recursiveUtil.resolveSchema(subSchema, null, rootPath); + utils.merge(sub, typeof _sub.thunk === "function" ? _sub.thunk(sub) : _sub); + if (Array.isArray(sub.allOf)) { + recursiveUtil.resolveSchema(sub, index, rootPath); + } + }); + } + if (Array.isArray(sub.oneOf || sub.anyOf)) { + const mix = sub.oneOf || sub.anyOf; + if (sub.enum && sub.oneOf) { + sub.enum = sub.enum.filter((x) => utils.validate(x, mix)); + } + return { + thunk(rootSchema) { + const copy = utils.omitProps(sub, ["anyOf", "oneOf"]); + const fixed = random.pick(mix); + utils.merge(copy, fixed); + mix.forEach((omit) => { + if (omit.required && omit !== fixed) { + omit.required.forEach((key) => { + const includesKey = copy.required && copy.required.includes(key); + if (copy.properties && !includesKey) { + delete copy.properties[key]; + } + if (rootSchema && rootSchema.properties) { + delete rootSchema.properties[key]; + } + }); + } + }); + return copy; + } + }; + } + Object.keys(sub).forEach((prop) => { + if ((Array.isArray(sub[prop]) || typeof sub[prop] === "object") && !utils.isKey(prop)) { + sub[prop] = recursiveUtil.resolveSchema(sub[prop], prop, rootPath.concat(prop)); + } + }); + if (rootPath) { + const lastProp = rootPath[rootPath.length - 1]; + if (lastProp === "properties" || lastProp === "items") { + return sub; + } + } + return container.wrap(sub); + }; + return recursiveUtil; + }; + var buildResolveSchema_default = buildResolveSchema; + module.exports = buildResolveSchema_default; + } + }); + + // src/lib/core/run.js + var require_run = __commonJS({ + "src/lib/core/run.js"(exports, module) { + var { getDependencies } = require_vendor(); + var optionAPI = require_option(); + var traverse = require_traverse(); + var random = require_random(); + var utils = require_utils(); + var buildResolveSchema = require_buildResolveSchema(); + function pick(data) { + return Array.isArray(data) ? random.pick(data) : data; + } + function cycle(data, reverse) { + if (!Array.isArray(data)) { + return data; + } + const value = reverse ? data.pop() : data.shift(); + if (reverse) { + data.unshift(value); + } else { + data.push(value); + } + return value; + } + function resolve(obj, data, values, property) { + if (!obj || typeof obj !== "object") { + return obj; + } + if (!values) { + values = {}; + } + if (!data) { + data = obj; + } + if (Array.isArray(obj)) { + return obj.map((x) => resolve(x, data, values, property)); + } + if (obj.jsonPath) { + const { JSONPath } = getDependencies(); + const params = typeof obj.jsonPath !== "object" ? { path: obj.jsonPath } : obj.jsonPath; + params.group = obj.group || params.group || property; + params.cycle = obj.cycle || params.cycle || false; + params.reverse = obj.reverse || params.reverse || false; + params.count = obj.count || params.count || 1; + const key = `${params.group}__${params.path}`; + if (!values[key]) { + if (params.count > 1) { + values[key] = JSONPath(params.path, data).slice(0, params.count); + } else { + values[key] = JSONPath(params.path, data); + } + } + if (params.cycle || params.reverse) { + return cycle(values[key], params.reverse); + } + return pick(values[key]); + } + Object.keys(obj).forEach((k) => { + obj[k] = resolve(obj[k], data, values, k); + }); + return obj; + } + function run(refs, schema, container, synchronous, validateSchema) { + if (Object.prototype.toString.call(schema) !== "[object Object]") { + throw new Error(`Invalid input, expecting object but given ${typeof schema}`); + } + const refDepthMin = optionAPI("refDepthMin") || 0; + const refDepthMax = optionAPI("refDepthMax") || 3; + try { + const { resolveSchema } = buildResolveSchema({ + refs, + schema, + container, + synchronous, + refDepthMin, + refDepthMax + }); + const result = traverse(utils.clone(schema), [], resolveSchema, void 0, validateSchema); + if (optionAPI("resolveJsonPath")) { + return { + value: resolve(result.value), + context: result.context + }; + } + return result; + } catch (e) { + if (e.path) { + throw new Error(`${e.message} in /${e.path.join("/")}`); + } else { + throw e; + } + } + } + var run_default = run; + module.exports = run_default; + } + }); + + // src/lib/renderers/js.js + var require_js = __commonJS({ + "src/lib/renderers/js.js"(exports, module) { + function renderJS(res) { + return res.value; + } + var js_default = renderJS; + module.exports = js_default; + } + }); + + // node_modules/yaml/dist/PlainValue-ec8e588e.js + var require_PlainValue_ec8e588e = __commonJS({ + "node_modules/yaml/dist/PlainValue-ec8e588e.js"(exports) { + "use strict"; + var Char = { + ANCHOR: "&", + COMMENT: "#", + TAG: "!", + DIRECTIVES_END: "-", + DOCUMENT_END: "." + }; + var Type = { + ALIAS: "ALIAS", + BLANK_LINE: "BLANK_LINE", + BLOCK_FOLDED: "BLOCK_FOLDED", + BLOCK_LITERAL: "BLOCK_LITERAL", + COMMENT: "COMMENT", + DIRECTIVE: "DIRECTIVE", + DOCUMENT: "DOCUMENT", + FLOW_MAP: "FLOW_MAP", + FLOW_SEQ: "FLOW_SEQ", + MAP: "MAP", + MAP_KEY: "MAP_KEY", + MAP_VALUE: "MAP_VALUE", + PLAIN: "PLAIN", + QUOTE_DOUBLE: "QUOTE_DOUBLE", + QUOTE_SINGLE: "QUOTE_SINGLE", + SEQ: "SEQ", + SEQ_ITEM: "SEQ_ITEM" + }; + var defaultTagPrefix = "tag:yaml.org,2002:"; + var defaultTags = { + MAP: "tag:yaml.org,2002:map", + SEQ: "tag:yaml.org,2002:seq", + STR: "tag:yaml.org,2002:str" + }; + function findLineStarts(src) { + const ls = [0]; + let offset = src.indexOf("\n"); + while (offset !== -1) { + offset += 1; + ls.push(offset); + offset = src.indexOf("\n", offset); + } + return ls; + } + function getSrcInfo(cst) { + let lineStarts, src; + if (typeof cst === "string") { + lineStarts = findLineStarts(cst); + src = cst; + } else { + if (Array.isArray(cst)) + cst = cst[0]; + if (cst && cst.context) { + if (!cst.lineStarts) + cst.lineStarts = findLineStarts(cst.context.src); + lineStarts = cst.lineStarts; + src = cst.context.src; + } + } + return { + lineStarts, + src + }; + } + function getLinePos(offset, cst) { + if (typeof offset !== "number" || offset < 0) + return null; + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !src || offset > src.length) + return null; + for (let i = 0; i < lineStarts.length; ++i) { + const start = lineStarts[i]; + if (offset < start) { + return { + line: i, + col: offset - lineStarts[i - 1] + 1 + }; + } + if (offset === start) + return { + line: i + 1, + col: 1 + }; + } + const line = lineStarts.length; + return { + line, + col: offset - lineStarts[line - 1] + 1 + }; + } + function getLine(line, cst) { + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !(line >= 1) || line > lineStarts.length) + return null; + const start = lineStarts[line - 1]; + let end = lineStarts[line]; + while (end && end > start && src[end - 1] === "\n") + --end; + return src.slice(start, end); + } + function getPrettyContext({ + start, + end + }, cst, maxWidth = 80) { + let src = getLine(start.line, cst); + if (!src) + return null; + let { + col + } = start; + if (src.length > maxWidth) { + if (col <= maxWidth - 10) { + src = src.substr(0, maxWidth - 1) + "\u2026"; + } else { + const halfWidth = Math.round(maxWidth / 2); + if (src.length > col + halfWidth) + src = src.substr(0, col + halfWidth - 1) + "\u2026"; + col -= src.length - maxWidth; + src = "\u2026" + src.substr(1 - maxWidth); + } + } + let errLen = 1; + let errEnd = ""; + if (end) { + if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { + errLen = end.col - start.col; + } else { + errLen = Math.min(src.length + 1, maxWidth) - col; + errEnd = "\u2026"; + } + } + const offset = col > 1 ? " ".repeat(col - 1) : ""; + const err = "^".repeat(errLen); + return `${src} +${offset}${err}${errEnd}`; + } + var Range = class { + static copy(orig) { + return new Range(orig.start, orig.end); + } + constructor(start, end) { + this.start = start; + this.end = end || start; + } + isEmpty() { + return typeof this.start !== "number" || !this.end || this.end <= this.start; + } + setOrigRange(cr, offset) { + const { + start, + end + } = this; + if (cr.length === 0 || end <= cr[0]) { + this.origStart = start; + this.origEnd = end; + return offset; + } + let i = offset; + while (i < cr.length) { + if (cr[i] > start) + break; + else + ++i; + } + this.origStart = start + i; + const nextOffset = i; + while (i < cr.length) { + if (cr[i] >= end) + break; + else + ++i; + } + this.origEnd = end + i; + return nextOffset; + } + }; + var Node = class { + static addStringTerminator(src, offset, str) { + if (str[str.length - 1] === "\n") + return str; + const next = Node.endOfWhiteSpace(src, offset); + return next >= src.length || src[next] === "\n" ? str + "\n" : str; + } + static atDocumentBoundary(src, offset, sep) { + const ch0 = src[offset]; + if (!ch0) + return true; + const prev = src[offset - 1]; + if (prev && prev !== "\n") + return false; + if (sep) { + if (ch0 !== sep) + return false; + } else { + if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) + return false; + } + const ch1 = src[offset + 1]; + const ch2 = src[offset + 2]; + if (ch1 !== ch0 || ch2 !== ch0) + return false; + const ch3 = src[offset + 3]; + return !ch3 || ch3 === "\n" || ch3 === " " || ch3 === " "; + } + static endOfIdentifier(src, offset) { + let ch = src[offset]; + const isVerbatim = ch === "<"; + const notOk = isVerbatim ? ["\n", " ", " ", ">"] : ["\n", " ", " ", "[", "]", "{", "}", ","]; + while (ch && notOk.indexOf(ch) === -1) + ch = src[offset += 1]; + if (isVerbatim && ch === ">") + offset += 1; + return offset; + } + static endOfIndent(src, offset) { + let ch = src[offset]; + while (ch === " ") + ch = src[offset += 1]; + return offset; + } + static endOfLine(src, offset) { + let ch = src[offset]; + while (ch && ch !== "\n") + ch = src[offset += 1]; + return offset; + } + static endOfWhiteSpace(src, offset) { + let ch = src[offset]; + while (ch === " " || ch === " ") + ch = src[offset += 1]; + return offset; + } + static startOfLine(src, offset) { + let ch = src[offset - 1]; + if (ch === "\n") + return offset; + while (ch && ch !== "\n") + ch = src[offset -= 1]; + return offset + 1; + } + static endOfBlockIndent(src, indent, lineStart) { + const inEnd = Node.endOfIndent(src, lineStart); + if (inEnd > lineStart + indent) { + return inEnd; + } else { + const wsEnd = Node.endOfWhiteSpace(src, inEnd); + const ch = src[wsEnd]; + if (!ch || ch === "\n") + return wsEnd; + } + return null; + } + static atBlank(src, offset, endAsBlank) { + const ch = src[offset]; + return ch === "\n" || ch === " " || ch === " " || endAsBlank && !ch; + } + static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { + if (!ch || indentDiff < 0) + return false; + if (indentDiff > 0) + return true; + return indicatorAsIndent && ch === "-"; + } + static normalizeOffset(src, offset) { + const ch = src[offset]; + return !ch ? offset : ch !== "\n" && src[offset - 1] === "\n" ? offset - 1 : Node.endOfWhiteSpace(src, offset); + } + static foldNewline(src, offset, indent) { + let inCount = 0; + let error = false; + let fold = ""; + let ch = src[offset + 1]; + while (ch === " " || ch === " " || ch === "\n") { + switch (ch) { + case "\n": + inCount = 0; + offset += 1; + fold += "\n"; + break; + case " ": + if (inCount <= indent) + error = true; + offset = Node.endOfWhiteSpace(src, offset + 2) - 1; + break; + case " ": + inCount += 1; + offset += 1; + break; + } + ch = src[offset + 1]; + } + if (!fold) + fold = " "; + if (ch && inCount <= indent) + error = true; + return { + fold, + offset, + error + }; + } + constructor(type, props, context) { + Object.defineProperty(this, "context", { + value: context || null, + writable: true + }); + this.error = null; + this.range = null; + this.valueRange = null; + this.props = props || []; + this.type = type; + this.value = null; + } + getPropValue(idx, key, skipKey) { + if (!this.context) + return null; + const { + src + } = this.context; + const prop = this.props[idx]; + return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; + } + get anchor() { + for (let i = 0; i < this.props.length; ++i) { + const anchor = this.getPropValue(i, Char.ANCHOR, true); + if (anchor != null) + return anchor; + } + return null; + } + get comment() { + const comments = []; + for (let i = 0; i < this.props.length; ++i) { + const comment = this.getPropValue(i, Char.COMMENT, true); + if (comment != null) + comments.push(comment); + } + return comments.length > 0 ? comments.join("\n") : null; + } + commentHasRequiredWhitespace(start) { + const { + src + } = this.context; + if (this.header && start === this.header.end) + return false; + if (!this.valueRange) + return false; + const { + end + } = this.valueRange; + return start !== end || Node.atBlank(src, end - 1); + } + get hasComment() { + if (this.context) { + const { + src + } = this.context; + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] === Char.COMMENT) + return true; + } + } + return false; + } + get hasProps() { + if (this.context) { + const { + src + } = this.context; + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] !== Char.COMMENT) + return true; + } + } + return false; + } + get includesTrailingLines() { + return false; + } + get jsonLike() { + const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; + return jsonLikeTypes.indexOf(this.type) !== -1; + } + get rangeAsLinePos() { + if (!this.range || !this.context) + return void 0; + const start = getLinePos(this.range.start, this.context.root); + if (!start) + return void 0; + const end = getLinePos(this.range.end, this.context.root); + return { + start, + end + }; + } + get rawValue() { + if (!this.valueRange || !this.context) + return null; + const { + start, + end + } = this.valueRange; + return this.context.src.slice(start, end); + } + get tag() { + for (let i = 0; i < this.props.length; ++i) { + const tag = this.getPropValue(i, Char.TAG, false); + if (tag != null) { + if (tag[1] === "<") { + return { + verbatim: tag.slice(2, -1) + }; + } else { + const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); + return { + handle, + suffix + }; + } + } + } + return null; + } + get valueRangeContainsNewline() { + if (!this.valueRange || !this.context) + return false; + const { + start, + end + } = this.valueRange; + const { + src + } = this.context; + for (let i = start; i < end; ++i) { + if (src[i] === "\n") + return true; + } + return false; + } + parseComment(start) { + const { + src + } = this.context; + if (src[start] === Char.COMMENT) { + const end = Node.endOfLine(src, start + 1); + const commentRange = new Range(start, end); + this.props.push(commentRange); + return end; + } + return start; + } + setOrigRanges(cr, offset) { + if (this.range) + offset = this.range.setOrigRange(cr, offset); + if (this.valueRange) + this.valueRange.setOrigRange(cr, offset); + this.props.forEach((prop) => prop.setOrigRange(cr, offset)); + return offset; + } + toString() { + const { + context: { + src + }, + range, + value + } = this; + if (value != null) + return value; + const str = src.slice(range.start, range.end); + return Node.addStringTerminator(src, range.end, str); + } + }; + var YAMLError = class extends Error { + constructor(name, source, message) { + if (!message || !(source instanceof Node)) + throw new Error(`Invalid arguments for new ${name}`); + super(); + this.name = name; + this.message = message; + this.source = source; + } + makePretty() { + if (!this.source) + return; + this.nodeType = this.source.type; + const cst = this.source.context && this.source.context.root; + if (typeof this.offset === "number") { + this.range = new Range(this.offset, this.offset + 1); + const start = cst && getLinePos(this.offset, cst); + if (start) { + const end = { + line: start.line, + col: start.col + 1 + }; + this.linePos = { + start, + end + }; + } + delete this.offset; + } else { + this.range = this.source.range; + this.linePos = this.source.rangeAsLinePos; + } + if (this.linePos) { + const { + line, + col + } = this.linePos.start; + this.message += ` at line ${line}, column ${col}`; + const ctx = cst && getPrettyContext(this.linePos, cst); + if (ctx) + this.message += `: + +${ctx} +`; + } + delete this.source; + } + }; + var YAMLReferenceError = class extends YAMLError { + constructor(source, message) { + super("YAMLReferenceError", source, message); + } + }; + var YAMLSemanticError = class extends YAMLError { + constructor(source, message) { + super("YAMLSemanticError", source, message); + } + }; + var YAMLSyntaxError = class extends YAMLError { + constructor(source, message) { + super("YAMLSyntaxError", source, message); + } + }; + var YAMLWarning = class extends YAMLError { + constructor(source, message) { + super("YAMLWarning", source, message); + } + }; + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + var PlainValue = class extends Node { + static endOfLine(src, start, inFlow) { + let ch = src[start]; + let offset = start; + while (ch && ch !== "\n") { + if (inFlow && (ch === "[" || ch === "]" || ch === "{" || ch === "}" || ch === ",")) + break; + const next = src[offset + 1]; + if (ch === ":" && (!next || next === "\n" || next === " " || next === " " || inFlow && next === ",")) + break; + if ((ch === " " || ch === " ") && next === "#") + break; + offset += 1; + ch = next; + } + return offset; + } + get strValue() { + if (!this.valueRange || !this.context) + return null; + let { + start, + end + } = this.valueRange; + const { + src + } = this.context; + let ch = src[end - 1]; + while (start < end && (ch === "\n" || ch === " " || ch === " ")) + ch = src[--end - 1]; + let str = ""; + for (let i = start; i < end; ++i) { + const ch2 = src[i]; + if (ch2 === "\n") { + const { + fold, + offset + } = Node.foldNewline(src, i, -1); + str += fold; + i = offset; + } else if (ch2 === " " || ch2 === " ") { + const wsStart = i; + let next = src[i + 1]; + while (i < end && (next === " " || next === " ")) { + i += 1; + next = src[i + 1]; + } + if (next !== "\n") + str += i > wsStart ? src.slice(wsStart, i + 1) : ch2; + } else { + str += ch2; + } + } + const ch0 = src[start]; + switch (ch0) { + case " ": { + const msg = "Plain value cannot start with a tab character"; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + case "@": + case "`": { + const msg = `Plain value cannot start with reserved character ${ch0}`; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + default: + return str; + } + } + parseBlockValue(start) { + const { + indent, + inFlow, + src + } = this.context; + let offset = start; + let valueEnd = start; + for (let ch = src[offset]; ch === "\n"; ch = src[offset]) { + if (Node.atDocumentBoundary(src, offset + 1)) + break; + const end = Node.endOfBlockIndent(src, indent, offset + 1); + if (end === null || src[end] === "#") + break; + if (src[end] === "\n") { + offset = end; + } else { + valueEnd = PlainValue.endOfLine(src, end, inFlow); + offset = valueEnd; + } + } + if (this.valueRange.isEmpty()) + this.valueRange.start = start; + this.valueRange.end = valueEnd; + return valueEnd; + } + parse(context, start) { + this.context = context; + const { + inFlow, + src + } = context; + let offset = start; + const ch = src[offset]; + if (ch && ch !== "#" && ch !== "\n") { + offset = PlainValue.endOfLine(src, start, inFlow); + } + this.valueRange = new Range(start, offset); + offset = Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + if (!this.hasComment || this.valueRange.isEmpty()) { + offset = this.parseBlockValue(offset); + } + return offset; + } + }; + exports.Char = Char; + exports.Node = Node; + exports.PlainValue = PlainValue; + exports.Range = Range; + exports.Type = Type; + exports.YAMLError = YAMLError; + exports.YAMLReferenceError = YAMLReferenceError; + exports.YAMLSemanticError = YAMLSemanticError; + exports.YAMLSyntaxError = YAMLSyntaxError; + exports.YAMLWarning = YAMLWarning; + exports._defineProperty = _defineProperty; + exports.defaultTagPrefix = defaultTagPrefix; + exports.defaultTags = defaultTags; + } + }); + + // node_modules/yaml/dist/resolveSeq-d03cb037.js + var require_resolveSeq_d03cb037 = __commonJS({ + "node_modules/yaml/dist/resolveSeq-d03cb037.js"(exports) { + "use strict"; + var PlainValue = require_PlainValue_ec8e588e(); + function addCommentBefore(str, indent, comment) { + if (!comment) + return str; + const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); + return `#${cc} +${indent}${str}`; + } + function addComment(str, indent, comment) { + return !comment ? str : comment.indexOf("\n") === -1 ? `${str} #${comment}` : `${str} +` + comment.replace(/^/gm, `${indent || ""}#`); + } + var Node = class { + }; + function toJSON(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJSON(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + const anchor = ctx && ctx.anchors && ctx.anchors.get(value); + if (anchor) + ctx.onCreate = (res2) => { + anchor.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (anchor && ctx.onCreate) + ctx.onCreate(res); + return res; + } + if ((!ctx || !ctx.keep) && typeof value === "bigint") + return Number(value); + return value; + } + var Scalar = class extends Node { + constructor(value) { + super(); + this.value = value; + } + toJSON(arg, ctx) { + return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + const o = {}; + Object.defineProperty(o, k, { + value: v, + writable: true, + enumerable: true, + configurable: true + }); + v = o; + } + } + return schema.createNode(v, false); + } + var isEmptyPath = (path) => path == null || typeof path === "object" && path[Symbol.iterator]().next().done; + var Collection = class extends Node { + constructor(schema) { + super(); + PlainValue._defineProperty(this, "items", []); + this.schema = schema; + } + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (node instanceof Collection) + node.addIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + deleteIn([key, ...rest]) { + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (node instanceof Collection) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + getIn([key, ...rest], keepScalar) { + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && node instanceof Scalar ? node.value : node; + else + return node instanceof Collection ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues() { + return this.items.every((node) => { + if (!node || node.type !== "PAIR") + return false; + const n = node.value; + return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + hasIn([key, ...rest]) { + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return node instanceof Collection ? node.hasIn(rest) : false; + } + setIn([key, ...rest], value) { + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (node instanceof Collection) + node.setIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + toJSON() { + return null; + } + toString(ctx, { + blockItem, + flowChars, + isMap, + itemIndent + }, onComment, onChompKeep) { + const { + indent, + indentStep, + stringify + } = ctx; + const inFlow = this.type === PlainValue.Type.FLOW_MAP || this.type === PlainValue.Type.FLOW_SEQ || ctx.inFlow; + if (inFlow) + itemIndent += indentStep; + const allNullValues = isMap && this.hasAllNullValues(); + ctx = Object.assign({}, ctx, { + allNullValues, + indent: itemIndent, + inFlow, + type: null + }); + let chompKeep = false; + let hasItemWithNewLine = false; + const nodes = this.items.reduce((nodes2, item, i) => { + let comment; + if (item) { + if (!chompKeep && item.spaceBefore) + nodes2.push({ + type: "comment", + str: "" + }); + if (item.commentBefore) + item.commentBefore.match(/^.*$/gm).forEach((line) => { + nodes2.push({ + type: "comment", + str: `#${line}` + }); + }); + if (item.comment) + comment = item.comment; + if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) + hasItemWithNewLine = true; + } + chompKeep = false; + let str2 = stringify(item, ctx, () => comment = null, () => chompKeep = true); + if (inFlow && !hasItemWithNewLine && str2.includes("\n")) + hasItemWithNewLine = true; + if (inFlow && i < this.items.length - 1) + str2 += ","; + str2 = addComment(str2, itemIndent, comment); + if (chompKeep && (comment || inFlow)) + chompKeep = false; + nodes2.push({ + type: "item", + str: str2 + }); + return nodes2; + }, []); + let str; + if (nodes.length === 0) { + str = flowChars.start + flowChars.end; + } else if (inFlow) { + const { + start, + end + } = flowChars; + const strings = nodes.map((n) => n.str); + if (hasItemWithNewLine || strings.reduce((sum, str2) => sum + str2.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { + str = start; + for (const s of strings) { + str += s ? ` +${indentStep}${indent}${s}` : "\n"; + } + str += ` +${indent}${end}`; + } else { + str = `${start} ${strings.join(" ")} ${end}`; + } + } else { + const strings = nodes.map(blockItem); + str = strings.shift(); + for (const s of strings) + str += s ? ` +${indent}${s}` : "\n"; + } + if (this.comment) { + str += "\n" + this.comment.replace(/^/gm, `${indent}#`); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + }; + PlainValue._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); + function asItemIndex(key) { + let idx = key instanceof Scalar ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return Number.isInteger(idx) && idx >= 0 ? idx : null; + } + var YAMLSeq = class extends Collection { + add(value) { + this.items.push(value); + } + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && it instanceof Scalar ? it.value : it; + } + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx && ctx.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJSON(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return super.toString(ctx, { + blockItem: (n) => n.type === "comment" ? n.str : `- ${n.str}`, + flowChars: { + start: "[", + end: "]" + }, + isMap: false, + itemIndent: (ctx.indent || "") + " " + }, onComment, onChompKeep); + } + }; + var stringifyKey = (key, jsKey, ctx) => { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (key instanceof Node && ctx && ctx.doc) + return key.toString({ + anchors: Object.create(null), + doc: ctx.doc, + indent: "", + indentStep: ctx.indentStep, + inFlow: true, + inStringifyKey: true, + stringify: ctx.stringify + }); + return JSON.stringify(jsKey); + }; + var Pair = class extends Node { + constructor(key, value = null) { + super(); + this.key = key; + this.value = value; + this.type = Pair.Type.PAIR; + } + get commentBefore() { + return this.key instanceof Node ? this.key.commentBefore : void 0; + } + set commentBefore(cb) { + if (this.key == null) + this.key = new Scalar(null); + if (this.key instanceof Node) + this.key.commentBefore = cb; + else { + const msg = "Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node."; + throw new Error(msg); + } + } + addToJSMap(ctx, map) { + const key = toJSON(this.key, "", ctx); + if (map instanceof Map) { + const value = toJSON(this.value, key, ctx); + map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else { + const stringKey = stringifyKey(this.key, key, ctx); + const value = toJSON(this.value, stringKey, ctx); + if (stringKey in map) + Object.defineProperty(map, stringKey, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else + map[stringKey] = value; + } + return map; + } + toJSON(_, ctx) { + const pair = ctx && ctx.mapAsMap ? new Map() : {}; + return this.addToJSMap(ctx, pair); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx || !ctx.doc) + return JSON.stringify(this); + const { + indent: indentSize, + indentSeq, + simpleKeys + } = ctx.doc.options; + let { + key, + value + } = this; + let keyComment = key instanceof Node && key.comment; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (key instanceof Collection) { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node ? key instanceof Collection || key.type === PlainValue.Type.BLOCK_FOLDED || key.type === PlainValue.Type.BLOCK_LITERAL : typeof key === "object")); + const { + doc, + indent, + indentStep, + stringify + } = ctx; + ctx = Object.assign({}, ctx, { + implicitKey: !explicitKey, + indent: indent + indentStep + }); + let chompKeep = false; + let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); + str = addComment(str, ctx.indent, keyComment); + if (!explicitKey && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.allNullValues && !simpleKeys) { + if (this.comment) { + str = addComment(str, ctx.indent, this.comment); + if (onComment) + onComment(); + } else if (chompKeep && !keyComment && onChompKeep) + onChompKeep(); + return ctx.inFlow && !explicitKey ? str : `? ${str}`; + } + str = explicitKey ? `? ${str} +${indent}:` : `${str}:`; + if (this.comment) { + str = addComment(str, ctx.indent, this.comment); + if (onComment) + onComment(); + } + let vcb = ""; + let valueComment = null; + if (value instanceof Node) { + if (value.spaceBefore) + vcb = "\n"; + if (value.commentBefore) { + const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); + vcb += ` +${cs}`; + } + valueComment = value.comment; + } else if (value && typeof value === "object") { + value = doc.schema.createNode(value, true); + } + ctx.implicitKey = false; + if (!explicitKey && !this.comment && value instanceof Scalar) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { + ctx.indent = ctx.indent.substr(2); + } + const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); + let ws = " "; + if (vcb || this.comment) { + ws = `${vcb} +${ctx.indent}`; + } else if (!explicitKey && value instanceof Collection) { + const flow = valueStr[0] === "[" || valueStr[0] === "{"; + if (!flow || valueStr.includes("\n")) + ws = ` +${ctx.indent}`; + } else if (valueStr[0] === "\n") + ws = ""; + if (chompKeep && !valueComment && onChompKeep) + onChompKeep(); + return addComment(str + ws + valueStr, ctx.indent, valueComment); + } + }; + PlainValue._defineProperty(Pair, "Type", { + PAIR: "PAIR", + MERGE_PAIR: "MERGE_PAIR" + }); + var getAliasCount = (node, anchors) => { + if (node instanceof Alias) { + const anchor = anchors.get(node.source); + return anchor.count * anchor.aliasCount; + } else if (node instanceof Collection) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(item, anchors); + if (c > count) + count = c; + } + return count; + } else if (node instanceof Pair) { + const kc = getAliasCount(node.key, anchors); + const vc = getAliasCount(node.value, anchors); + return Math.max(kc, vc); + } + return 1; + }; + var Alias = class extends Node { + static stringify({ + range, + source + }, { + anchors, + doc, + implicitKey, + inStringifyKey + }) { + let anchor = Object.keys(anchors).find((a) => anchors[a] === source); + if (!anchor && inStringifyKey) + anchor = doc.anchors.getName(source) || doc.anchors.newName(); + if (anchor) + return `*${anchor}${implicitKey ? " " : ""}`; + const msg = doc.anchors.getName(source) ? "Alias node must be after source node" : "Source node not found for alias node"; + throw new Error(`${msg} [${range}]`); + } + constructor(source) { + super(); + this.source = source; + this.type = PlainValue.Type.ALIAS; + } + set tag(t) { + throw new Error("Alias nodes cannot have tags"); + } + toJSON(arg, ctx) { + if (!ctx) + return toJSON(this.source, arg, ctx); + const { + anchors, + maxAliasCount + } = ctx; + const anchor = anchors.get(this.source); + if (!anchor || anchor.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + if (this.cstNode) + throw new PlainValue.YAMLReferenceError(this.cstNode, msg); + else + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + anchor.count += 1; + if (anchor.aliasCount === 0) + anchor.aliasCount = getAliasCount(this.source, anchors); + if (anchor.count * anchor.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + if (this.cstNode) + throw new PlainValue.YAMLReferenceError(this.cstNode, msg); + else + throw new ReferenceError(msg); + } + } + return anchor.res; + } + toString(ctx) { + return Alias.stringify(this, ctx); + } + }; + PlainValue._defineProperty(Alias, "default", true); + function findPair(items, key) { + const k = key instanceof Scalar ? key.value : key; + for (const it of items) { + if (it instanceof Pair) { + if (it.key === key || it.key === k) + return it; + if (it.key && it.key.value === k) + return it; + } + } + return void 0; + } + var YAMLMap = class extends Collection { + add(pair, overwrite) { + if (!pair) + pair = new Pair(pair); + else if (!(pair instanceof Pair)) + pair = new Pair(pair.key || pair, pair.value); + const prev = findPair(this.items, pair.key); + const sortEntries = this.schema && this.schema.sortMapEntries; + if (prev) { + if (overwrite) + prev.value = pair.value; + else + throw new Error(`Key ${pair.key} already set`); + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(pair, item) < 0); + if (i === -1) + this.items.push(pair); + else + this.items.splice(i, 0, pair); + } else { + this.items.push(pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it && it.value; + return !keepScalar && node instanceof Scalar ? node.value : node; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; + if (ctx && ctx.onCreate) + ctx.onCreate(map); + for (const item of this.items) + item.addToJSMap(ctx, map); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!(item instanceof Pair)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + return super.toString(ctx, { + blockItem: (n) => n.str, + flowChars: { + start: "{", + end: "}" + }, + isMap: true, + itemIndent: ctx.indent || "" + }, onComment, onChompKeep); + } + }; + var MERGE_KEY = "<<"; + var Merge = class extends Pair { + constructor(pair) { + if (pair instanceof Pair) { + let seq = pair.value; + if (!(seq instanceof YAMLSeq)) { + seq = new YAMLSeq(); + seq.items.push(pair.value); + seq.range = pair.value.range; + } + super(pair.key, seq); + this.range = pair.range; + } else { + super(new Scalar(MERGE_KEY), new YAMLSeq()); + } + this.type = Pair.Type.MERGE_PAIR; + } + addToJSMap(ctx, map) { + for (const { + source + } of this.value.items) { + if (!(source instanceof YAMLMap)) + throw new Error("Merge sources must be maps"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) + map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + } + return map; + } + toString(ctx, onComment) { + const seq = this.value; + if (seq.items.length > 1) + return super.toString(ctx, onComment); + this.value = seq.items[0]; + const str = super.toString(ctx, onComment); + this.value = seq; + return str; + } + }; + var binaryOptions = { + defaultType: PlainValue.Type.BLOCK_LITERAL, + lineWidth: 76 + }; + var boolOptions = { + trueStr: "true", + falseStr: "false" + }; + var intOptions = { + asBigInt: false + }; + var nullOptions = { + nullStr: "null" + }; + var strOptions = { + defaultType: PlainValue.Type.PLAIN, + doubleQuoted: { + jsonEncoding: false, + minMultiLineLength: 40 + }, + fold: { + lineWidth: 80, + minContentWidth: 20 + } + }; + function resolveScalar(str, tags, scalarFallback) { + for (const { + format, + test, + resolve + } of tags) { + if (test) { + const match = str.match(test); + if (match) { + let res = resolve.apply(null, match); + if (!(res instanceof Scalar)) + res = new Scalar(res); + if (format) + res.format = format; + return res; + } + } + } + if (scalarFallback) + str = scalarFallback(str); + return new Scalar(str); + } + var FOLD_FLOW = "flow"; + var FOLD_BLOCK = "block"; + var FOLD_QUOTED = "quoted"; + var consumeMoreIndentedLines = (text, i) => { + let ch = text[i + 1]; + while (ch === " " || ch === " ") { + do { + ch = text[i += 1]; + } while (ch && ch !== "\n"); + ch = text[i + 1]; + } + return i; + }; + function foldFlowLines(text, indent, mode, { + indentAtStart, + lineWidth = 80, + minContentWidth = 20, + onFold, + onOverflow + }) { + if (!lineWidth || lineWidth < 0) + return text; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i); + end = i + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; + } + var getFoldOptions = ({ + indentAtStart + }) => indentAtStart ? Object.assign({ + indentAtStart + }, strOptions.fold) : strOptions.fold; + var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; + } + function doubleQuotedString(value, ctx) { + const { + implicitKey + } = ctx; + const { + jsonEncoding, + minMultiLineLength + } = strOptions.doubleQuoted; + const json = JSON.stringify(value); + if (jsonEncoding) + return json; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); + } + function singleQuotedString(value, ctx) { + if (ctx.implicitKey) { + if (/\n/.test(value)) + return doubleQuotedString(value, ctx); + } else { + if (/[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + } + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); + } + function blockString({ + comment, + type, + value + }, ctx, onComment, onChompKeep) { + if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { + return doubleQuotedString(value, ctx); + } + const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : ""); + const indentSize = indent ? "2" : "1"; + const literal = type === PlainValue.Type.BLOCK_FOLDED ? false : type === PlainValue.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); + let header = literal ? "|" : ">"; + if (!value) + return header + "\n"; + let wsStart = ""; + let wsEnd = ""; + value = value.replace(/[\n\t ]*$/, (ws) => { + const n = ws.indexOf("\n"); + if (n === -1) { + header += "-"; + } else if (value === ws || n !== ws.length - 1) { + header += "+"; + if (onChompKeep) + onChompKeep(); + } + wsEnd = ws.replace(/\n$/, ""); + return ""; + }).replace(/^[\n ]*/, (ws) => { + if (ws.indexOf(" ") !== -1) + header += indentSize; + const m = ws.match(/ +$/); + if (m) { + wsStart = ws.slice(0, -m[0].length); + return m[0]; + } else { + wsStart = ws; + return ""; + } + }); + if (wsEnd) + wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); + if (wsStart) + wsStart = wsStart.replace(/\n+/g, `$&${indent}`); + if (comment) { + header += " #" + comment.replace(/ ?[\r\n]+/g, " "); + if (onComment) + onComment(); + } + if (!value) + return `${header}${indentSize} +${indent}${wsEnd}`; + if (literal) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header} +${indent}${wsStart}${value}${wsEnd}`; + } + value = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); + return `${header} +${indent}${body}`; + } + function plainString(item, ctx, onComment, onChompKeep) { + const { + comment, + type, + value + } = item; + const { + actualString, + implicitKey, + indent, + inFlow + } = ctx; + if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { + return doubleQuotedString(value, ctx); + } + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || value.indexOf("\n") === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== PlainValue.Type.PLAIN && value.indexOf("\n") !== -1) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (indent === "" && containsDocumentMarker(value)) { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const { + tags + } = ctx.doc.schema; + const resolved = resolveScalar(str, tags, tags.scalarFallback).value; + if (typeof resolved !== "string") + return doubleQuotedString(value, ctx); + } + const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); + if (comment && !inFlow && (body.indexOf("\n") !== -1 || comment.indexOf("\n") !== -1)) { + if (onComment) + onComment(); + return addCommentBefore(body, indent, comment); + } + return body; + } + function stringifyString(item, ctx, onComment, onChompKeep) { + const { + defaultType + } = strOptions; + const { + implicitKey, + inFlow + } = ctx; + let { + type, + value + } = item; + if (typeof value !== "string") { + value = String(value); + item = Object.assign({}, item, { + value + }); + } + const _stringify = (_type) => { + switch (_type) { + case PlainValue.Type.BLOCK_FOLDED: + case PlainValue.Type.BLOCK_LITERAL: + return blockString(item, ctx, onComment, onChompKeep); + case PlainValue.Type.QUOTE_DOUBLE: + return doubleQuotedString(value, ctx); + case PlainValue.Type.QUOTE_SINGLE: + return singleQuotedString(value, ctx); + case PlainValue.Type.PLAIN: + return plainString(item, ctx, onComment, onChompKeep); + default: + return null; + } + }; + if (type !== PlainValue.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { + type = PlainValue.Type.QUOTE_DOUBLE; + } else if ((implicitKey || inFlow) && (type === PlainValue.Type.BLOCK_FOLDED || type === PlainValue.Type.BLOCK_LITERAL)) { + type = PlainValue.Type.QUOTE_DOUBLE; + } + let res = _stringify(type); + if (res === null) { + res = _stringify(defaultType); + if (res === null) + throw new Error(`Unsupported default string type ${defaultType}`); + } + return res; + } + function stringifyNumber({ + format, + minFractionDigits, + tag, + value + }) { + if (typeof value === "bigint") + return String(value); + if (!isFinite(value)) + return isNaN(value) ? ".nan" : value < 0 ? "-.inf" : ".inf"; + let n = JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; + } + function checkFlowCollectionEnd(errors, cst) { + let char, name; + switch (cst.type) { + case PlainValue.Type.FLOW_MAP: + char = "}"; + name = "flow map"; + break; + case PlainValue.Type.FLOW_SEQ: + char = "]"; + name = "flow sequence"; + break; + default: + errors.push(new PlainValue.YAMLSemanticError(cst, "Not a flow collection!?")); + return; + } + let lastItem; + for (let i = cst.items.length - 1; i >= 0; --i) { + const item = cst.items[i]; + if (!item || item.type !== PlainValue.Type.COMMENT) { + lastItem = item; + break; + } + } + if (lastItem && lastItem.char !== char) { + const msg = `Expected ${name} to end with ${char}`; + let err; + if (typeof lastItem.offset === "number") { + err = new PlainValue.YAMLSemanticError(cst, msg); + err.offset = lastItem.offset + 1; + } else { + err = new PlainValue.YAMLSemanticError(lastItem, msg); + if (lastItem.range && lastItem.range.end) + err.offset = lastItem.range.end - lastItem.range.start; + } + errors.push(err); + } + } + function checkFlowCommentSpace(errors, comment) { + const prev = comment.context.src[comment.range.start - 1]; + if (prev !== "\n" && prev !== " " && prev !== " ") { + const msg = "Comments must be separated from other tokens by white space characters"; + errors.push(new PlainValue.YAMLSemanticError(comment, msg)); + } + } + function getLongKeyError(source, key) { + const sk = String(key); + const k = sk.substr(0, 8) + "..." + sk.substr(-8); + return new PlainValue.YAMLSemanticError(source, `The "${k}" key is too long`); + } + function resolveComments(collection, comments) { + for (const { + afterKey, + before, + comment + } of comments) { + let item = collection.items[before]; + if (!item) { + if (comment !== void 0) { + if (collection.comment) + collection.comment += "\n" + comment; + else + collection.comment = comment; + } + } else { + if (afterKey && item.value) + item = item.value; + if (comment === void 0) { + if (afterKey || !item.commentBefore) + item.spaceBefore = true; + } else { + if (item.commentBefore) + item.commentBefore += "\n" + comment; + else + item.commentBefore = comment; + } + } + } + } + function resolveString(doc, node) { + const res = node.strValue; + if (!res) + return ""; + if (typeof res === "string") + return res; + res.errors.forEach((error) => { + if (!error.source) + error.source = node; + doc.errors.push(error); + }); + return res.str; + } + function resolveTagHandle(doc, node) { + const { + handle, + suffix + } = node.tag; + let prefix = doc.tagPrefixes.find((p) => p.handle === handle); + if (!prefix) { + const dtp = doc.getDefaults().tagPrefixes; + if (dtp) + prefix = dtp.find((p) => p.handle === handle); + if (!prefix) + throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); + } + if (!suffix) + throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); + if (handle === "!" && (doc.version || doc.options.version) === "1.0") { + if (suffix[0] === "^") { + doc.warnings.push(new PlainValue.YAMLWarning(node, "YAML 1.0 ^ tag expansion is not supported")); + return suffix; + } + if (/[:/]/.test(suffix)) { + const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); + return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; + } + } + return prefix.prefix + decodeURIComponent(suffix); + } + function resolveTagName(doc, node) { + const { + tag, + type + } = node; + let nonSpecific = false; + if (tag) { + const { + handle, + suffix, + verbatim + } = tag; + if (verbatim) { + if (verbatim !== "!" && verbatim !== "!!") + return verbatim; + const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; + doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); + } else if (handle === "!" && !suffix) { + nonSpecific = true; + } else { + try { + return resolveTagHandle(doc, node); + } catch (error) { + doc.errors.push(error); + } + } + } + switch (type) { + case PlainValue.Type.BLOCK_FOLDED: + case PlainValue.Type.BLOCK_LITERAL: + case PlainValue.Type.QUOTE_DOUBLE: + case PlainValue.Type.QUOTE_SINGLE: + return PlainValue.defaultTags.STR; + case PlainValue.Type.FLOW_MAP: + case PlainValue.Type.MAP: + return PlainValue.defaultTags.MAP; + case PlainValue.Type.FLOW_SEQ: + case PlainValue.Type.SEQ: + return PlainValue.defaultTags.SEQ; + case PlainValue.Type.PLAIN: + return nonSpecific ? PlainValue.defaultTags.STR : null; + default: + return null; + } + } + function resolveByTagName(doc, node, tagName) { + const { + tags + } = doc.schema; + const matchWithTest = []; + for (const tag of tags) { + if (tag.tag === tagName) { + if (tag.test) + matchWithTest.push(tag); + else { + const res = tag.resolve(doc, node); + return res instanceof Collection ? res : new Scalar(res); + } + } + } + const str = resolveString(doc, node); + if (typeof str === "string" && matchWithTest.length > 0) + return resolveScalar(str, matchWithTest, tags.scalarFallback); + return null; + } + function getFallbackTagName({ + type + }) { + switch (type) { + case PlainValue.Type.FLOW_MAP: + case PlainValue.Type.MAP: + return PlainValue.defaultTags.MAP; + case PlainValue.Type.FLOW_SEQ: + case PlainValue.Type.SEQ: + return PlainValue.defaultTags.SEQ; + default: + return PlainValue.defaultTags.STR; + } + } + function resolveTag(doc, node, tagName) { + try { + const res = resolveByTagName(doc, node, tagName); + if (res) { + if (tagName && node.tag) + res.tag = tagName; + return res; + } + } catch (error) { + if (!error.source) + error.source = node; + doc.errors.push(error); + return null; + } + try { + const fallback = getFallbackTagName(node); + if (!fallback) + throw new Error(`The tag ${tagName} is unavailable`); + const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; + doc.warnings.push(new PlainValue.YAMLWarning(node, msg)); + const res = resolveByTagName(doc, node, fallback); + res.tag = tagName; + return res; + } catch (error) { + const refError = new PlainValue.YAMLReferenceError(node, error.message); + refError.stack = error.stack; + doc.errors.push(refError); + return null; + } + } + var isCollectionItem = (node) => { + if (!node) + return false; + const { + type + } = node; + return type === PlainValue.Type.MAP_KEY || type === PlainValue.Type.MAP_VALUE || type === PlainValue.Type.SEQ_ITEM; + }; + function resolveNodeProps(errors, node) { + const comments = { + before: [], + after: [] + }; + let hasAnchor = false; + let hasTag = false; + const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; + for (const { + start, + end + } of props) { + switch (node.context.src[start]) { + case PlainValue.Char.COMMENT: { + if (!node.commentHasRequiredWhitespace(start)) { + const msg = "Comments must be separated from other tokens by white space characters"; + errors.push(new PlainValue.YAMLSemanticError(node, msg)); + } + const { + header, + valueRange + } = node; + const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; + cc.push(node.context.src.slice(start + 1, end)); + break; + } + case PlainValue.Char.ANCHOR: + if (hasAnchor) { + const msg = "A node can have at most one anchor"; + errors.push(new PlainValue.YAMLSemanticError(node, msg)); + } + hasAnchor = true; + break; + case PlainValue.Char.TAG: + if (hasTag) { + const msg = "A node can have at most one tag"; + errors.push(new PlainValue.YAMLSemanticError(node, msg)); + } + hasTag = true; + break; + } + } + return { + comments, + hasAnchor, + hasTag + }; + } + function resolveNodeValue(doc, node) { + const { + anchors, + errors, + schema + } = doc; + if (node.type === PlainValue.Type.ALIAS) { + const name = node.rawValue; + const src = anchors.getNode(name); + if (!src) { + const msg = `Aliased anchor not found: ${name}`; + errors.push(new PlainValue.YAMLReferenceError(node, msg)); + return null; + } + const res = new Alias(src); + anchors._cstAliases.push(res); + return res; + } + const tagName = resolveTagName(doc, node); + if (tagName) + return resolveTag(doc, node, tagName); + if (node.type !== PlainValue.Type.PLAIN) { + const msg = `Failed to resolve ${node.type} node here`; + errors.push(new PlainValue.YAMLSyntaxError(node, msg)); + return null; + } + try { + const str = resolveString(doc, node); + return resolveScalar(str, schema.tags, schema.tags.scalarFallback); + } catch (error) { + if (!error.source) + error.source = node; + errors.push(error); + return null; + } + } + function resolveNode(doc, node) { + if (!node) + return null; + if (node.error) + doc.errors.push(node.error); + const { + comments, + hasAnchor, + hasTag + } = resolveNodeProps(doc.errors, node); + if (hasAnchor) { + const { + anchors + } = doc; + const name = node.anchor; + const prev = anchors.getNode(name); + if (prev) + anchors.map[anchors.newName(name)] = prev; + anchors.map[name] = node; + } + if (node.type === PlainValue.Type.ALIAS && (hasAnchor || hasTag)) { + const msg = "An alias node must not specify any properties"; + doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); + } + const res = resolveNodeValue(doc, node); + if (res) { + res.range = [node.range.start, node.range.end]; + if (doc.options.keepCstNodes) + res.cstNode = node; + if (doc.options.keepNodeTypes) + res.type = node.type; + const cb = comments.before.join("\n"); + if (cb) { + res.commentBefore = res.commentBefore ? `${res.commentBefore} +${cb}` : cb; + } + const ca = comments.after.join("\n"); + if (ca) + res.comment = res.comment ? `${res.comment} +${ca}` : ca; + } + return node.resolved = res; + } + function resolveMap(doc, cst) { + if (cst.type !== PlainValue.Type.MAP && cst.type !== PlainValue.Type.FLOW_MAP) { + const msg = `A ${cst.type} node cannot be resolved as a mapping`; + doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); + return null; + } + const { + comments, + items + } = cst.type === PlainValue.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); + const map = new YAMLMap(); + map.items = items; + resolveComments(map, comments); + let hasCollectionKey = false; + for (let i = 0; i < items.length; ++i) { + const { + key: iKey + } = items[i]; + if (iKey instanceof Collection) + hasCollectionKey = true; + if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { + items[i] = new Merge(items[i]); + const sources = items[i].value.items; + let error = null; + sources.some((node) => { + if (node instanceof Alias) { + const { + type + } = node.source; + if (type === PlainValue.Type.MAP || type === PlainValue.Type.FLOW_MAP) + return false; + return error = "Merge nodes aliases can only point to maps"; + } + return error = "Merge nodes can only have Alias nodes as values"; + }); + if (error) + doc.errors.push(new PlainValue.YAMLSemanticError(cst, error)); + } else { + for (let j = i + 1; j < items.length; ++j) { + const { + key: jKey + } = items[j]; + if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, "value") && iKey.value === jKey.value) { + const msg = `Map keys must be unique; "${iKey}" is repeated`; + doc.errors.push(new PlainValue.YAMLSemanticError(cst, msg)); + break; + } + } + } + } + if (hasCollectionKey && !doc.options.mapAsMap) { + const warn = "Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this."; + doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); + } + cst.resolved = map; + return map; + } + var valueHasPairComment = ({ + context: { + lineStart, + node, + src + }, + props + }) => { + if (props.length === 0) + return false; + const { + start + } = props[0]; + if (node && start > node.valueRange.start) + return false; + if (src[start] !== PlainValue.Char.COMMENT) + return false; + for (let i = lineStart; i < start; ++i) + if (src[i] === "\n") + return false; + return true; + }; + function resolvePairComment(item, pair) { + if (!valueHasPairComment(item)) + return; + const comment = item.getPropValue(0, PlainValue.Char.COMMENT, true); + let found = false; + const cb = pair.value.commentBefore; + if (cb && cb.startsWith(comment)) { + pair.value.commentBefore = cb.substr(comment.length + 1); + found = true; + } else { + const cc = pair.value.comment; + if (!item.node && cc && cc.startsWith(comment)) { + pair.value.comment = cc.substr(comment.length + 1); + found = true; + } + } + if (found) + pair.comment = comment; + } + function resolveBlockMapItems(doc, cst) { + const comments = []; + const items = []; + let key = void 0; + let keyStart = null; + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + switch (item.type) { + case PlainValue.Type.BLANK_LINE: + comments.push({ + afterKey: !!key, + before: items.length + }); + break; + case PlainValue.Type.COMMENT: + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + break; + case PlainValue.Type.MAP_KEY: + if (key !== void 0) + items.push(new Pair(key)); + if (item.error) + doc.errors.push(item.error); + key = resolveNode(doc, item.node); + keyStart = null; + break; + case PlainValue.Type.MAP_VALUE: + { + if (key === void 0) + key = null; + if (item.error) + doc.errors.push(item.error); + if (!item.context.atLineStart && item.node && item.node.type === PlainValue.Type.MAP && !item.node.context.atLineStart) { + const msg = "Nested mappings are not allowed in compact mappings"; + doc.errors.push(new PlainValue.YAMLSemanticError(item.node, msg)); + } + let valueNode = item.node; + if (!valueNode && item.props.length > 0) { + valueNode = new PlainValue.PlainValue(PlainValue.Type.PLAIN, []); + valueNode.context = { + parent: item, + src: item.context.src + }; + const pos = item.range.start + 1; + valueNode.range = { + start: pos, + end: pos + }; + valueNode.valueRange = { + start: pos, + end: pos + }; + if (typeof item.range.origStart === "number") { + const origPos = item.range.origStart + 1; + valueNode.range.origStart = valueNode.range.origEnd = origPos; + valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; + } + } + const pair = new Pair(key, resolveNode(doc, valueNode)); + resolvePairComment(item, pair); + items.push(pair); + if (key && typeof keyStart === "number") { + if (item.range.start > keyStart + 1024) + doc.errors.push(getLongKeyError(cst, key)); + } + key = void 0; + keyStart = null; + } + break; + default: + if (key !== void 0) + items.push(new Pair(key)); + key = resolveNode(doc, item); + keyStart = item.range.start; + if (item.error) + doc.errors.push(item.error); + next: + for (let j = i + 1; ; ++j) { + const nextItem = cst.items[j]; + switch (nextItem && nextItem.type) { + case PlainValue.Type.BLANK_LINE: + case PlainValue.Type.COMMENT: + continue next; + case PlainValue.Type.MAP_VALUE: + break next; + default: { + const msg = "Implicit map keys need to be followed by map values"; + doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); + break next; + } + } + } + if (item.valueRangeContainsNewline) { + const msg = "Implicit map keys need to be on a single line"; + doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); + } + } + } + if (key !== void 0) + items.push(new Pair(key)); + return { + comments, + items + }; + } + function resolveFlowMapItems(doc, cst) { + const comments = []; + const items = []; + let key = void 0; + let explicitKey = false; + let next = "{"; + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + if (typeof item.char === "string") { + const { + char, + offset + } = item; + if (char === "?" && key === void 0 && !explicitKey) { + explicitKey = true; + next = ":"; + continue; + } + if (char === ":") { + if (key === void 0) + key = null; + if (next === ":") { + next = ","; + continue; + } + } else { + if (explicitKey) { + if (key === void 0 && char !== ",") + key = null; + explicitKey = false; + } + if (key !== void 0) { + items.push(new Pair(key)); + key = void 0; + if (char === ",") { + next = ":"; + continue; + } + } + } + if (char === "}") { + if (i === cst.items.length - 1) + continue; + } else if (char === next) { + next = ":"; + continue; + } + const msg = `Flow map contains an unexpected ${char}`; + const err = new PlainValue.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } else if (item.type === PlainValue.Type.BLANK_LINE) { + comments.push({ + afterKey: !!key, + before: items.length + }); + } else if (item.type === PlainValue.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + } else if (key === void 0) { + if (next === ",") + doc.errors.push(new PlainValue.YAMLSemanticError(item, "Separator , missing in flow map")); + key = resolveNode(doc, item); + } else { + if (next !== ",") + doc.errors.push(new PlainValue.YAMLSemanticError(item, "Indicator : missing in flow map entry")); + items.push(new Pair(key, resolveNode(doc, item))); + key = void 0; + explicitKey = false; + } + } + checkFlowCollectionEnd(doc.errors, cst); + if (key !== void 0) + items.push(new Pair(key)); + return { + comments, + items + }; + } + function resolveSeq(doc, cst) { + if (cst.type !== PlainValue.Type.SEQ && cst.type !== PlainValue.Type.FLOW_SEQ) { + const msg = `A ${cst.type} node cannot be resolved as a sequence`; + doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); + return null; + } + const { + comments, + items + } = cst.type === PlainValue.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); + const seq = new YAMLSeq(); + seq.items = items; + resolveComments(seq, comments); + if (!doc.options.mapAsMap && items.some((it) => it instanceof Pair && it.key instanceof Collection)) { + const warn = "Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this."; + doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); + } + cst.resolved = seq; + return seq; + } + function resolveBlockSeqItems(doc, cst) { + const comments = []; + const items = []; + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + switch (item.type) { + case PlainValue.Type.BLANK_LINE: + comments.push({ + before: items.length + }); + break; + case PlainValue.Type.COMMENT: + comments.push({ + comment: item.comment, + before: items.length + }); + break; + case PlainValue.Type.SEQ_ITEM: + if (item.error) + doc.errors.push(item.error); + items.push(resolveNode(doc, item.node)); + if (item.hasProps) { + const msg = "Sequence items cannot have tags or anchors before the - indicator"; + doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); + } + break; + default: + if (item.error) + doc.errors.push(item.error); + doc.errors.push(new PlainValue.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); + } + } + return { + comments, + items + }; + } + function resolveFlowSeqItems(doc, cst) { + const comments = []; + const items = []; + let explicitKey = false; + let key = void 0; + let keyStart = null; + let next = "["; + let prevItem = null; + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + if (typeof item.char === "string") { + const { + char, + offset + } = item; + if (char !== ":" && (explicitKey || key !== void 0)) { + if (explicitKey && key === void 0) + key = next ? items.pop() : null; + items.push(new Pair(key)); + explicitKey = false; + key = void 0; + keyStart = null; + } + if (char === next) { + next = null; + } else if (!next && char === "?") { + explicitKey = true; + } else if (next !== "[" && char === ":" && key === void 0) { + if (next === ",") { + key = items.pop(); + if (key instanceof Pair) { + const msg = "Chaining flow sequence pairs is invalid"; + const err = new PlainValue.YAMLSemanticError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + if (!explicitKey && typeof keyStart === "number") { + const keyEnd = item.range ? item.range.start : item.offset; + if (keyEnd > keyStart + 1024) + doc.errors.push(getLongKeyError(cst, key)); + const { + src + } = prevItem.context; + for (let i2 = keyStart; i2 < keyEnd; ++i2) + if (src[i2] === "\n") { + const msg = "Implicit keys of flow sequence pairs need to be on a single line"; + doc.errors.push(new PlainValue.YAMLSemanticError(prevItem, msg)); + break; + } + } + } else { + key = null; + } + keyStart = null; + explicitKey = false; + next = null; + } else if (next === "[" || char !== "]" || i < cst.items.length - 1) { + const msg = `Flow sequence contains an unexpected ${char}`; + const err = new PlainValue.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + } else if (item.type === PlainValue.Type.BLANK_LINE) { + comments.push({ + before: items.length + }); + } else if (item.type === PlainValue.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + comment: item.comment, + before: items.length + }); + } else { + if (next) { + const msg = `Expected a ${next} in flow sequence`; + doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); + } + const value = resolveNode(doc, item); + if (key === void 0) { + items.push(value); + prevItem = item; + } else { + items.push(new Pair(key, value)); + key = void 0; + } + keyStart = item.range.start; + next = ","; + } + } + checkFlowCollectionEnd(doc.errors, cst); + if (key !== void 0) + items.push(new Pair(key)); + return { + comments, + items + }; + } + exports.Alias = Alias; + exports.Collection = Collection; + exports.Merge = Merge; + exports.Node = Node; + exports.Pair = Pair; + exports.Scalar = Scalar; + exports.YAMLMap = YAMLMap; + exports.YAMLSeq = YAMLSeq; + exports.addComment = addComment; + exports.binaryOptions = binaryOptions; + exports.boolOptions = boolOptions; + exports.findPair = findPair; + exports.intOptions = intOptions; + exports.isEmptyPath = isEmptyPath; + exports.nullOptions = nullOptions; + exports.resolveMap = resolveMap; + exports.resolveNode = resolveNode; + exports.resolveSeq = resolveSeq; + exports.resolveString = resolveString; + exports.strOptions = strOptions; + exports.stringifyNumber = stringifyNumber; + exports.stringifyString = stringifyString; + exports.toJSON = toJSON; + } + }); + + // node_modules/yaml/dist/warnings-1000a372.js + var require_warnings_1000a372 = __commonJS({ + "node_modules/yaml/dist/warnings-1000a372.js"(exports) { + "use strict"; + var PlainValue = require_PlainValue_ec8e588e(); + var resolveSeq = require_resolveSeq_d03cb037(); + var binary = { + identify: (value) => value instanceof Uint8Array, + default: false, + tag: "tag:yaml.org,2002:binary", + resolve: (doc, node) => { + const src = resolveSeq.resolveString(doc, node); + if (typeof Buffer === "function") { + return Buffer.from(src, "base64"); + } else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } else { + const msg = "This environment does not support reading binary tags; either Buffer or atob is required"; + doc.errors.push(new PlainValue.YAMLReferenceError(node, msg)); + return null; + } + }, + options: resolveSeq.binaryOptions, + stringify: ({ + comment, + type, + value + }, ctx, onComment, onChompKeep) => { + let src; + if (typeof Buffer === "function") { + src = value instanceof Buffer ? value.toString("base64") : Buffer.from(value.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < value.length; ++i) + s += String.fromCharCode(value[i]); + src = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + if (!type) + type = resolveSeq.binaryOptions.defaultType; + if (type === PlainValue.Type.QUOTE_DOUBLE) { + value = src; + } else { + const { + lineWidth + } = resolveSeq.binaryOptions; + const n = Math.ceil(src.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = src.substr(o, lineWidth); + } + value = lines.join(type === PlainValue.Type.BLOCK_LITERAL ? "\n" : " "); + } + return resolveSeq.stringifyString({ + comment, + type, + value + }, ctx, onComment, onChompKeep); + } + }; + function parsePairs(doc, cst) { + const seq = resolveSeq.resolveSeq(doc, cst); + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (item instanceof resolveSeq.Pair) + continue; + else if (item instanceof resolveSeq.YAMLMap) { + if (item.items.length > 1) { + const msg = "Each pair must have its own sequence indicator"; + throw new PlainValue.YAMLSemanticError(cst, msg); + } + const pair = item.items[0] || new resolveSeq.Pair(); + if (item.commentBefore) + pair.commentBefore = pair.commentBefore ? `${item.commentBefore} +${pair.commentBefore}` : item.commentBefore; + if (item.comment) + pair.comment = pair.comment ? `${item.comment} +${pair.comment}` : item.comment; + item = pair; + } + seq.items[i] = item instanceof resolveSeq.Pair ? item : new resolveSeq.Pair(item); + } + return seq; + } + function createPairs(schema, iterable, ctx) { + const pairs2 = new resolveSeq.YAMLSeq(schema); + pairs2.tag = "tag:yaml.org,2002:pairs"; + for (const it of iterable) { + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else + throw new TypeError(`Expected { key: value } tuple: ${it}`); + } else { + key = it; + } + const pair = schema.createPair(key, value, ctx); + pairs2.items.push(pair); + } + return pairs2; + } + var pairs = { + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: parsePairs, + createNode: createPairs + }; + var YAMLOMap = class extends resolveSeq.YAMLSeq { + constructor() { + super(); + PlainValue._defineProperty(this, "add", resolveSeq.YAMLMap.prototype.add.bind(this)); + PlainValue._defineProperty(this, "delete", resolveSeq.YAMLMap.prototype.delete.bind(this)); + PlainValue._defineProperty(this, "get", resolveSeq.YAMLMap.prototype.get.bind(this)); + PlainValue._defineProperty(this, "has", resolveSeq.YAMLMap.prototype.has.bind(this)); + PlainValue._defineProperty(this, "set", resolveSeq.YAMLMap.prototype.set.bind(this)); + this.tag = YAMLOMap.tag; + } + toJSON(_, ctx) { + const map = new Map(); + if (ctx && ctx.onCreate) + ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (pair instanceof resolveSeq.Pair) { + key = resolveSeq.toJSON(pair.key, "", ctx); + value = resolveSeq.toJSON(pair.value, key, ctx); + } else { + key = resolveSeq.toJSON(pair, "", ctx); + } + if (map.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map.set(key, value); + } + return map; + } + }; + PlainValue._defineProperty(YAMLOMap, "tag", "tag:yaml.org,2002:omap"); + function parseOMap(doc, cst) { + const pairs2 = parsePairs(doc, cst); + const seenKeys = []; + for (const { + key + } of pairs2.items) { + if (key instanceof resolveSeq.Scalar) { + if (seenKeys.includes(key.value)) { + const msg = "Ordered maps must not include duplicate keys"; + throw new PlainValue.YAMLSemanticError(cst, msg); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + } + function createOMap(schema, iterable, ctx) { + const pairs2 = createPairs(schema, iterable, ctx); + const omap2 = new YAMLOMap(); + omap2.items = pairs2.items; + return omap2; + } + var omap = { + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve: parseOMap, + createNode: createOMap + }; + var YAMLSet = class extends resolveSeq.YAMLMap { + constructor() { + super(); + this.tag = YAMLSet.tag; + } + add(key) { + const pair = key instanceof resolveSeq.Pair ? key : new resolveSeq.Pair(key); + const prev = resolveSeq.findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + get(key, keepPair) { + const pair = resolveSeq.findPair(this.items, key); + return !keepPair && pair instanceof resolveSeq.Pair ? pair.key instanceof resolveSeq.Scalar ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = resolveSeq.findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new resolveSeq.Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues()) + return super.toString(ctx, onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + }; + PlainValue._defineProperty(YAMLSet, "tag", "tag:yaml.org,2002:set"); + function parseSet(doc, cst) { + const map = resolveSeq.resolveMap(doc, cst); + if (!map.hasAllNullValues()) + throw new PlainValue.YAMLSemanticError(cst, "Set items must all have null values"); + return Object.assign(new YAMLSet(), map); + } + function createSet(schema, iterable, ctx) { + const set2 = new YAMLSet(); + for (const value of iterable) + set2.items.push(schema.createPair(value, null, ctx)); + return set2; + } + var set = { + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + resolve: parseSet, + createNode: createSet + }; + var parseSexagesimal = (sign, parts) => { + const n = parts.split(":").reduce((n2, p) => n2 * 60 + Number(p), 0); + return sign === "-" ? -n : n; + }; + var stringifySexagesimal = ({ + value + }) => { + if (isNaN(value) || !isFinite(value)) + return resolveSeq.stringifyNumber(value); + let sign = ""; + if (value < 0) { + sign = "-"; + value = Math.abs(value); + } + const parts = [value % 60]; + if (value < 60) { + parts.unshift(0); + } else { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value % 60); + if (value >= 60) { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value); + } + } + return sign + parts.map((n) => n < 10 ? "0" + String(n) : String(n)).join(":").replace(/000000\d*$/, ""); + }; + var intTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, "")), + stringify: stringifySexagesimal + }; + var floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, "")), + stringify: stringifySexagesimal + }; + var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + test: RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"), + resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { + if (millisec) + millisec = (millisec + "00").substr(1, 3); + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz[0], tz.slice(1)); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ + value + }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "") + }; + function shouldWarn(deprecation) { + const env = typeof process !== "undefined" && process.env || {}; + if (deprecation) { + if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== "undefined") + return !YAML_SILENCE_DEPRECATION_WARNINGS; + return !env.YAML_SILENCE_DEPRECATION_WARNINGS; + } + if (typeof YAML_SILENCE_WARNINGS !== "undefined") + return !YAML_SILENCE_WARNINGS; + return !env.YAML_SILENCE_WARNINGS; + } + function warn(warning, type) { + if (shouldWarn(false)) { + const emit = typeof process !== "undefined" && process.emitWarning; + if (emit) + emit(warning, type); + else { + console.warn(type ? `${type}: ${warning}` : warning); + } + } + } + function warnFileDeprecation(filename) { + if (shouldWarn(true)) { + const path = filename.replace(/.*yaml[/\\]/i, "").replace(/\.js$/, "").replace(/\\/g, "/"); + warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, "DeprecationWarning"); + } + } + var warned = {}; + function warnOptionDeprecation(name, alternative) { + if (!warned[name] && shouldWarn(true)) { + warned[name] = true; + let msg = `The option '${name}' will be removed in a future release`; + msg += alternative ? `, use '${alternative}' instead.` : "."; + warn(msg, "DeprecationWarning"); + } + } + exports.binary = binary; + exports.floatTime = floatTime; + exports.intTime = intTime; + exports.omap = omap; + exports.pairs = pairs; + exports.set = set; + exports.timestamp = timestamp; + exports.warn = warn; + exports.warnFileDeprecation = warnFileDeprecation; + exports.warnOptionDeprecation = warnOptionDeprecation; + } + }); + + // node_modules/yaml/dist/Schema-88e323a7.js + var require_Schema_88e323a7 = __commonJS({ + "node_modules/yaml/dist/Schema-88e323a7.js"(exports) { + "use strict"; + var PlainValue = require_PlainValue_ec8e588e(); + var resolveSeq = require_resolveSeq_d03cb037(); + var warnings = require_warnings_1000a372(); + function createMap(schema, obj, ctx) { + const map2 = new resolveSeq.YAMLMap(schema); + if (obj instanceof Map) { + for (const [key, value] of obj) + map2.items.push(schema.createPair(key, value, ctx)); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + map2.items.push(schema.createPair(key, obj[key], ctx)); + } + if (typeof schema.sortMapEntries === "function") { + map2.items.sort(schema.sortMapEntries); + } + return map2; + } + var map = { + createNode: createMap, + default: true, + nodeClass: resolveSeq.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve: resolveSeq.resolveMap + }; + function createSeq(schema, obj, ctx) { + const seq2 = new resolveSeq.YAMLSeq(schema); + if (obj && obj[Symbol.iterator]) { + for (const it of obj) { + const v = schema.createNode(it, ctx.wrapScalars, null, ctx); + seq2.items.push(v); + } + } + return seq2; + } + var seq = { + createNode: createSeq, + default: true, + nodeClass: resolveSeq.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve: resolveSeq.resolveSeq + }; + var string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: resolveSeq.resolveString, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ + actualString: true + }, ctx); + return resolveSeq.stringifyString(item, ctx, onComment, onChompKeep); + }, + options: resolveSeq.strOptions + }; + var failsafe = [map, seq, string]; + var intIdentify$2 = (value) => typeof value === "bigint" || Number.isInteger(value); + var intResolve$1 = (src, part, radix) => resolveSeq.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); + function intStringify$1(node, radix, prefix) { + const { + value + } = node; + if (intIdentify$2(value) && value >= 0) + return prefix + value.toString(radix); + return resolveSeq.stringifyNumber(node); + } + var nullObj = { + identify: (value) => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq.nullOptions, + stringify: () => resolveSeq.nullOptions.nullStr + }; + var boolObj = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => str[0] === "t" || str[0] === "T", + options: resolveSeq.boolOptions, + stringify: ({ + value + }) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr + }; + var octObj = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o([0-7]+)$/, + resolve: (str, oct) => intResolve$1(str, oct, 8), + options: resolveSeq.intOptions, + stringify: (node) => intStringify$1(node, 8, "0o") + }; + var intObj = { + identify: intIdentify$2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str) => intResolve$1(str, str, 10), + options: resolveSeq.intOptions, + stringify: resolveSeq.stringifyNumber + }; + var hexObj = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x([0-9a-fA-F]+)$/, + resolve: (str, hex) => intResolve$1(str, hex, 16), + options: resolveSeq.intOptions, + stringify: (node) => intStringify$1(node, 16, "0x") + }; + var nanObj = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq.stringifyNumber + }; + var expObj = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify: ({ + value + }) => Number(value).toExponential() + }; + var floatObj = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, + resolve(str, frac1, frac2) { + const frac = frac1 || frac2; + const node = new resolveSeq.Scalar(parseFloat(str)); + if (frac && frac[frac.length - 1] === "0") + node.minFractionDigits = frac.length; + return node; + }, + stringify: resolveSeq.stringifyNumber + }; + var core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); + var intIdentify$1 = (value) => typeof value === "bigint" || Number.isInteger(value); + var stringifyJSON = ({ + value + }) => JSON.stringify(value); + var json = [map, seq, { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: resolveSeq.resolveString, + stringify: stringifyJSON + }, { + identify: (value) => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true|false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, { + identify: intIdentify$1, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str) => resolveSeq.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ + value + }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) + }, { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + }]; + json.scalarFallback = (str) => { + throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); + }; + var boolStringify = ({ + value + }) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr; + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve(sign, src, radix) { + let str = src.replace(/_/g, ""); + if (resolveSeq.intOptions.asBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n2 = BigInt(str); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; + } + function intStringify(node, radix, prefix) { + const { + value + } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return resolveSeq.stringifyNumber(node); + } + var yaml11 = failsafe.concat([{ + identify: (value) => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq.nullOptions, + stringify: () => resolveSeq.nullOptions.nullStr + }, { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => true, + options: resolveSeq.boolOptions, + stringify: boolStringify + }, { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, + resolve: () => false, + options: resolveSeq.boolOptions, + stringify: boolStringify + }, { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^([-+]?)0b([0-1_]+)$/, + resolve: (str, sign, bin) => intResolve(sign, bin, 2), + stringify: (node) => intStringify(node, 2, "0b") + }, { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^([-+]?)0([0-7_]+)$/, + resolve: (str, sign, oct) => intResolve(sign, oct, 8), + stringify: (node) => intStringify(node, 8, "0") + }, { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^([-+]?)([0-9][0-9_]*)$/, + resolve: (str, sign, abs) => intResolve(sign, abs, 10), + stringify: resolveSeq.stringifyNumber + }, { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^([-+]?)0x([0-9a-fA-F_]+)$/, + resolve: (str, sign, hex) => intResolve(sign, hex, 16), + stringify: (node) => intStringify(node, 16, "0x") + }, { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq.stringifyNumber + }, { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify: ({ + value + }) => Number(value).toExponential() + }, { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, + resolve(str, frac) { + const node = new resolveSeq.Scalar(parseFloat(str.replace(/_/g, ""))); + if (frac) { + const f = frac.replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: resolveSeq.stringifyNumber + }], warnings.binary, warnings.omap, warnings.pairs, warnings.set, warnings.intTime, warnings.floatTime, warnings.timestamp); + var schemas = { + core, + failsafe, + json, + yaml11 + }; + var tags = { + binary: warnings.binary, + bool: boolObj, + float: floatObj, + floatExp: expObj, + floatNaN: nanObj, + floatTime: warnings.floatTime, + int: intObj, + intHex: hexObj, + intOct: octObj, + intTime: warnings.intTime, + map, + null: nullObj, + omap: warnings.omap, + pairs: warnings.pairs, + seq, + set: warnings.set, + timestamp: warnings.timestamp + }; + function findTagObject(value, tagName, tags2) { + if (tagName) { + const match = tags2.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) || match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags2.find((t) => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); + } + function createNode(value, tagName, ctx) { + if (value instanceof resolveSeq.Node) + return value; + const { + defaultPrefix, + onTagObj, + prevObjects, + schema, + wrapScalars + } = ctx; + if (tagName && tagName.startsWith("!!")) + tagName = defaultPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (typeof value.toJSON === "function") + value = value.toJSON(); + if (!value || typeof value !== "object") + return wrapScalars ? new resolveSeq.Scalar(value) : value; + tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const obj = { + value: void 0, + node: void 0 + }; + if (value && typeof value === "object" && prevObjects) { + const prev = prevObjects.get(value); + if (prev) { + const alias = new resolveSeq.Alias(prev); + ctx.aliasNodes.push(alias); + return alias; + } + obj.value = value; + prevObjects.set(value, obj); + } + obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq.Scalar(value) : value; + if (tagName && obj.node instanceof resolveSeq.Node) + obj.node.tag = tagName; + return obj.node; + } + function getSchemaTags(schemas2, knownTags, customTags, schemaId) { + let tags2 = schemas2[schemaId.replace(/\W/g, "")]; + if (!tags2) { + const keys = Object.keys(schemas2).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags2 = tags2.concat(tag); + } else if (typeof customTags === "function") { + tags2 = customTags(tags2.slice()); + } + for (let i = 0; i < tags2.length; ++i) { + const tag = tags2[i]; + if (typeof tag === "string") { + const tagObj = knownTags[tag]; + if (!tagObj) { + const keys = Object.keys(knownTags).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); + } + tags2[i] = tagObj; + } + } + return tags2; + } + var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + var Schema = class { + constructor({ + customTags, + merge, + schema, + sortMapEntries, + tags: deprecatedCustomTags + }) { + this.merge = !!merge; + this.name = schema; + this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; + if (!customTags && deprecatedCustomTags) + warnings.warnOptionDeprecation("tags", "customTags"); + this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); + } + createNode(value, wrapScalars, tagName, ctx) { + const baseCtx = { + defaultPrefix: Schema.defaultPrefix, + schema: this, + wrapScalars + }; + const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; + return createNode(value, tagName, createCtx); + } + createPair(key, value, ctx) { + if (!ctx) + ctx = { + wrapScalars: true + }; + const k = this.createNode(key, ctx.wrapScalars, null, ctx); + const v = this.createNode(value, ctx.wrapScalars, null, ctx); + return new resolveSeq.Pair(k, v); + } + }; + PlainValue._defineProperty(Schema, "defaultPrefix", PlainValue.defaultTagPrefix); + PlainValue._defineProperty(Schema, "defaultTags", PlainValue.defaultTags); + exports.Schema = Schema; + } + }); + + // node_modules/yaml/dist/types.js + var require_types3 = __commonJS({ + "node_modules/yaml/dist/types.js"(exports) { + "use strict"; + var resolveSeq = require_resolveSeq_d03cb037(); + var Schema = require_Schema_88e323a7(); + require_PlainValue_ec8e588e(); + require_warnings_1000a372(); + exports.Alias = resolveSeq.Alias; + exports.Collection = resolveSeq.Collection; + exports.Merge = resolveSeq.Merge; + exports.Node = resolveSeq.Node; + exports.Pair = resolveSeq.Pair; + exports.Scalar = resolveSeq.Scalar; + exports.YAMLMap = resolveSeq.YAMLMap; + exports.YAMLSeq = resolveSeq.YAMLSeq; + exports.binaryOptions = resolveSeq.binaryOptions; + exports.boolOptions = resolveSeq.boolOptions; + exports.intOptions = resolveSeq.intOptions; + exports.nullOptions = resolveSeq.nullOptions; + exports.strOptions = resolveSeq.strOptions; + exports.Schema = Schema.Schema; + } + }); + + // node_modules/yaml/types.js + var require_types4 = __commonJS({ + "node_modules/yaml/types.js"(exports) { + var types = require_types3(); + exports.binaryOptions = types.binaryOptions; + exports.boolOptions = types.boolOptions; + exports.intOptions = types.intOptions; + exports.nullOptions = types.nullOptions; + exports.strOptions = types.strOptions; + exports.Schema = types.Schema; + exports.Alias = types.Alias; + exports.Collection = types.Collection; + exports.Merge = types.Merge; + exports.Node = types.Node; + exports.Pair = types.Pair; + exports.Scalar = types.Scalar; + exports.YAMLMap = types.YAMLMap; + exports.YAMLSeq = types.YAMLSeq; + } + }); + + // src/lib/renderers/yaml.js + var require_yaml = __commonJS({ + "src/lib/renderers/yaml.js"(exports, module) { + var yaml = require_yaml(); + var { YAMLMap, YAMLSeq } = require_types4(); + var optionAPI = require_option(); + function getIn(obj, path) { + return path.reduce((v, k) => k in v ? v[k] : {}, obj); + } + function addComments(context, path, commentNode, iterNode = commentNode) { + const { title, description, comment } = getIn(context, path); + const lines = []; + if (optionAPI("renderTitle") && title) { + lines.push(` ${title}`, ""); + } + if (optionAPI("renderDescription") && description) { + lines.push(` ${description}`); + } + if (optionAPI("renderComment") && comment) { + lines.push(` ${comment}`); + } + commentNode.commentBefore = lines.join("\n"); + if (iterNode instanceof YAMLMap) { + iterNode.items.forEach((n) => { + addComments(context, [...path, "items", n.key.value], n.key, n.value); + }); + } else if (iterNode instanceof YAMLSeq) { + iterNode.items.forEach((n, i) => { + addComments(context, [...path, "items", i], n); + }); + } + } + function renderYAML({ value, context }) { + const nodes = yaml.createNode(value); + addComments(context, [], nodes); + const doc = new yaml.Document(); + doc.contents = nodes; + return doc.toString(); + } + var yaml_default = renderYAML; + module.exports = yaml_default; + } + }); + + // src/lib/renderers/index.js + var require_renderers = __commonJS({ + "src/lib/renderers/index.js"(exports, module) { + var renderJS = require_js(); + var renderYAML = require_yaml(); + Object.assign(module.exports, { renderJS, renderYAML }); + } + }); + + // src/lib/index.js + var require_lib3 = __commonJS({ + "src/lib/index.js"(exports, module) { + var { getDependencies } = require_vendor(); + var Container = require_Container(); + var format = require_format(); + var option = require_option(); + var env = require_constants(); + var random = require_random(); + var utils = require_utils(); + var run = require_run(); + var { renderJS, renderYAML } = require_renderers(); + var container = new Container(); + function setupKeywords() { + container.define("autoIncrement", function autoIncrement(value, schema) { + if (!this.offset) { + const min = schema.minimum || 1; + const max = min + env.MAX_NUMBER; + const offset = value.initialOffset || schema.initialOffset; + this.offset = offset || random.number(min, max); + } + if (value === true) { + return this.offset++; + } + return schema; + }); + container.define("sequentialDate", function sequentialDate(value, schema) { + if (!this.now) { + this.now = random.date(); + } + if (value) { + schema = this.now.toISOString(); + value = value === true ? "days" : value; + if (["seconds", "minutes", "hours", "days", "weeks", "months", "years"].indexOf(value) === -1) { + throw new Error(`Unsupported increment by ${utils.short(value)}`); + } + this.now.setTime(this.now.getTime() + random.date(value)); + } + return schema; + }); + } + function getRefs(refs, schema) { + let $refs = {}; + if (Array.isArray(refs)) { + refs.forEach((_schema) => { + $refs[_schema.$id || _schema.id] = _schema; + }); + } else { + $refs = refs || {}; + } + function walk(obj) { + if (!obj || typeof obj !== "object") + return; + if (Array.isArray(obj)) + return obj.forEach(walk); + const _id = obj.$id || obj.id; + if (typeof _id === "string" && !$refs[_id]) { + $refs[_id] = obj; + } + Object.keys(obj).forEach((key) => { + walk(obj[key]); + }); + } + walk(refs); + walk(schema); + return $refs; + } + var jsf = (schema, refs, cwd) => { + console.log("[json-schema-faker] calling JsonSchemaFaker() is deprecated, call either .generate() or .resolve()"); + if (cwd) { + console.log("[json-schema-faker] references are only supported by calling .resolve()"); + } + return jsf.generate(schema, refs); + }; + jsf.generateWithContext = (schema, refs, validateSchema) => { + const $refs = getRefs(refs, schema); + return run($refs, schema, container, true, validateSchema); + }; + jsf.generate = (schema, refs, validateSchema) => renderJS(jsf.generateWithContext(schema, refs, validateSchema)); + jsf.generateYAML = (schema, refs, validateSchema) => renderYAML(jsf.generateWithContext(schema, refs, validateSchema)); + jsf.resolveWithContext = (schema, refs, cwd) => { + if (typeof refs === "string") { + cwd = refs; + refs = {}; + } + cwd = cwd || (typeof process !== "undefined" ? process.cwd() : ""); + cwd = `${cwd.replace(/\/+$/, "")}/`; + const $refs = getRefs(refs, schema); + const fixedRefs = { + order: 1, + canRead(file) { + const key = file.url.replace("/:", ":"); + return $refs[key] || $refs[key.split("/").pop()]; + }, + read(file, callback) { + try { + callback(null, this.canRead(file)); + } catch (e) { + callback(e); + } + } + }; + const { $RefParser } = getDependencies(); + return $RefParser.bundle(cwd, schema, { + resolve: { + file: { order: 100 }, + http: { order: 200 }, + fixedRefs + }, + dereference: { + circular: "ignore" + } + }).then((sub) => run($refs, sub, container)).catch((e) => { + throw new Error(`Error while resolving schema (${e.message})`); + }); + }; + jsf.resolve = (schema, refs, cwd) => jsf.resolveWithContext(schema, refs, cwd).then(renderJS); + jsf.resolveYAML = (schema, refs, cwd) => jsf.resolveWithContext(schema, refs, cwd).then(renderYAML); + setupKeywords(); + jsf.format = format; + jsf.option = option; + jsf.random = random; + jsf.extend = (name, cb) => { + container.extend(name, cb); + return jsf; + }; + jsf.define = (name, cb) => { + container.define(name, cb); + return jsf; + }; + jsf.reset = (name) => { + container.reset(name); + setupKeywords(); + return jsf; + }; + jsf.locate = (name) => { + return container.get(name); + }; + if (typeof VERSION !== "undefined") { + jsf.VERSION = VERSION; + } + var json_schema_faker_default = jsf; + module.exports = json_schema_faker_default; + } + }); + + // main.iife.js + var require_main_iife = __commonJS({ + "main.iife.js"(exports, module) { + var { setDependencies } = require_vendor(); + var JSONSchemaFaker = require_lib3(); + if (typeof window !== "undefined") { + setDependencies(__spreadProps(__spreadValues({}, window.JSONPath), { + $RefParser: window.$RefParser + })); + window.JSONSchemaFaker = JSONSchemaFaker; + } + module.exports = JSONSchemaFaker; + } + }); + return require_main_iife(); +})(); +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define(factory); + } else if (typeof module === 'object' && module.exports) { + module.exports = factory(); + } else { + root.JSONSchemaFaker = factory(); + } +}(typeof self !== 'undefined' ? self : this, () => JSONSchemaFaker)); + diff --git a/assets/json-schema-faker.js b/assets/json-schema-faker.js deleted file mode 100644 index ac3755588..000000000 --- a/assets/json-schema-faker.js +++ /dev/null @@ -1,25050 +0,0 @@ -/* eslint-disable */ - -/*! - * json-schema-faker library v0.5.0-rc15 - * http://json-schema-faker.js.org - * - * Copyright (c) 2014-2018 Alvaro Cabrera & Tomasz Ducin - * Released under the MIT license - * - * Date: 2018-04-09 17:23:23.954Z - */ - -var _ = require('lodash'), - validateSchema = require('../lib/ajValidation/ajvValidation').validateSchema, - { - handleExclusiveMaximum, - handleExclusiveMinimum - } = require('./../lib/common/schemaUtilsCommon'); - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.JSONSchemaFaker = factory()); -}(this, (function () { 'use strict'; - - /*! ***************************************************************************** - 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 Reflect, Promise */ - - 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]; }; - - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = Object.assign || function __assign(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; - }; - - function __rest(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) - t[p[i]] = s[p[i]]; - return t; - } - - function __decorate(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; - } - - function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - } - - function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - } - - function __awaiter(thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - - function __generator(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 = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, 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 }; - } - } - - function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - - function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - } - - function __read(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; - } - - function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - } - - function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - } - - function __asyncGenerator(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]); } - } - - function __asyncDelegator(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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } - } - - function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator]; - return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); - } - - function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - } - - var tslib_es6 = /*#__PURE__*/Object.freeze({ - __extends: __extends, - __assign: __assign, - __rest: __rest, - __decorate: __decorate, - __param: __param, - __metadata: __metadata, - __awaiter: __awaiter, - __generator: __generator, - __exportStar: __exportStar, - __values: __values, - __read: __read, - __spread: __spread, - __await: __await, - __asyncGenerator: __asyncGenerator, - __asyncDelegator: __asyncDelegator, - __asyncValues: __asyncValues, - __makeTemplateObject: __makeTemplateObject - }); - - var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var types = { - ROOT : 0, - GROUP : 1, - POSITION : 2, - SET : 3, - RANGE : 4, - REPETITION : 5, - REFERENCE : 6, - CHAR : 7, - }; - - var INTS = function() { - return [{ type: types.RANGE , from: 48, to: 57 }]; - }; - - var WORDS = function() { - return [ - { type: types.CHAR, value: 95 }, - { type: types.RANGE, from: 97, to: 122 }, - { type: types.RANGE, from: 65, to: 90 } - ].concat(INTS()); - }; - - var WHITESPACE = function() { - return [ - { type: types.CHAR, value: 9 }, - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 11 }, - { type: types.CHAR, value: 12 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 32 }, - { type: types.CHAR, value: 160 }, - { type: types.CHAR, value: 5760 }, - { type: types.CHAR, value: 6158 }, - { type: types.CHAR, value: 8192 }, - { type: types.CHAR, value: 8193 }, - { type: types.CHAR, value: 8194 }, - { type: types.CHAR, value: 8195 }, - { type: types.CHAR, value: 8196 }, - { type: types.CHAR, value: 8197 }, - { type: types.CHAR, value: 8198 }, - { type: types.CHAR, value: 8199 }, - { type: types.CHAR, value: 8200 }, - { type: types.CHAR, value: 8201 }, - { type: types.CHAR, value: 8202 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - { type: types.CHAR, value: 8239 }, - { type: types.CHAR, value: 8287 }, - { type: types.CHAR, value: 12288 }, - { type: types.CHAR, value: 65279 } - ]; - }; - - var NOTANYCHAR = function() { - return [ - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - ]; - }; - - // Predefined class objects. - var words = function() { - return { type: types.SET, set: WORDS(), not: false }; - }; - - var notWords = function() { - return { type: types.SET, set: WORDS(), not: true }; - }; - - var ints = function() { - return { type: types.SET, set: INTS(), not: false }; - }; - - var notInts = function() { - return { type: types.SET, set: INTS(), not: true }; - }; - - var whitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: false }; - }; - - var notWhitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: true }; - }; - - var anyChar = function() { - return { type: types.SET, set: NOTANYCHAR(), not: true }; - }; - - var sets = { - words: words, - notWords: notWords, - ints: ints, - notInts: notInts, - whitespace: whitespace, - notWhitespace: notWhitespace, - anyChar: anyChar - }; - - var util = createCommonjsModule(function (module, exports) { - // All of these are private and only used by randexp. - // It's assumed that they will always be called with the correct input. - - var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; - var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; - - /** - * Finds character representations in str and convert all to - * their respective characters - * - * @param {String} str - * @return {String} - */ - exports.strToChars = function(str) { - /* jshint maxlen: false */ - var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; - str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { - if (lbs) { - return s; - } - - var code = b ? 8 : - a16 ? parseInt(a16, 16) : - b16 ? parseInt(b16, 16) : - c8 ? parseInt(c8, 8) : - dctrl ? CTRL.indexOf(dctrl) : - SLSH[eslsh]; - - var c = String.fromCharCode(code); - - // Escape special regex characters. - if (/[\[\]{}\^$.|?*+()]/.test(c)) { - c = '\\' + c; - } - - return c; - }); - - return str; - }; - - - /** - * turns class into tokens - * reads str until it encounters a ] not preceeded by a \ - * - * @param {String} str - * @param {String} regexpStr - * @return {Array., Number>} - */ - exports.tokenizeClass = function(str, regexpStr) { - /* jshint maxlen: false */ - var tokens = []; - var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; - var rs, c; - - - while ((rs = regexp.exec(str)) != null) { - if (rs[1]) { - tokens.push(sets.words()); - - } else if (rs[2]) { - tokens.push(sets.ints()); - - } else if (rs[3]) { - tokens.push(sets.whitespace()); - - } else if (rs[4]) { - tokens.push(sets.notWords()); - - } else if (rs[5]) { - tokens.push(sets.notInts()); - - } else if (rs[6]) { - tokens.push(sets.notWhitespace()); - - } else if (rs[7]) { - tokens.push({ - type: types.RANGE, - from: (rs[8] || rs[9]).charCodeAt(0), - to: rs[10].charCodeAt(0), - }); - - } else if (c = rs[12]) { - tokens.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); - - } else { - return [tokens, regexp.lastIndex]; - } - } - - exports.error(regexpStr, 'Unterminated character class'); - }; - - - /** - * Shortcut to throw errors. - * - * @param {String} regexp - * @param {String} msg - */ - exports.error = function(regexp, msg) { - throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); - }; - }); - var util_1 = util.strToChars; - var util_2 = util.tokenizeClass; - var util_3 = util.error; - - var wordBoundary = function() { - return { type: types.POSITION, value: 'b' }; - }; - - var nonWordBoundary = function() { - return { type: types.POSITION, value: 'B' }; - }; - - var begin = function() { - return { type: types.POSITION, value: '^' }; - }; - - var end = function() { - return { type: types.POSITION, value: '$' }; - }; - - var positions = { - wordBoundary: wordBoundary, - nonWordBoundary: nonWordBoundary, - begin: begin, - end: end - }; - - var lib = function(regexpStr) { - var i = 0, l, c, - start = { type: types.ROOT, stack: []}, - - // Keep track of last clause/group and stack. - lastGroup = start, - last = start.stack, - groupStack = []; - - - var repeatErr = function(i) { - util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); - }; - - // Decode a few escaped characters. - var str = util.strToChars(regexpStr); - l = str.length; - - // Iterate through each character in string. - while (i < l) { - c = str[i++]; - - switch (c) { - // Handle escaped characters, inclues a few sets. - case '\\': - c = str[i++]; - - switch (c) { - case 'b': - last.push(positions.wordBoundary()); - break; - - case 'B': - last.push(positions.nonWordBoundary()); - break; - - case 'w': - last.push(sets.words()); - break; - - case 'W': - last.push(sets.notWords()); - break; - - case 'd': - last.push(sets.ints()); - break; - - case 'D': - last.push(sets.notInts()); - break; - - case 's': - last.push(sets.whitespace()); - break; - - case 'S': - last.push(sets.notWhitespace()); - break; - - default: - // Check if c is integer. - // In which case it's a reference. - if (/\d/.test(c)) { - last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); - - // Escaped character. - } else { - last.push({ type: types.CHAR, value: c.charCodeAt(0) }); - } - } - - break; - - - // Positionals. - case '^': - last.push(positions.begin()); - break; - - case '$': - last.push(positions.end()); - break; - - - // Handle custom sets. - case '[': - // Check if this class is 'anti' i.e. [^abc]. - var not; - if (str[i] === '^') { - not = true; - i++; - } else { - not = false; - } - - // Get all the characters in class. - var classTokens = util.tokenizeClass(str.slice(i), regexpStr); - - // Increase index by length of class. - i += classTokens[1]; - last.push({ - type: types.SET, - set: classTokens[0], - not: not, - }); - - break; - - - // Class of any character except \n. - case '.': - last.push(sets.anyChar()); - break; - - - // Push group onto stack. - case '(': - // Create group. - var group = { - type: types.GROUP, - stack: [], - remember: true, - }; - - c = str[i]; - - // If if this is a special kind of group. - if (c === '?') { - c = str[i + 1]; - i += 2; - - // Match if followed by. - if (c === '=') { - group.followedBy = true; - - // Match if not followed by. - } else if (c === '!') { - group.notFollowedBy = true; - - } else if (c !== ':') { - util.error(regexpStr, - 'Invalid group, character \'' + c + - '\' after \'?\' at column ' + (i - 1)); - } - - group.remember = false; - } - - // Insert subgroup into current group stack. - last.push(group); - - // Remember the current group for when the group closes. - groupStack.push(lastGroup); - - // Make this new group the current group. - lastGroup = group; - last = group.stack; - break; - - - // Pop group out of stack. - case ')': - if (groupStack.length === 0) { - util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); - } - lastGroup = groupStack.pop(); - - // Check if this group has a PIPE. - // To get back the correct last stack. - last = lastGroup.options ? - lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; - break; - - - // Use pipe character to give more choices. - case '|': - // Create array where options are if this is the first PIPE - // in this clause. - if (!lastGroup.options) { - lastGroup.options = [lastGroup.stack]; - delete lastGroup.stack; - } - - // Create a new stack and add to options for rest of clause. - var stack = []; - lastGroup.options.push(stack); - last = stack; - break; - - - // Repetition. - // For every repetition, remove last element from last stack - // then insert back a RANGE object. - // This design is chosen because there could be more than - // one repetition symbols in a regex i.e. `a?+{2,3}`. - case '{': - var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; - if (rs !== null) { - if (last.length === 0) { - repeatErr(i); - } - min = parseInt(rs[1], 10); - max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; - i += rs[0].length; - - last.push({ - type: types.REPETITION, - min: min, - max: max, - value: last.pop(), - }); - } else { - last.push({ - type: types.CHAR, - value: 123, - }); - } - break; - - case '?': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 0, - max: 1, - value: last.pop(), - }); - break; - - case '+': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 1, - max: Infinity, - value: last.pop(), - }); - break; - - case '*': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 0, - max: Infinity, - value: last.pop(), - }); - break; - - - // Default is a character that is not `\[](){}?+*^$`. - default: - last.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); - } - - } - - // Check if any groups have not been closed. - if (groupStack.length !== 0) { - util.error(regexpStr, 'Unterminated group'); - } - - return start; - }; - - var types_1$1 = types; - lib.types = types_1$1; - - //protected helper class - function _SubRange(low, high) { - this.low = low; - this.high = high; - this.length = 1 + high - low; - } - - _SubRange.prototype.overlaps = function (range) { - return !(this.high < range.low || this.low > range.high); - }; - - _SubRange.prototype.touches = function (range) { - return !(this.high + 1 < range.low || this.low - 1 > range.high); - }; - - //returns inclusive combination of _SubRanges as a _SubRange - _SubRange.prototype.add = function (range) { - return this.touches(range) && new _SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high)); - }; - - //returns subtraction of _SubRanges as an array of _SubRanges (there's a case where subtraction divides it in 2) - _SubRange.prototype.subtract = function (range) { - if (!this.overlaps(range)) return false; - if (range.low <= this.low && range.high >= this.high) return []; - if (range.low > this.low && range.high < this.high) return [new _SubRange(this.low, range.low - 1), new _SubRange(range.high + 1, this.high)]; - if (range.low <= this.low) return [new _SubRange(range.high + 1, this.high)]; - return [new _SubRange(this.low, range.low - 1)]; - }; - - _SubRange.prototype.toString = function () { - if (this.low == this.high) return this.low.toString(); - return this.low + '-' + this.high; - }; - - _SubRange.prototype.clone = function () { - return new _SubRange(this.low, this.high); - }; - - - - - function DiscontinuousRange(a, b) { - if (this instanceof DiscontinuousRange) { - this.ranges = []; - this.length = 0; - if (a !== undefined) this.add(a, b); - } else { - return new DiscontinuousRange(a, b); - } - } - - function _update_length(self) { - self.length = self.ranges.reduce(function (previous, range) {return previous + range.length}, 0); - } - - DiscontinuousRange.prototype.add = function (a, b) { - var self = this; - function _add(subrange) { - var new_ranges = []; - var i = 0; - while (i < self.ranges.length && !subrange.touches(self.ranges[i])) { - new_ranges.push(self.ranges[i].clone()); - i++; - } - while (i < self.ranges.length && subrange.touches(self.ranges[i])) { - subrange = subrange.add(self.ranges[i]); - i++; - } - new_ranges.push(subrange); - while (i < self.ranges.length) { - new_ranges.push(self.ranges[i].clone()); - i++; - } - self.ranges = new_ranges; - _update_length(self); - } - - if (a instanceof DiscontinuousRange) { - a.ranges.forEach(_add); - } else { - if (a instanceof _SubRange) { - _add(a); - } else { - if (b === undefined) b = a; - _add(new _SubRange(a, b)); - } - } - return this; - }; - - DiscontinuousRange.prototype.subtract = function (a, b) { - var self = this; - function _subtract(subrange) { - var new_ranges = []; - var i = 0; - while (i < self.ranges.length && !subrange.overlaps(self.ranges[i])) { - new_ranges.push(self.ranges[i].clone()); - i++; - } - while (i < self.ranges.length && subrange.overlaps(self.ranges[i])) { - new_ranges = new_ranges.concat(self.ranges[i].subtract(subrange)); - i++; - } - while (i < self.ranges.length) { - new_ranges.push(self.ranges[i].clone()); - i++; - } - self.ranges = new_ranges; - _update_length(self); - } - if (a instanceof DiscontinuousRange) { - a.ranges.forEach(_subtract); - } else { - if (a instanceof _SubRange) { - _subtract(a); - } else { - if (b === undefined) b = a; - _subtract(new _SubRange(a, b)); - } - } - return this; - }; - - - DiscontinuousRange.prototype.index = function (index) { - var i = 0; - while (i < this.ranges.length && this.ranges[i].length <= index) { - index -= this.ranges[i].length; - i++; - } - if (i >= this.ranges.length) return null; - return this.ranges[i].low + index; - }; - - - DiscontinuousRange.prototype.toString = function () { - return '[ ' + this.ranges.join(', ') + ' ]' - }; - - DiscontinuousRange.prototype.clone = function () { - return new DiscontinuousRange(this); - }; - - var discontinuousRange = DiscontinuousRange; - - var randexp = createCommonjsModule(function (module) { - var types = lib.types; - - - /** - * If code is alphabetic, converts to other case. - * If not alphabetic, returns back code. - * - * @param {Number} code - * @return {Number} - */ - function toOtherCase(code) { - return code + (97 <= code && code <= 122 ? -32 : - 65 <= code && code <= 90 ? 32 : 0); - } - - - /** - * Randomly returns a true or false value. - * - * @return {Boolean} - */ - function randBool() { - return !this.randInt(0, 1); - } - - - /** - * Randomly selects and returns a value from the array. - * - * @param {Array.} arr - * @return {Object} - */ - function randSelect(arr) { - if (arr instanceof discontinuousRange) { - return arr.index(this.randInt(0, arr.length - 1)); - } - return arr[this.randInt(0, arr.length - 1)]; - } - - - /** - * expands a token to a DiscontinuousRange of characters which has a - * length and an index function (for random selecting) - * - * @param {Object} token - * @return {DiscontinuousRange} - */ - function expand(token) { - if (token.type === lib.types.CHAR) { - return new discontinuousRange(token.value); - } else if (token.type === lib.types.RANGE) { - return new discontinuousRange(token.from, token.to); - } else { - var drange = new discontinuousRange(); - for (var i = 0; i < token.set.length; i++) { - var subrange = expand.call(this, token.set[i]); - drange.add(subrange); - if (this.ignoreCase) { - for (var j = 0; j < subrange.length; j++) { - var code = subrange.index(j); - var otherCaseCode = toOtherCase(code); - if (code !== otherCaseCode) { - drange.add(otherCaseCode); - } - } - } - } - if (token.not) { - return this.defaultRange.clone().subtract(drange); - } else { - return drange; - } - } - } - - - /** - * Checks if some custom properties have been set for this regexp. - * - * @param {RandExp} randexp - * @param {RegExp} regexp - */ - function checkCustom(randexp, regexp) { - if (typeof regexp.max === 'number') { - randexp.max = regexp.max; - } - if (regexp.defaultRange instanceof discontinuousRange) { - randexp.defaultRange = regexp.defaultRange; - } - if (typeof regexp.randInt === 'function') { - randexp.randInt = regexp.randInt; - } - } - - - /** - * @constructor - * @param {RegExp|String} regexp - * @param {String} m - */ - var RandExp = module.exports = function(regexp, m) { - this.defaultRange = this.defaultRange.clone(); - if (regexp instanceof RegExp) { - this.ignoreCase = regexp.ignoreCase; - this.multiline = regexp.multiline; - checkCustom(this, regexp); - regexp = regexp.source; - - } else if (typeof regexp === 'string') { - this.ignoreCase = m && m.indexOf('i') !== -1; - this.multiline = m && m.indexOf('m') !== -1; - } else { - throw new Error('Expected a regexp or string'); - } - - this.tokens = lib(regexp); - }; - - - // When a repetitional token has its max set to Infinite, - // randexp won't actually generate a random amount between min and Infinite - // instead it will see Infinite as min + 100. - RandExp.prototype.max = 100; - - - // Generates the random string. - RandExp.prototype.gen = function() { - return gen.call(this, this.tokens, []); - }; - - - // Enables use of randexp with a shorter call. - RandExp.randexp = function(regexp, m) { - var randexp; - if (regexp._randexp === undefined) { - randexp = new RandExp(regexp, m); - regexp._randexp = randexp; - } else { - randexp = regexp._randexp; - } - checkCustom(randexp, regexp); - return randexp.gen(); - }; - - - // This enables sugary /regexp/.gen syntax. - RandExp.sugar = function() { - /* jshint freeze:false */ - RegExp.prototype.gen = function() { - return RandExp.randexp(this); - }; - }; - - // This allows expanding to include additional characters - // for instance: RandExp.defaultRange.add(0, 65535); - RandExp.prototype.defaultRange = new discontinuousRange(32, 126); - - - /** - * Randomly generates and returns a number between a and b (inclusive). - * - * @param {Number} a - * @param {Number} b - * @return {Number} - */ - RandExp.prototype.randInt = function(a, b) { - return a + Math.floor(Math.random() * (1 + b - a)); - }; - - - /** - * Generate random string modeled after given tokens. - * - * @param {Object} token - * @param {Array.} groups - * @return {String} - */ - function gen(token, groups) { - var stack, str, n, i, l; - - switch (token.type) { - - - case types.ROOT: - case types.GROUP: - // Ignore lookaheads for now. - if (token.followedBy || token.notFollowedBy) { return ''; } - - // Insert placeholder until group string is generated. - if (token.remember && token.groupNumber === undefined) { - token.groupNumber = groups.push(null) - 1; - } - - stack = token.options ? - randSelect.call(this, token.options) : token.stack; - - str = ''; - for (i = 0, l = stack.length; i < l; i++) { - str += gen.call(this, stack[i], groups); - } - - if (token.remember) { - groups[token.groupNumber] = str; - } - return str; - - - case types.POSITION: - // Do nothing for now. - return ''; - - - case types.SET: - var expandedSet = expand.call(this, token); - if (!expandedSet.length) { return ''; } - return String.fromCharCode(randSelect.call(this, expandedSet)); - - - case types.REPETITION: - // Randomly generate number between min and max. - n = this.randInt(token.min, - token.max === Infinity ? token.min + this.max : token.max); - - str = ''; - for (i = 0; i < n; i++) { - str += gen.call(this, token.value, groups); - } - - return str; - - - case types.REFERENCE: - return groups[token.value - 1] || ''; - - - case types.CHAR: - var code = this.ignoreCase && randBool.call(this) ? - toOtherCase(token.value) : token.value; - return String.fromCharCode(code); - } - } - }); - - // https://gist.github.com/pjt33/efb2f1134bab986113fd - - function URLUtils(url, baseURL) { - // remove leading ./ - url = url.replace(/^\.\//, ''); - - var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@]*)(?::([^:@]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); - if (!m) { - throw new RangeError(); - } - var href = m[0] || ''; - var protocol = m[1] || ''; - var username = m[2] || ''; - var password = m[3] || ''; - var host = m[4] || ''; - var hostname = m[5] || ''; - var port = m[6] || ''; - var pathname = m[7] || ''; - var search = m[8] || ''; - var hash = m[9] || ''; - if (baseURL !== undefined) { - var base = new URLUtils(baseURL); - var flag = protocol === '' && host === '' && username === ''; - if (flag && pathname === '' && search === '') { - search = base.search; - } - if (flag && pathname.charAt(0) !== '/') { - pathname = (pathname !== '' ? (base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + pathname) : base.pathname); - } - // dot segments removal - var output = []; - - pathname.replace(/\/?[^\/]+/g, function(p) { - if (p === '/..') { - output.pop(); - } else { - output.push(p); - } - }); - - pathname = output.join('') || '/'; - - if (flag) { - port = base.port; - hostname = base.hostname; - host = base.host; - password = base.password; - username = base.username; - } - if (protocol === '') { - protocol = base.protocol; - } - href = protocol + (host !== '' ? '//' : '') + (username !== '' ? username + (password !== '' ? ':' + password : '') + '@' : '') + host + pathname + search + hash; - } - this.href = href; - this.origin = protocol + (host !== '' ? '//' + host : ''); - this.protocol = protocol; - this.username = username; - this.password = password; - this.host = host; - this.hostname = hostname; - this.port = port; - this.pathname = pathname; - this.search = search; - this.hash = hash; - } - - function isURL(path) { - if (typeof path === 'string' && /^\w+:\/\//.test(path)) { - return true; - } - } - - function parseURI(href, base) { - return new URLUtils(href, base); - } - - function resolveURL(base, href) { - base = base || 'http://json-schema.org/schema#'; - - href = parseURI(href, base); - base = parseURI(base); - - if (base.hash && !href.hash) { - return href.href + base.hash; - } - - return href.href; - } - - function getDocumentURI(uri) { - return typeof uri === 'string' && uri.split('#')[0]; - } - - function isKeyword(prop) { - return prop === 'enum' || prop === 'default' || prop === 'required'; - } - - var helpers = { - isURL: isURL, - parseURI: parseURI, - isKeyword: isKeyword, - resolveURL: resolveURL, - getDocumentURI: getDocumentURI - }; - - var findReference = createCommonjsModule(function (module) { - - - - function get(obj, path) { - var hash = path.split('#')[1]; - - var parts = hash.split('/').slice(1); - - while (parts.length) { - var key = decodeURIComponent(parts.shift()).replace(/~1/g, '/').replace(/~0/g, '~'); - - if (typeof obj[key] === 'undefined') { - throw new Error('JSON pointer not found: ' + path); - } - - obj = obj[key]; - } - - return obj; - } - - var find = module.exports = function(id, refs, filter) { - var target = refs[id] || refs[id.split('#')[1]] || refs[helpers.getDocumentURI(id)]; - - try { - if (target) { - target = id.indexOf('#/') > -1 ? get(target, id) : target; - } else { - for (var key in refs) { - if (helpers.resolveURL(refs[key].id, id) === refs[key].id) { - target = refs[key]; - break; - } - } - } - } catch (e) { - if (typeof filter === 'function') { - target = filter(id, refs); - } else { - throw e; - } - } - - if (!target) { - throw new Error('Reference not found: ' + id); - } - - while (target.$ref) { - target = find(target.$ref, refs); - } - - return target; - }; - }); - - var deepExtend_1 = createCommonjsModule(function (module) { - - function isSpecificValue(val) { - return ( - val instanceof Buffer - || val instanceof Date - || val instanceof RegExp - ) ? true : false; - } - - function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error('Unexpected situation'); - } - } - - /** - * Recursive cloning array. - */ - function deepCloneArray(arr) { - var clone = []; - arr.forEach(function (item, index) { - if (typeof item === 'object' && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; - } - - /** - * Extening object that entered in first argument. - * - * Returns extended object or false if have no target object or incorrect type. - * - * If you wish to clone source object (without modify it), just use empty new - * object as first argument, like this: - * deepExtend({}, yourObj_1, [yourObj_N]); - */ - var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } - - if (arguments.length < 2) { - return arguments[0]; - } - - var target = arguments[0]; - - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - - var val, src; - - args.forEach(function (obj) { - // skip argument if isn't an object, is null, or is an array - if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { - return; - } - - Object.keys(obj).forEach(function (key) { - src = target[key]; // source value - val = obj[key]; // new value - - // recursion prevention - if (val === target) { - return; - - /** - * if new value isn't object then just overwrite by new value - * instead of extending. - */ - } else if (typeof val !== 'object' || val === null) { - target[key] = val; - return; - - // just clone arrays (and recursive clone objects inside) - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; - - // custom cloning and overwrite for specific objects - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; - - // overwrite by new value if source isn't object or array - } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; - - // source value and new value is objects both, extending... - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); - - return target; - }; - }); - - function copy(_, obj, refs, parent, resolve, callback) { - var target = Array.isArray(obj) ? [] : {}; - - if (typeof obj.$ref === 'string') { - var id = obj.$ref; - var base = helpers.getDocumentURI(id); - var local = id.indexOf('#/') > -1; - - if (local || (resolve && base !== parent)) { - var fixed = findReference(id, refs, callback); - - deepExtend_1(obj, fixed); - - delete obj.$ref; - delete obj.id; - } - - if (_[id]) { - return obj; - } - - _[id] = 1; - } - - for (var prop in obj) { - if (typeof obj[prop] === 'object' && obj[prop] !== null && !helpers.isKeyword(prop)) { - target[prop] = copy(_, obj[prop], refs, parent, resolve, callback); - } else { - target[prop] = obj[prop]; - } - } - - return target; - } - - var resolveSchema = function(obj, refs, resolve, callback) { - var fixedId = helpers.resolveURL(obj.$schema, obj.id), - parent = helpers.getDocumentURI(fixedId); - - return copy({}, obj, refs, parent, resolve, callback); - }; - - var cloneObj = createCommonjsModule(function (module) { - - var clone = module.exports = function(obj, seen) { - seen = seen || []; - - if (seen.indexOf(obj) > -1) { - throw new Error('unable dereference circular structures'); - } - - if (!obj || typeof obj !== 'object') { - return obj; - } - - seen = seen.concat([obj]); - - var target = Array.isArray(obj) ? [] : {}; - - function copy(key, value) { - target[key] = clone(value, seen); - } - - if (Array.isArray(target)) { - obj.forEach(function(value, key) { - copy(key, value); - }); - } else if (Object.prototype.toString.call(obj) === '[object Object]') { - Object.keys(obj).forEach(function(key) { - copy(key, obj[key]); - }); - } - - return target; - }; - }); - - var SCHEMA_URI = [ - 'http://json-schema.org/schema#', - 'http://json-schema.org/draft-04/schema#' - ]; - - function expand(obj, parent, callback) { - if (obj) { - var id = typeof obj.id === 'string' ? obj.id : '#'; - - if (!helpers.isURL(id)) { - id = helpers.resolveURL(parent === id ? null : parent, id); - } - - if (typeof obj.$ref === 'string' && !helpers.isURL(obj.$ref)) { - obj.$ref = helpers.resolveURL(id, obj.$ref); - } - - if (typeof obj.id === 'string') { - obj.id = parent = id; - } - } - - for (var key in obj) { - var value = obj[key]; - - if (typeof value === 'object' && value !== null && !helpers.isKeyword(key)) { - expand(value, parent, callback); - } - } - - if (typeof callback === 'function') { - callback(obj); - } - } - - var normalizeSchema = function(fakeroot, schema, push) { - if (typeof fakeroot === 'object') { - push = schema; - schema = fakeroot; - fakeroot = null; - } - - var base = fakeroot || '', - copy = cloneObj(schema); - - if (copy.$schema && SCHEMA_URI.indexOf(copy.$schema) === -1) { - throw new Error('Unsupported schema version (v4 only)'); - } - - base = helpers.resolveURL(copy.$schema || SCHEMA_URI[0], base); - - expand(copy, helpers.resolveURL(copy.id || '#', base), push); - - copy.id = copy.id || base; - - return copy; - }; - - var lib$1 = createCommonjsModule(function (module) { - - - - helpers.findByRef = findReference; - helpers.resolveSchema = resolveSchema; - helpers.normalizeSchema = normalizeSchema; - - var instance = module.exports = function(f) { - function $ref(fakeroot, schema, refs, ex) { - if (typeof fakeroot === 'object') { - ex = refs; - refs = schema; - schema = fakeroot; - fakeroot = undefined; - } - - if (typeof schema !== 'object') { - throw new Error('schema must be an object'); - } - - if (typeof refs === 'object' && refs !== null) { - var aux = refs; - - refs = []; - - for (var k in aux) { - aux[k].id = aux[k].id || k; - refs.push(aux[k]); - } - } - - if (typeof refs !== 'undefined' && !Array.isArray(refs)) { - ex = !!refs; - refs = []; - } - - function push(ref) { - if (typeof ref.id === 'string') { - var id = helpers.resolveURL(fakeroot, ref.id).replace(/\/#?$/, ''); - - if (id.indexOf('#') > -1) { - var parts = id.split('#'); - - if (parts[1].charAt() === '/') { - id = parts[0]; - } else { - id = parts[1] || parts[0]; - } - } - - if (!$ref.refs[id]) { - $ref.refs[id] = ref; - } - } - } - - (refs || []).concat([schema]).forEach(function(ref) { - schema = helpers.normalizeSchema(fakeroot, ref, push); - push(schema); - }); - - return helpers.resolveSchema(schema, $ref.refs, ex, f); - } - - $ref.refs = {}; - $ref.util = helpers; - - return $ref; - }; - - instance.util = helpers; - }); - - var jsonpath = createCommonjsModule(function (module, exports) { - /*! jsonpath 1.0.0 */ - - (function(f){{module.exports=f();}})(function(){var define;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND", f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o - Copyright (C) 2013 Thaddee Tyl - Copyright (C) 2013 Mathias Bynens - Copyright (C) 2012 Ariya Hidayat - Copyright (C) 2012 Mathias Bynens - Copyright (C) 2012 Joost-Wim Boekesteijn - Copyright (C) 2012 Kris Kowal - Copyright (C) 2012 Yusuke Suzuki - Copyright (C) 2012 Arpad Borsos - Copyright (C) 2011 Ariya Hidayat - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - /*jslint bitwise:true plusplus:true */ - /*global esprima:true, define:true, exports:true, window: true, - throwErrorTolerant: true, - throwError: true, generateStatement: true, peek: true, - parseAssignmentExpression: true, parseBlock: true, parseExpression: true, - parseFunctionDeclaration: true, parseFunctionExpression: true, - parseFunctionSourceElements: true, parseVariableIdentifier: true, - parseLeftHandSideExpression: true, - parseUnaryExpression: true, - parseStatement: true, parseSourceElement: true */ - - (function (root, factory) { - - // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, - // Rhino, and plain browser loading. - - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define(['exports'], factory); - } else if (typeof exports !== 'undefined') { - factory(exports); - } else { - factory((root.esprima = {})); - } - }(this, function (exports) { - - var Token, - TokenName, - FnExprTokens, - Syntax, - PropertyKind, - Messages, - Regex, - SyntaxTreeDelegate, - source, - strict, - index, - lineNumber, - lineStart, - length, - delegate, - lookahead, - state, - extra; - - Token = { - BooleanLiteral: 1, - EOF: 2, - Identifier: 3, - Keyword: 4, - NullLiteral: 5, - NumericLiteral: 6, - Punctuator: 7, - StringLiteral: 8, - RegularExpression: 9 - }; - - TokenName = {}; - TokenName[Token.BooleanLiteral] = 'Boolean'; - TokenName[Token.EOF] = ''; - TokenName[Token.Identifier] = 'Identifier'; - TokenName[Token.Keyword] = 'Keyword'; - TokenName[Token.NullLiteral] = 'Null'; - TokenName[Token.NumericLiteral] = 'Numeric'; - TokenName[Token.Punctuator] = 'Punctuator'; - TokenName[Token.StringLiteral] = 'String'; - TokenName[Token.RegularExpression] = 'RegularExpression'; - - // A function following one of those tokens is an expression. - FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', - 'return', 'case', 'delete', 'throw', 'void', - // assignment operators - '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', - '&=', '|=', '^=', ',', - // binary/unary operators - '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', - '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', - '<=', '<', '>', '!=', '!==']; - - Syntax = { - AssignmentExpression: 'AssignmentExpression', - ArrayExpression: 'ArrayExpression', - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DoWhileStatement: 'DoWhileStatement', - DebuggerStatement: 'DebuggerStatement', - EmptyStatement: 'EmptyStatement', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - Identifier: 'Identifier', - IfStatement: 'IfStatement', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - Program: 'Program', - Property: 'Property', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement' - }; - - PropertyKind = { - Data: 1, - Get: 2, - Set: 4 - }; - - // Error messages should be identical to V8. - Messages = { - UnexpectedToken: 'Unexpected token %0', - UnexpectedNumber: 'Unexpected number', - UnexpectedString: 'Unexpected string', - UnexpectedIdentifier: 'Unexpected identifier', - UnexpectedReserved: 'Unexpected reserved word', - UnexpectedEOS: 'Unexpected end of input', - NewlineAfterThrow: 'Illegal newline after throw', - InvalidRegExp: 'Invalid regular expression', - UnterminatedRegExp: 'Invalid regular expression: missing /', - InvalidLHSInAssignment: 'Invalid left-hand side in assignment', - InvalidLHSInForIn: 'Invalid left-hand side in for-in', - MultipleDefaultsInSwitch: 'More than one default clause in switch statement', - NoCatchOrFinally: 'Missing catch or finally after try', - UnknownLabel: 'Undefined label \'%0\'', - Redeclaration: '%0 \'%1\' has already been declared', - IllegalContinue: 'Illegal continue statement', - IllegalBreak: 'Illegal break statement', - IllegalReturn: 'Illegal return statement', - StrictModeWith: 'Strict mode code may not include a with statement', - StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', - StrictVarName: 'Variable name may not be eval or arguments in strict mode', - StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', - StrictParamDupe: 'Strict mode function may not have duplicate parameter names', - StrictFunctionName: 'Function name may not be eval or arguments in strict mode', - StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', - StrictDelete: 'Delete of an unqualified identifier in strict mode.', - StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', - AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', - AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', - StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', - StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', - StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', - StrictReservedWord: 'Use of future reserved word in strict mode' - }; - - // See also tools/generate-unicode-regex.py. - Regex = { - NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\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\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\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\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-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\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\u0D60\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\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\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\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]'), - NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\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\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\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\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\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\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\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\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-\u191C\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\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\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\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\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-\uFE26\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]') - }; - - // Ensure the condition is true, otherwise throw an error. - // This is only to have a better contract semantic, i.e. another safety net - // to catch a logic error. The condition shall be fulfilled in normal case. - // Do NOT use this to enforce a certain condition on any user input. - - function assert(condition, message) { - /* istanbul ignore if */ - if (!condition) { - throw new Error('ASSERT: ' + message); - } - } - - function isDecimalDigit(ch) { - return (ch >= 48 && ch <= 57); // 0..9 - } - - function isHexDigit(ch) { - return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; - } - - function isOctalDigit(ch) { - return '01234567'.indexOf(ch) >= 0; - } - - - // 7.2 White Space - - function isWhiteSpace(ch) { - return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || - (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); - } - - // 7.3 Line Terminators - - function isLineTerminator(ch) { - return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); - } - - // 7.6 Identifier Names and Identifiers - - function isIdentifierStart(ch) { - return (ch == 0x40) || (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) - (ch >= 0x41 && ch <= 0x5A) || // A..Z - (ch >= 0x61 && ch <= 0x7A) || // a..z - (ch === 0x5C) || // \ (backslash) - ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); - } - - function isIdentifierPart(ch) { - return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) - (ch >= 0x41 && ch <= 0x5A) || // A..Z - (ch >= 0x61 && ch <= 0x7A) || // a..z - (ch >= 0x30 && ch <= 0x39) || // 0..9 - (ch === 0x5C) || // \ (backslash) - ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); - } - - // 7.6.1.2 Future Reserved Words - - function isFutureReservedWord(id) { - switch (id) { - case 'class': - case 'enum': - case 'export': - case 'extends': - case 'import': - case 'super': - return true; - default: - return false; - } - } - - function isStrictModeReservedWord(id) { - switch (id) { - case 'implements': - case 'interface': - case 'package': - case 'private': - case 'protected': - case 'public': - case 'static': - case 'yield': - case 'let': - return true; - default: - return false; - } - } - - function isRestrictedWord(id) { - return id === 'eval' || id === 'arguments'; - } - - // 7.6.1.1 Keywords - - function isKeyword(id) { - if (strict && isStrictModeReservedWord(id)) { - return true; - } - - // 'const' is specialized as Keyword in V8. - // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. - // Some others are from future reserved words. - - switch (id.length) { - case 2: - return (id === 'if') || (id === 'in') || (id === 'do'); - case 3: - return (id === 'var') || (id === 'for') || (id === 'new') || - (id === 'try') || (id === 'let'); - case 4: - return (id === 'this') || (id === 'else') || (id === 'case') || - (id === 'void') || (id === 'with') || (id === 'enum'); - case 5: - return (id === 'while') || (id === 'break') || (id === 'catch') || - (id === 'throw') || (id === 'const') || (id === 'yield') || - (id === 'class') || (id === 'super'); - case 6: - return (id === 'return') || (id === 'typeof') || (id === 'delete') || - (id === 'switch') || (id === 'export') || (id === 'import'); - case 7: - return (id === 'default') || (id === 'finally') || (id === 'extends'); - case 8: - return (id === 'function') || (id === 'continue') || (id === 'debugger'); - case 10: - return (id === 'instanceof'); - default: - return false; - } - } - - // 7.4 Comments - - function addComment(type, value, start, end, loc) { - var comment; - - assert(typeof start === 'number', 'Comment must have valid position'); - - // Because the way the actual token is scanned, often the comments - // (if any) are skipped twice during the lexical analysis. - // Thus, we need to skip adding a comment if the comment array already - // handled it. - if (state.lastCommentStart >= start) { - return; - } - state.lastCommentStart = start; - - comment = { - type: type, - value: value - }; - if (extra.range) { - comment.range = [start, end]; - } - if (extra.loc) { - comment.loc = loc; - } - extra.comments.push(comment); - if (extra.attachComment) { - extra.leadingComments.push(comment); - extra.trailingComments.push(comment); - } - } - - function skipSingleLineComment(offset) { - var start, loc, ch, comment; - - start = index - offset; - loc = { - start: { - line: lineNumber, - column: index - lineStart - offset - } - }; - - while (index < length) { - ch = source.charCodeAt(index); - ++index; - if (isLineTerminator(ch)) { - if (extra.comments) { - comment = source.slice(start + offset, index - 1); - loc.end = { - line: lineNumber, - column: index - lineStart - 1 - }; - addComment('Line', comment, start, index - 1, loc); - } - if (ch === 13 && source.charCodeAt(index) === 10) { - ++index; - } - ++lineNumber; - lineStart = index; - return; - } - } - - if (extra.comments) { - comment = source.slice(start + offset, index); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - addComment('Line', comment, start, index, loc); - } - } - - function skipMultiLineComment() { - var start, loc, ch, comment; - - if (extra.comments) { - start = index - 2; - loc = { - start: { - line: lineNumber, - column: index - lineStart - 2 - } - }; - } - - while (index < length) { - ch = source.charCodeAt(index); - if (isLineTerminator(ch)) { - if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { - ++index; - } - ++lineNumber; - ++index; - lineStart = index; - if (index >= length) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - } else if (ch === 0x2A) { - // Block comment ends with '*/'. - if (source.charCodeAt(index + 1) === 0x2F) { - ++index; - ++index; - if (extra.comments) { - comment = source.slice(start + 2, index - 2); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - addComment('Block', comment, start, index, loc); - } - return; - } - ++index; - } else { - ++index; - } - } - - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - function skipComment() { - var ch, start; - - start = (index === 0); - while (index < length) { - ch = source.charCodeAt(index); - - if (isWhiteSpace(ch)) { - ++index; - } else if (isLineTerminator(ch)) { - ++index; - if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { - ++index; - } - ++lineNumber; - lineStart = index; - start = true; - } else if (ch === 0x2F) { // U+002F is '/' - ch = source.charCodeAt(index + 1); - if (ch === 0x2F) { - ++index; - ++index; - skipSingleLineComment(2); - start = true; - } else if (ch === 0x2A) { // U+002A is '*' - ++index; - ++index; - skipMultiLineComment(); - } else { - break; - } - } else if (start && ch === 0x2D) { // U+002D is '-' - // U+003E is '>' - if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { - // '-->' is a single-line comment - index += 3; - skipSingleLineComment(3); - } else { - break; - } - } else if (ch === 0x3C) { // U+003C is '<' - if (source.slice(index + 1, index + 4) === '!--') { - ++index; // `<` - ++index; // `!` - ++index; // `-` - ++index; // `-` - skipSingleLineComment(4); - } else { - break; - } - } else { - break; - } - } - } - - function scanHexEscape(prefix) { - var i, len, ch, code = 0; - - len = (prefix === 'u') ? 4 : 2; - for (i = 0; i < len; ++i) { - if (index < length && isHexDigit(source[index])) { - ch = source[index++]; - code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); - } else { - return ''; - } - } - return String.fromCharCode(code); - } - - function getEscapedIdentifier() { - var ch, id; - - ch = source.charCodeAt(index++); - id = String.fromCharCode(ch); - - // '\u' (U+005C, U+0075) denotes an escaped character. - if (ch === 0x5C) { - if (source.charCodeAt(index) !== 0x75) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - ++index; - ch = scanHexEscape('u'); - if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - id = ch; - } - - while (index < length) { - ch = source.charCodeAt(index); - if (!isIdentifierPart(ch)) { - break; - } - ++index; - id += String.fromCharCode(ch); - - // '\u' (U+005C, U+0075) denotes an escaped character. - if (ch === 0x5C) { - id = id.substr(0, id.length - 1); - if (source.charCodeAt(index) !== 0x75) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - ++index; - ch = scanHexEscape('u'); - if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - id += ch; - } - } - - return id; - } - - function getIdentifier() { - var start, ch; - - start = index++; - while (index < length) { - ch = source.charCodeAt(index); - if (ch === 0x5C) { - // Blackslash (U+005C) marks Unicode escape sequence. - index = start; - return getEscapedIdentifier(); - } - if (isIdentifierPart(ch)) { - ++index; - } else { - break; - } - } - - return source.slice(start, index); - } - - function scanIdentifier() { - var start, id, type; - - start = index; - - // Backslash (U+005C) starts an escaped character. - id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); - - // There is no keyword or literal with only one character. - // Thus, it must be an identifier. - if (id.length === 1) { - type = Token.Identifier; - } else if (isKeyword(id)) { - type = Token.Keyword; - } else if (id === 'null') { - type = Token.NullLiteral; - } else if (id === 'true' || id === 'false') { - type = Token.BooleanLiteral; - } else { - type = Token.Identifier; - } - - return { - type: type, - value: id, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - - // 7.7 Punctuators - - function scanPunctuator() { - var start = index, - code = source.charCodeAt(index), - code2, - ch1 = source[index], - ch2, - ch3, - ch4; - - switch (code) { - - // Check for most common single-character punctuators. - case 0x2E: // . dot - case 0x28: // ( open bracket - case 0x29: // ) close bracket - case 0x3B: // ; semicolon - case 0x2C: // , comma - case 0x7B: // { open curly brace - case 0x7D: // } close curly brace - case 0x5B: // [ - case 0x5D: // ] - case 0x3A: // : - case 0x3F: // ? - case 0x7E: // ~ - ++index; - if (extra.tokenize) { - if (code === 0x28) { - extra.openParenToken = extra.tokens.length; - } else if (code === 0x7B) { - extra.openCurlyToken = extra.tokens.length; - } - } - return { - type: Token.Punctuator, - value: String.fromCharCode(code), - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - - default: - code2 = source.charCodeAt(index + 1); - - // '=' (U+003D) marks an assignment or comparison operator. - if (code2 === 0x3D) { - switch (code) { - case 0x2B: // + - case 0x2D: // - - case 0x2F: // / - case 0x3C: // < - case 0x3E: // > - case 0x5E: // ^ - case 0x7C: // | - case 0x25: // % - case 0x26: // & - case 0x2A: // * - index += 2; - return { - type: Token.Punctuator, - value: String.fromCharCode(code) + String.fromCharCode(code2), - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - - case 0x21: // ! - case 0x3D: // = - index += 2; - - // !== and === - if (source.charCodeAt(index) === 0x3D) { - ++index; - } - return { - type: Token.Punctuator, - value: source.slice(start, index), - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - } - } - - // 4-character punctuator: >>>= - - ch4 = source.substr(index, 4); - - if (ch4 === '>>>=') { - index += 4; - return { - type: Token.Punctuator, - value: ch4, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - // 3-character punctuators: === !== >>> <<= >>= - - ch3 = ch4.substr(0, 3); - - if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { - index += 3; - return { - type: Token.Punctuator, - value: ch3, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - // Other 2-character punctuators: ++ -- << >> && || - ch2 = ch3.substr(0, 2); - - if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { - index += 2; - return { - type: Token.Punctuator, - value: ch2, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - // 1-character punctuators: < > = ! + - * % & | ^ / - if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { - ++index; - return { - type: Token.Punctuator, - value: ch1, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - // 7.8.3 Numeric Literals - - function scanHexLiteral(start) { - var number = ''; - - while (index < length) { - if (!isHexDigit(source[index])) { - break; - } - number += source[index++]; - } - - if (number.length === 0) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - if (isIdentifierStart(source.charCodeAt(index))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - return { - type: Token.NumericLiteral, - value: parseInt('0x' + number, 16), - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - function scanOctalLiteral(start) { - var number = '0' + source[index++]; - while (index < length) { - if (!isOctalDigit(source[index])) { - break; - } - number += source[index++]; - } - - if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - return { - type: Token.NumericLiteral, - value: parseInt(number, 8), - octal: true, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - function scanNumericLiteral() { - var number, start, ch; - - ch = source[index]; - assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), - 'Numeric literal must start with a decimal digit or a decimal point'); - - start = index; - number = ''; - if (ch !== '.') { - number = source[index++]; - ch = source[index]; - - // Hex number starts with '0x'. - // Octal number starts with '0'. - if (number === '0') { - if (ch === 'x' || ch === 'X') { - ++index; - return scanHexLiteral(start); - } - if (isOctalDigit(ch)) { - return scanOctalLiteral(start); - } - - // decimal number starts with '0' such as '09' is illegal. - if (ch && isDecimalDigit(ch.charCodeAt(0))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - } - - while (isDecimalDigit(source.charCodeAt(index))) { - number += source[index++]; - } - ch = source[index]; - } - - if (ch === '.') { - number += source[index++]; - while (isDecimalDigit(source.charCodeAt(index))) { - number += source[index++]; - } - ch = source[index]; - } - - if (ch === 'e' || ch === 'E') { - number += source[index++]; - - ch = source[index]; - if (ch === '+' || ch === '-') { - number += source[index++]; - } - if (isDecimalDigit(source.charCodeAt(index))) { - while (isDecimalDigit(source.charCodeAt(index))) { - number += source[index++]; - } - } else { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - } - - if (isIdentifierStart(source.charCodeAt(index))) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - return { - type: Token.NumericLiteral, - value: parseFloat(number), - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - // 7.8.4 String Literals - - function scanStringLiteral() { - var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart; - startLineNumber = lineNumber; - startLineStart = lineStart; - - quote = source[index]; - assert((quote === '\'' || quote === '"'), - 'String literal must starts with a quote'); - - start = index; - ++index; - - while (index < length) { - ch = source[index++]; - - if (ch === quote) { - quote = ''; - break; - } else if (ch === '\\') { - ch = source[index++]; - if (!ch || !isLineTerminator(ch.charCodeAt(0))) { - switch (ch) { - case 'u': - case 'x': - restore = index; - unescaped = scanHexEscape(ch); - if (unescaped) { - str += unescaped; - } else { - index = restore; - str += ch; - } - break; - case 'n': - str += '\n'; - break; - case 'r': - str += '\r'; - break; - case 't': - str += '\t'; - break; - case 'b': - str += '\b'; - break; - case 'f': - str += '\f'; - break; - case 'v': - str += '\x0B'; - break; - - default: - if (isOctalDigit(ch)) { - code = '01234567'.indexOf(ch); - - // \0 is not octal escape sequence - if (code !== 0) { - octal = true; - } - - if (index < length && isOctalDigit(source[index])) { - octal = true; - code = code * 8 + '01234567'.indexOf(source[index++]); - - // 3 digits are only allowed when string starts - // with 0, 1, 2, 3 - if ('0123'.indexOf(ch) >= 0 && - index < length && - isOctalDigit(source[index])) { - code = code * 8 + '01234567'.indexOf(source[index++]); - } - } - str += String.fromCharCode(code); - } else { - str += ch; - } - break; - } - } else { - ++lineNumber; - if (ch === '\r' && source[index] === '\n') { - ++index; - } - lineStart = index; - } - } else if (isLineTerminator(ch.charCodeAt(0))) { - break; - } else { - str += ch; - } - } - - if (quote !== '') { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - return { - type: Token.StringLiteral, - value: str, - octal: octal, - startLineNumber: startLineNumber, - startLineStart: startLineStart, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - function testRegExp(pattern, flags) { - var value; - try { - value = new RegExp(pattern, flags); - } catch (e) { - throwError({}, Messages.InvalidRegExp); - } - return value; - } - - function scanRegExpBody() { - var ch, str, classMarker, terminated, body; - - ch = source[index]; - assert(ch === '/', 'Regular expression literal must start with a slash'); - str = source[index++]; - - classMarker = false; - terminated = false; - while (index < length) { - ch = source[index++]; - str += ch; - if (ch === '\\') { - ch = source[index++]; - // ECMA-262 7.8.5 - if (isLineTerminator(ch.charCodeAt(0))) { - throwError({}, Messages.UnterminatedRegExp); - } - str += ch; - } else if (isLineTerminator(ch.charCodeAt(0))) { - throwError({}, Messages.UnterminatedRegExp); - } else if (classMarker) { - if (ch === ']') { - classMarker = false; - } - } else { - if (ch === '/') { - terminated = true; - break; - } else if (ch === '[') { - classMarker = true; - } - } - } - - if (!terminated) { - throwError({}, Messages.UnterminatedRegExp); - } - - // Exclude leading and trailing slash. - body = str.substr(1, str.length - 2); - return { - value: body, - literal: str - }; - } - - function scanRegExpFlags() { - var ch, str, flags, restore; - - str = ''; - flags = ''; - while (index < length) { - ch = source[index]; - if (!isIdentifierPart(ch.charCodeAt(0))) { - break; - } - - ++index; - if (ch === '\\' && index < length) { - ch = source[index]; - if (ch === 'u') { - ++index; - restore = index; - ch = scanHexEscape('u'); - if (ch) { - flags += ch; - for (str += '\\u'; restore < index; ++restore) { - str += source[restore]; - } - } else { - index = restore; - flags += 'u'; - str += '\\u'; - } - throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); - } else { - str += '\\'; - throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - } else { - flags += ch; - str += ch; - } - } - - return { - value: flags, - literal: str - }; - } - - function scanRegExp() { - var start, body, flags, value; - - lookahead = null; - skipComment(); - start = index; - - body = scanRegExpBody(); - flags = scanRegExpFlags(); - value = testRegExp(body.value, flags.value); - - if (extra.tokenize) { - return { - type: Token.RegularExpression, - value: value, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; - } - - return { - literal: body.literal + flags.literal, - value: value, - start: start, - end: index - }; - } - - function collectRegex() { - var pos, loc, regex, token; - - skipComment(); - - pos = index; - loc = { - start: { - line: lineNumber, - column: index - lineStart - } - }; - - regex = scanRegExp(); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - - /* istanbul ignore next */ - if (!extra.tokenize) { - // Pop the previous token, which is likely '/' or '/=' - if (extra.tokens.length > 0) { - token = extra.tokens[extra.tokens.length - 1]; - if (token.range[0] === pos && token.type === 'Punctuator') { - if (token.value === '/' || token.value === '/=') { - extra.tokens.pop(); - } - } - } - - extra.tokens.push({ - type: 'RegularExpression', - value: regex.literal, - range: [pos, index], - loc: loc - }); - } - - return regex; - } - - function isIdentifierName(token) { - return token.type === Token.Identifier || - token.type === Token.Keyword || - token.type === Token.BooleanLiteral || - token.type === Token.NullLiteral; - } - - function advanceSlash() { - var prevToken, - checkToken; - // Using the following algorithm: - // https://github.com/mozilla/sweet.js/wiki/design - prevToken = extra.tokens[extra.tokens.length - 1]; - if (!prevToken) { - // Nothing before that: it cannot be a division. - return collectRegex(); - } - if (prevToken.type === 'Punctuator') { - if (prevToken.value === ']') { - return scanPunctuator(); - } - if (prevToken.value === ')') { - checkToken = extra.tokens[extra.openParenToken - 1]; - if (checkToken && - checkToken.type === 'Keyword' && - (checkToken.value === 'if' || - checkToken.value === 'while' || - checkToken.value === 'for' || - checkToken.value === 'with')) { - return collectRegex(); - } - return scanPunctuator(); - } - if (prevToken.value === '}') { - // Dividing a function by anything makes little sense, - // but we have to check for that. - if (extra.tokens[extra.openCurlyToken - 3] && - extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { - // Anonymous function. - checkToken = extra.tokens[extra.openCurlyToken - 4]; - if (!checkToken) { - return scanPunctuator(); - } - } else if (extra.tokens[extra.openCurlyToken - 4] && - extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { - // Named function. - checkToken = extra.tokens[extra.openCurlyToken - 5]; - if (!checkToken) { - return collectRegex(); - } - } else { - return scanPunctuator(); - } - // checkToken determines whether the function is - // a declaration or an expression. - if (FnExprTokens.indexOf(checkToken.value) >= 0) { - // It is an expression. - return scanPunctuator(); - } - // It is a declaration. - return collectRegex(); - } - return collectRegex(); - } - if (prevToken.type === 'Keyword') { - return collectRegex(); - } - return scanPunctuator(); - } - - function advance() { - var ch; - - skipComment(); - - if (index >= length) { - return { - type: Token.EOF, - lineNumber: lineNumber, - lineStart: lineStart, - start: index, - end: index - }; - } - - ch = source.charCodeAt(index); - - if (isIdentifierStart(ch)) { - return scanIdentifier(); - } - - // Very common: ( and ) and ; - if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { - return scanPunctuator(); - } - - // String literal starts with single quote (U+0027) or double quote (U+0022). - if (ch === 0x27 || ch === 0x22) { - return scanStringLiteral(); - } - - - // Dot (.) U+002E can also start a floating-point number, hence the need - // to check the next character. - if (ch === 0x2E) { - if (isDecimalDigit(source.charCodeAt(index + 1))) { - return scanNumericLiteral(); - } - return scanPunctuator(); - } - - if (isDecimalDigit(ch)) { - return scanNumericLiteral(); - } - - // Slash (/) U+002F can also start a regex. - if (extra.tokenize && ch === 0x2F) { - return advanceSlash(); - } - - return scanPunctuator(); - } - - function collectToken() { - var loc, token, value; - - skipComment(); - loc = { - start: { - line: lineNumber, - column: index - lineStart - } - }; - - token = advance(); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - - if (token.type !== Token.EOF) { - value = source.slice(token.start, token.end); - extra.tokens.push({ - type: TokenName[token.type], - value: value, - range: [token.start, token.end], - loc: loc - }); - } - - return token; - } - - function lex() { - var token; - - token = lookahead; - index = token.end; - lineNumber = token.lineNumber; - lineStart = token.lineStart; - - lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); - - index = token.end; - lineNumber = token.lineNumber; - lineStart = token.lineStart; - - return token; - } - - function peek() { - var pos, line, start; - - pos = index; - line = lineNumber; - start = lineStart; - lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); - index = pos; - lineNumber = line; - lineStart = start; - } - - function Position(line, column) { - this.line = line; - this.column = column; - } - - function SourceLocation(startLine, startColumn, line, column) { - this.start = new Position(startLine, startColumn); - this.end = new Position(line, column); - } - - SyntaxTreeDelegate = { - - name: 'SyntaxTree', - - processComment: function (node) { - var lastChild, trailingComments; - - if (node.type === Syntax.Program) { - if (node.body.length > 0) { - return; - } - } - - if (extra.trailingComments.length > 0) { - if (extra.trailingComments[0].range[0] >= node.range[1]) { - trailingComments = extra.trailingComments; - extra.trailingComments = []; - } else { - extra.trailingComments.length = 0; - } - } else { - if (extra.bottomRightStack.length > 0 && - extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments && - extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) { - trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; - delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; - } - } - - // Eating the stack. - while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) { - lastChild = extra.bottomRightStack.pop(); - } - - if (lastChild) { - if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { - node.leadingComments = lastChild.leadingComments; - delete lastChild.leadingComments; - } - } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { - node.leadingComments = extra.leadingComments; - extra.leadingComments = []; - } - - - if (trailingComments) { - node.trailingComments = trailingComments; - } - - extra.bottomRightStack.push(node); - }, - - markEnd: function (node, startToken) { - if (extra.range) { - node.range = [startToken.start, index]; - } - if (extra.loc) { - node.loc = new SourceLocation( - startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber, - startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart), - lineNumber, - index - lineStart - ); - this.postProcess(node); - } - - if (extra.attachComment) { - this.processComment(node); - } - return node; - }, - - postProcess: function (node) { - if (extra.source) { - node.loc.source = extra.source; - } - return node; - }, - - createArrayExpression: function (elements) { - return { - type: Syntax.ArrayExpression, - elements: elements - }; - }, - - createAssignmentExpression: function (operator, left, right) { - return { - type: Syntax.AssignmentExpression, - operator: operator, - left: left, - right: right - }; - }, - - createBinaryExpression: function (operator, left, right) { - var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : - Syntax.BinaryExpression; - return { - type: type, - operator: operator, - left: left, - right: right - }; - }, - - createBlockStatement: function (body) { - return { - type: Syntax.BlockStatement, - body: body - }; - }, - - createBreakStatement: function (label) { - return { - type: Syntax.BreakStatement, - label: label - }; - }, - - createCallExpression: function (callee, args) { - return { - type: Syntax.CallExpression, - callee: callee, - 'arguments': args - }; - }, - - createCatchClause: function (param, body) { - return { - type: Syntax.CatchClause, - param: param, - body: body - }; - }, - - createConditionalExpression: function (test, consequent, alternate) { - return { - type: Syntax.ConditionalExpression, - test: test, - consequent: consequent, - alternate: alternate - }; - }, - - createContinueStatement: function (label) { - return { - type: Syntax.ContinueStatement, - label: label - }; - }, - - createDebuggerStatement: function () { - return { - type: Syntax.DebuggerStatement - }; - }, - - createDoWhileStatement: function (body, test) { - return { - type: Syntax.DoWhileStatement, - body: body, - test: test - }; - }, - - createEmptyStatement: function () { - return { - type: Syntax.EmptyStatement - }; - }, - - createExpressionStatement: function (expression) { - return { - type: Syntax.ExpressionStatement, - expression: expression - }; - }, - - createForStatement: function (init, test, update, body) { - return { - type: Syntax.ForStatement, - init: init, - test: test, - update: update, - body: body - }; - }, - - createForInStatement: function (left, right, body) { - return { - type: Syntax.ForInStatement, - left: left, - right: right, - body: body, - each: false - }; - }, - - createFunctionDeclaration: function (id, params, defaults, body) { - return { - type: Syntax.FunctionDeclaration, - id: id, - params: params, - defaults: defaults, - body: body, - rest: null, - generator: false, - expression: false - }; - }, - - createFunctionExpression: function (id, params, defaults, body) { - return { - type: Syntax.FunctionExpression, - id: id, - params: params, - defaults: defaults, - body: body, - rest: null, - generator: false, - expression: false - }; - }, - - createIdentifier: function (name) { - return { - type: Syntax.Identifier, - name: name - }; - }, - - createIfStatement: function (test, consequent, alternate) { - return { - type: Syntax.IfStatement, - test: test, - consequent: consequent, - alternate: alternate - }; - }, - - createLabeledStatement: function (label, body) { - return { - type: Syntax.LabeledStatement, - label: label, - body: body - }; - }, - - createLiteral: function (token) { - return { - type: Syntax.Literal, - value: token.value, - raw: source.slice(token.start, token.end) - }; - }, - - createMemberExpression: function (accessor, object, property) { - return { - type: Syntax.MemberExpression, - computed: accessor === '[', - object: object, - property: property - }; - }, - - createNewExpression: function (callee, args) { - return { - type: Syntax.NewExpression, - callee: callee, - 'arguments': args - }; - }, - - createObjectExpression: function (properties) { - return { - type: Syntax.ObjectExpression, - properties: properties - }; - }, - - createPostfixExpression: function (operator, argument) { - return { - type: Syntax.UpdateExpression, - operator: operator, - argument: argument, - prefix: false - }; - }, - - createProgram: function (body) { - return { - type: Syntax.Program, - body: body - }; - }, - - createProperty: function (kind, key, value) { - return { - type: Syntax.Property, - key: key, - value: value, - kind: kind - }; - }, - - createReturnStatement: function (argument) { - return { - type: Syntax.ReturnStatement, - argument: argument - }; - }, - - createSequenceExpression: function (expressions) { - return { - type: Syntax.SequenceExpression, - expressions: expressions - }; - }, - - createSwitchCase: function (test, consequent) { - return { - type: Syntax.SwitchCase, - test: test, - consequent: consequent - }; - }, - - createSwitchStatement: function (discriminant, cases) { - return { - type: Syntax.SwitchStatement, - discriminant: discriminant, - cases: cases - }; - }, - - createThisExpression: function () { - return { - type: Syntax.ThisExpression - }; - }, - - createThrowStatement: function (argument) { - return { - type: Syntax.ThrowStatement, - argument: argument - }; - }, - - createTryStatement: function (block, guardedHandlers, handlers, finalizer) { - return { - type: Syntax.TryStatement, - block: block, - guardedHandlers: guardedHandlers, - handlers: handlers, - finalizer: finalizer - }; - }, - - createUnaryExpression: function (operator, argument) { - if (operator === '++' || operator === '--') { - return { - type: Syntax.UpdateExpression, - operator: operator, - argument: argument, - prefix: true - }; - } - return { - type: Syntax.UnaryExpression, - operator: operator, - argument: argument, - prefix: true - }; - }, - - createVariableDeclaration: function (declarations, kind) { - return { - type: Syntax.VariableDeclaration, - declarations: declarations, - kind: kind - }; - }, - - createVariableDeclarator: function (id, init) { - return { - type: Syntax.VariableDeclarator, - id: id, - init: init - }; - }, - - createWhileStatement: function (test, body) { - return { - type: Syntax.WhileStatement, - test: test, - body: body - }; - }, - - createWithStatement: function (object, body) { - return { - type: Syntax.WithStatement, - object: object, - body: body - }; - } - }; - - // Return true if there is a line terminator before the next token. - - function peekLineTerminator() { - var pos, line, start, found; - - pos = index; - line = lineNumber; - start = lineStart; - skipComment(); - found = lineNumber !== line; - index = pos; - lineNumber = line; - lineStart = start; - - return found; - } - - // Throw an exception - - function throwError(token, messageFormat) { - var error, - args = Array.prototype.slice.call(arguments, 2), - msg = messageFormat.replace( - /%(\d)/g, - function (whole, index) { - assert(index < args.length, 'Message reference must be in range'); - return args[index]; - } - ); - - if (typeof token.lineNumber === 'number') { - error = new Error('Line ' + token.lineNumber + ': ' + msg); - error.index = token.start; - error.lineNumber = token.lineNumber; - error.column = token.start - lineStart + 1; - } else { - error = new Error('Line ' + lineNumber + ': ' + msg); - error.index = index; - error.lineNumber = lineNumber; - error.column = index - lineStart + 1; - } - - error.description = msg; - throw error; - } - - function throwErrorTolerant() { - try { - throwError.apply(null, arguments); - } catch (e) { - if (extra.errors) { - extra.errors.push(e); - } else { - throw e; - } - } - } - - - // Throw an exception because of the token. - - function throwUnexpected(token) { - if (token.type === Token.EOF) { - throwError(token, Messages.UnexpectedEOS); - } - - if (token.type === Token.NumericLiteral) { - throwError(token, Messages.UnexpectedNumber); - } - - if (token.type === Token.StringLiteral) { - throwError(token, Messages.UnexpectedString); - } - - if (token.type === Token.Identifier) { - throwError(token, Messages.UnexpectedIdentifier); - } - - if (token.type === Token.Keyword) { - if (isFutureReservedWord(token.value)) { - throwError(token, Messages.UnexpectedReserved); - } else if (strict && isStrictModeReservedWord(token.value)) { - throwErrorTolerant(token, Messages.StrictReservedWord); - return; - } - throwError(token, Messages.UnexpectedToken, token.value); - } - - // BooleanLiteral, NullLiteral, or Punctuator. - throwError(token, Messages.UnexpectedToken, token.value); - } - - // Expect the next token to match the specified punctuator. - // If not, an exception will be thrown. - - function expect(value) { - var token = lex(); - if (token.type !== Token.Punctuator || token.value !== value) { - throwUnexpected(token); - } - } - - // Expect the next token to match the specified keyword. - // If not, an exception will be thrown. - - function expectKeyword(keyword) { - var token = lex(); - if (token.type !== Token.Keyword || token.value !== keyword) { - throwUnexpected(token); - } - } - - // Return true if the next token matches the specified punctuator. - - function match(value) { - return lookahead.type === Token.Punctuator && lookahead.value === value; - } - - // Return true if the next token matches the specified keyword - - function matchKeyword(keyword) { - return lookahead.type === Token.Keyword && lookahead.value === keyword; - } - - // Return true if the next token is an assignment operator - - function matchAssign() { - var op; - - if (lookahead.type !== Token.Punctuator) { - return false; - } - op = lookahead.value; - return op === '=' || - op === '*=' || - op === '/=' || - op === '%=' || - op === '+=' || - op === '-=' || - op === '<<=' || - op === '>>=' || - op === '>>>=' || - op === '&=' || - op === '^=' || - op === '|='; - } - - function consumeSemicolon() { - var line; - - // Catch the very common case first: immediately a semicolon (U+003B). - if (source.charCodeAt(index) === 0x3B || match(';')) { - lex(); - return; - } - - line = lineNumber; - skipComment(); - if (lineNumber !== line) { - return; - } - - if (lookahead.type !== Token.EOF && !match('}')) { - throwUnexpected(lookahead); - } - } - - // Return true if provided expression is LeftHandSideExpression - - function isLeftHandSide(expr) { - return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; - } - - // 11.1.4 Array Initialiser - - function parseArrayInitialiser() { - var elements = [], startToken; - - startToken = lookahead; - expect('['); - - while (!match(']')) { - if (match(',')) { - lex(); - elements.push(null); - } else { - elements.push(parseAssignmentExpression()); - - if (!match(']')) { - expect(','); - } - } - } - - lex(); - - return delegate.markEnd(delegate.createArrayExpression(elements), startToken); - } - - // 11.1.5 Object Initialiser - - function parsePropertyFunction(param, first) { - var previousStrict, body, startToken; - - previousStrict = strict; - startToken = lookahead; - body = parseFunctionSourceElements(); - if (first && strict && isRestrictedWord(param[0].name)) { - throwErrorTolerant(first, Messages.StrictParamName); - } - strict = previousStrict; - return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken); - } - - function parseObjectPropertyKey() { - var token, startToken; - - startToken = lookahead; - token = lex(); - - // Note: This function is called only from parseObjectProperty(), where - // EOF and Punctuator tokens are already filtered out. - - if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { - if (strict && token.octal) { - throwErrorTolerant(token, Messages.StrictOctalLiteral); - } - return delegate.markEnd(delegate.createLiteral(token), startToken); - } - - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); - } - - function parseObjectProperty() { - var token, key, id, value, param, startToken; - - token = lookahead; - startToken = lookahead; - - if (token.type === Token.Identifier) { - - id = parseObjectPropertyKey(); - - // Property Assignment: Getter and Setter. - - if (token.value === 'get' && !match(':')) { - key = parseObjectPropertyKey(); - expect('('); - expect(')'); - value = parsePropertyFunction([]); - return delegate.markEnd(delegate.createProperty('get', key, value), startToken); - } - if (token.value === 'set' && !match(':')) { - key = parseObjectPropertyKey(); - expect('('); - token = lookahead; - if (token.type !== Token.Identifier) { - expect(')'); - throwErrorTolerant(token, Messages.UnexpectedToken, token.value); - value = parsePropertyFunction([]); - } else { - param = [ parseVariableIdentifier() ]; - expect(')'); - value = parsePropertyFunction(param, token); - } - return delegate.markEnd(delegate.createProperty('set', key, value), startToken); - } - expect(':'); - value = parseAssignmentExpression(); - return delegate.markEnd(delegate.createProperty('init', id, value), startToken); - } - if (token.type === Token.EOF || token.type === Token.Punctuator) { - throwUnexpected(token); - } else { - key = parseObjectPropertyKey(); - expect(':'); - value = parseAssignmentExpression(); - return delegate.markEnd(delegate.createProperty('init', key, value), startToken); - } - } - - function parseObjectInitialiser() { - var properties = [], property, name, key, kind, map = {}, toString = String, startToken; - - startToken = lookahead; - - expect('{'); - - while (!match('}')) { - property = parseObjectProperty(); - - if (property.key.type === Syntax.Identifier) { - name = property.key.name; - } else { - name = toString(property.key.value); - } - kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; - - key = '$' + name; - if (Object.prototype.hasOwnProperty.call(map, key)) { - if (map[key] === PropertyKind.Data) { - if (strict && kind === PropertyKind.Data) { - throwErrorTolerant({}, Messages.StrictDuplicateProperty); - } else if (kind !== PropertyKind.Data) { - throwErrorTolerant({}, Messages.AccessorDataProperty); - } - } else { - if (kind === PropertyKind.Data) { - throwErrorTolerant({}, Messages.AccessorDataProperty); - } else if (map[key] & kind) { - throwErrorTolerant({}, Messages.AccessorGetSet); - } - } - map[key] |= kind; - } else { - map[key] = kind; - } - - properties.push(property); - - if (!match('}')) { - expect(','); - } - } - - expect('}'); - - return delegate.markEnd(delegate.createObjectExpression(properties), startToken); - } - - // 11.1.6 The Grouping Operator - - function parseGroupExpression() { - var expr; - - expect('('); - - expr = parseExpression(); - - expect(')'); - - return expr; - } - - - // 11.1 Primary Expressions - - function parsePrimaryExpression() { - var type, token, expr, startToken; - - if (match('(')) { - return parseGroupExpression(); - } - - if (match('[')) { - return parseArrayInitialiser(); - } - - if (match('{')) { - return parseObjectInitialiser(); - } - - type = lookahead.type; - startToken = lookahead; - - if (type === Token.Identifier) { - expr = delegate.createIdentifier(lex().value); - } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { - if (strict && lookahead.octal) { - throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); - } - expr = delegate.createLiteral(lex()); - } else if (type === Token.Keyword) { - if (matchKeyword('function')) { - return parseFunctionExpression(); - } - if (matchKeyword('this')) { - lex(); - expr = delegate.createThisExpression(); - } else { - throwUnexpected(lex()); - } - } else if (type === Token.BooleanLiteral) { - token = lex(); - token.value = (token.value === 'true'); - expr = delegate.createLiteral(token); - } else if (type === Token.NullLiteral) { - token = lex(); - token.value = null; - expr = delegate.createLiteral(token); - } else if (match('/') || match('/=')) { - if (typeof extra.tokens !== 'undefined') { - expr = delegate.createLiteral(collectRegex()); - } else { - expr = delegate.createLiteral(scanRegExp()); - } - peek(); - } else { - throwUnexpected(lex()); - } - - return delegate.markEnd(expr, startToken); - } - - // 11.2 Left-Hand-Side Expressions - - function parseArguments() { - var args = []; - - expect('('); - - if (!match(')')) { - while (index < length) { - args.push(parseAssignmentExpression()); - if (match(')')) { - break; - } - expect(','); - } - } - - expect(')'); - - return args; - } - - function parseNonComputedProperty() { - var token, startToken; - - startToken = lookahead; - token = lex(); - - if (!isIdentifierName(token)) { - throwUnexpected(token); - } - - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); - } - - function parseNonComputedMember() { - expect('.'); - - return parseNonComputedProperty(); - } - - function parseComputedMember() { - var expr; - - expect('['); - - expr = parseExpression(); - - expect(']'); - - return expr; - } - - function parseNewExpression() { - var callee, args, startToken; - - startToken = lookahead; - expectKeyword('new'); - callee = parseLeftHandSideExpression(); - args = match('(') ? parseArguments() : []; - - return delegate.markEnd(delegate.createNewExpression(callee, args), startToken); - } - - function parseLeftHandSideExpressionAllowCall() { - var previousAllowIn, expr, args, property, startToken; - - startToken = lookahead; - - previousAllowIn = state.allowIn; - state.allowIn = true; - expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); - state.allowIn = previousAllowIn; - - for (;;) { - if (match('.')) { - property = parseNonComputedMember(); - expr = delegate.createMemberExpression('.', expr, property); - } else if (match('(')) { - args = parseArguments(); - expr = delegate.createCallExpression(expr, args); - } else if (match('[')) { - property = parseComputedMember(); - expr = delegate.createMemberExpression('[', expr, property); - } else { - break; - } - delegate.markEnd(expr, startToken); - } - - return expr; - } - - function parseLeftHandSideExpression() { - var previousAllowIn, expr, property, startToken; - - startToken = lookahead; - - previousAllowIn = state.allowIn; - expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); - state.allowIn = previousAllowIn; - - while (match('.') || match('[')) { - if (match('[')) { - property = parseComputedMember(); - expr = delegate.createMemberExpression('[', expr, property); - } else { - property = parseNonComputedMember(); - expr = delegate.createMemberExpression('.', expr, property); - } - delegate.markEnd(expr, startToken); - } - - return expr; - } - - // 11.3 Postfix Expressions - - function parsePostfixExpression() { - var expr, token, startToken = lookahead; - - expr = parseLeftHandSideExpressionAllowCall(); - - if (lookahead.type === Token.Punctuator) { - if ((match('++') || match('--')) && !peekLineTerminator()) { - // 11.3.1, 11.3.2 - if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { - throwErrorTolerant({}, Messages.StrictLHSPostfix); - } - - if (!isLeftHandSide(expr)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); - } - - token = lex(); - expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken); - } - } - - return expr; - } - - // 11.4 Unary Operators - - function parseUnaryExpression() { - var token, expr, startToken; - - if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { - expr = parsePostfixExpression(); - } else if (match('++') || match('--')) { - startToken = lookahead; - token = lex(); - expr = parseUnaryExpression(); - // 11.4.4, 11.4.5 - if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { - throwErrorTolerant({}, Messages.StrictLHSPrefix); - } - - if (!isLeftHandSide(expr)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); - } - - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); - } else if (match('+') || match('-') || match('~') || match('!')) { - startToken = lookahead; - token = lex(); - expr = parseUnaryExpression(); - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); - } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { - startToken = lookahead; - token = lex(); - expr = parseUnaryExpression(); - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); - if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { - throwErrorTolerant({}, Messages.StrictDelete); - } - } else { - expr = parsePostfixExpression(); - } - - return expr; - } - - function binaryPrecedence(token, allowIn) { - var prec = 0; - - if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { - return 0; - } - - switch (token.value) { - case '||': - prec = 1; - break; - - case '&&': - prec = 2; - break; - - case '|': - prec = 3; - break; - - case '^': - prec = 4; - break; - - case '&': - prec = 5; - break; - - case '==': - case '!=': - case '===': - case '!==': - prec = 6; - break; - - case '<': - case '>': - case '<=': - case '>=': - case 'instanceof': - prec = 7; - break; - - case 'in': - prec = allowIn ? 7 : 0; - break; - - case '<<': - case '>>': - case '>>>': - prec = 8; - break; - - case '+': - case '-': - prec = 9; - break; - - case '*': - case '/': - case '%': - prec = 11; - break; - - default: - break; - } - - return prec; - } - - // 11.5 Multiplicative Operators - // 11.6 Additive Operators - // 11.7 Bitwise Shift Operators - // 11.8 Relational Operators - // 11.9 Equality Operators - // 11.10 Binary Bitwise Operators - // 11.11 Binary Logical Operators - - function parseBinaryExpression() { - var marker, markers, expr, token, prec, stack, right, operator, left, i; - - marker = lookahead; - left = parseUnaryExpression(); - - token = lookahead; - prec = binaryPrecedence(token, state.allowIn); - if (prec === 0) { - return left; - } - token.prec = prec; - lex(); - - markers = [marker, lookahead]; - right = parseUnaryExpression(); - - stack = [left, token, right]; - - while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { - - // Reduce: make a binary expression from the three topmost entries. - while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { - right = stack.pop(); - operator = stack.pop().value; - left = stack.pop(); - expr = delegate.createBinaryExpression(operator, left, right); - markers.pop(); - marker = markers[markers.length - 1]; - delegate.markEnd(expr, marker); - stack.push(expr); - } - - // Shift. - token = lex(); - token.prec = prec; - stack.push(token); - markers.push(lookahead); - expr = parseUnaryExpression(); - stack.push(expr); - } - - // Final reduce to clean-up the stack. - i = stack.length - 1; - expr = stack[i]; - markers.pop(); - while (i > 1) { - expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); - i -= 2; - marker = markers.pop(); - delegate.markEnd(expr, marker); - } - - return expr; - } - - - // 11.12 Conditional Operator - - function parseConditionalExpression() { - var expr, previousAllowIn, consequent, alternate, startToken; - - startToken = lookahead; - - expr = parseBinaryExpression(); - - if (match('?')) { - lex(); - previousAllowIn = state.allowIn; - state.allowIn = true; - consequent = parseAssignmentExpression(); - state.allowIn = previousAllowIn; - expect(':'); - alternate = parseAssignmentExpression(); - - expr = delegate.createConditionalExpression(expr, consequent, alternate); - delegate.markEnd(expr, startToken); - } - - return expr; - } - - // 11.13 Assignment Operators - - function parseAssignmentExpression() { - var token, left, right, node, startToken; - - token = lookahead; - startToken = lookahead; - - node = left = parseConditionalExpression(); - - if (matchAssign()) { - // LeftHandSideExpression - if (!isLeftHandSide(left)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); - } - - // 11.13.1 - if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) { - throwErrorTolerant(token, Messages.StrictLHSAssignment); - } - - token = lex(); - right = parseAssignmentExpression(); - node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken); - } - - return node; - } - - // 11.14 Comma Operator - - function parseExpression() { - var expr, startToken = lookahead; - - expr = parseAssignmentExpression(); - - if (match(',')) { - expr = delegate.createSequenceExpression([ expr ]); - - while (index < length) { - if (!match(',')) { - break; - } - lex(); - expr.expressions.push(parseAssignmentExpression()); - } - - delegate.markEnd(expr, startToken); - } - - return expr; - } - - // 12.1 Block - - function parseStatementList() { - var list = [], - statement; - - while (index < length) { - if (match('}')) { - break; - } - statement = parseSourceElement(); - if (typeof statement === 'undefined') { - break; - } - list.push(statement); - } - - return list; - } - - function parseBlock() { - var block, startToken; - - startToken = lookahead; - expect('{'); - - block = parseStatementList(); - - expect('}'); - - return delegate.markEnd(delegate.createBlockStatement(block), startToken); - } - - // 12.2 Variable Statement - - function parseVariableIdentifier() { - var token, startToken; - - startToken = lookahead; - token = lex(); - - if (token.type !== Token.Identifier) { - throwUnexpected(token); - } - - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); - } - - function parseVariableDeclaration(kind) { - var init = null, id, startToken; - - startToken = lookahead; - id = parseVariableIdentifier(); - - // 12.2.1 - if (strict && isRestrictedWord(id.name)) { - throwErrorTolerant({}, Messages.StrictVarName); - } - - if (kind === 'const') { - expect('='); - init = parseAssignmentExpression(); - } else if (match('=')) { - lex(); - init = parseAssignmentExpression(); - } - - return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken); - } - - function parseVariableDeclarationList(kind) { - var list = []; - - do { - list.push(parseVariableDeclaration(kind)); - if (!match(',')) { - break; - } - lex(); - } while (index < length); - - return list; - } - - function parseVariableStatement() { - var declarations; - - expectKeyword('var'); - - declarations = parseVariableDeclarationList(); - - consumeSemicolon(); - - return delegate.createVariableDeclaration(declarations, 'var'); - } - - // kind may be `const` or `let` - // Both are experimental and not in the specification yet. - // see http://wiki.ecmascript.org/doku.php?id=harmony:const - // and http://wiki.ecmascript.org/doku.php?id=harmony:let - function parseConstLetDeclaration(kind) { - var declarations, startToken; - - startToken = lookahead; - - expectKeyword(kind); - - declarations = parseVariableDeclarationList(kind); - - consumeSemicolon(); - - return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken); - } - - // 12.3 Empty Statement - - function parseEmptyStatement() { - expect(';'); - return delegate.createEmptyStatement(); - } - - // 12.4 Expression Statement - - function parseExpressionStatement() { - var expr = parseExpression(); - consumeSemicolon(); - return delegate.createExpressionStatement(expr); - } - - // 12.5 If statement - - function parseIfStatement() { - var test, consequent, alternate; - - expectKeyword('if'); - - expect('('); - - test = parseExpression(); - - expect(')'); - - consequent = parseStatement(); - - if (matchKeyword('else')) { - lex(); - alternate = parseStatement(); - } else { - alternate = null; - } - - return delegate.createIfStatement(test, consequent, alternate); - } - - // 12.6 Iteration Statements - - function parseDoWhileStatement() { - var body, test, oldInIteration; - - expectKeyword('do'); - - oldInIteration = state.inIteration; - state.inIteration = true; - - body = parseStatement(); - - state.inIteration = oldInIteration; - - expectKeyword('while'); - - expect('('); - - test = parseExpression(); - - expect(')'); - - if (match(';')) { - lex(); - } - - return delegate.createDoWhileStatement(body, test); - } - - function parseWhileStatement() { - var test, body, oldInIteration; - - expectKeyword('while'); - - expect('('); - - test = parseExpression(); - - expect(')'); - - oldInIteration = state.inIteration; - state.inIteration = true; - - body = parseStatement(); - - state.inIteration = oldInIteration; - - return delegate.createWhileStatement(test, body); - } - - function parseForVariableDeclaration() { - var token, declarations, startToken; - - startToken = lookahead; - token = lex(); - declarations = parseVariableDeclarationList(); - - return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken); - } - - function parseForStatement() { - var init, test, update, left, right, body, oldInIteration; - - init = test = update = null; - - expectKeyword('for'); - - expect('('); - - if (match(';')) { - lex(); - } else { - if (matchKeyword('var') || matchKeyword('let')) { - state.allowIn = false; - init = parseForVariableDeclaration(); - state.allowIn = true; - - if (init.declarations.length === 1 && matchKeyword('in')) { - lex(); - left = init; - right = parseExpression(); - init = null; - } - } else { - state.allowIn = false; - init = parseExpression(); - state.allowIn = true; - - if (matchKeyword('in')) { - // LeftHandSideExpression - if (!isLeftHandSide(init)) { - throwErrorTolerant({}, Messages.InvalidLHSInForIn); - } - - lex(); - left = init; - right = parseExpression(); - init = null; - } - } - - if (typeof left === 'undefined') { - expect(';'); - } - } - - if (typeof left === 'undefined') { - - if (!match(';')) { - test = parseExpression(); - } - expect(';'); - - if (!match(')')) { - update = parseExpression(); - } - } - - expect(')'); - - oldInIteration = state.inIteration; - state.inIteration = true; - - body = parseStatement(); - - state.inIteration = oldInIteration; - - return (typeof left === 'undefined') ? - delegate.createForStatement(init, test, update, body) : - delegate.createForInStatement(left, right, body); - } - - // 12.7 The continue statement - - function parseContinueStatement() { - var label = null, key; - - expectKeyword('continue'); - - // Optimize the most common form: 'continue;'. - if (source.charCodeAt(index) === 0x3B) { - lex(); - - if (!state.inIteration) { - throwError({}, Messages.IllegalContinue); - } - - return delegate.createContinueStatement(null); - } - - if (peekLineTerminator()) { - if (!state.inIteration) { - throwError({}, Messages.IllegalContinue); - } - - return delegate.createContinueStatement(null); - } - - if (lookahead.type === Token.Identifier) { - label = parseVariableIdentifier(); - - key = '$' + label.name; - if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { - throwError({}, Messages.UnknownLabel, label.name); - } - } - - consumeSemicolon(); - - if (label === null && !state.inIteration) { - throwError({}, Messages.IllegalContinue); - } - - return delegate.createContinueStatement(label); - } - - // 12.8 The break statement - - function parseBreakStatement() { - var label = null, key; - - expectKeyword('break'); - - // Catch the very common case first: immediately a semicolon (U+003B). - if (source.charCodeAt(index) === 0x3B) { - lex(); - - if (!(state.inIteration || state.inSwitch)) { - throwError({}, Messages.IllegalBreak); - } - - return delegate.createBreakStatement(null); - } - - if (peekLineTerminator()) { - if (!(state.inIteration || state.inSwitch)) { - throwError({}, Messages.IllegalBreak); - } - - return delegate.createBreakStatement(null); - } - - if (lookahead.type === Token.Identifier) { - label = parseVariableIdentifier(); - - key = '$' + label.name; - if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { - throwError({}, Messages.UnknownLabel, label.name); - } - } - - consumeSemicolon(); - - if (label === null && !(state.inIteration || state.inSwitch)) { - throwError({}, Messages.IllegalBreak); - } - - return delegate.createBreakStatement(label); - } - - // 12.9 The return statement - - function parseReturnStatement() { - var argument = null; - - expectKeyword('return'); - - if (!state.inFunctionBody) { - throwErrorTolerant({}, Messages.IllegalReturn); - } - - // 'return' followed by a space and an identifier is very common. - if (source.charCodeAt(index) === 0x20) { - if (isIdentifierStart(source.charCodeAt(index + 1))) { - argument = parseExpression(); - consumeSemicolon(); - return delegate.createReturnStatement(argument); - } - } - - if (peekLineTerminator()) { - return delegate.createReturnStatement(null); - } - - if (!match(';')) { - if (!match('}') && lookahead.type !== Token.EOF) { - argument = parseExpression(); - } - } - - consumeSemicolon(); - - return delegate.createReturnStatement(argument); - } - - // 12.10 The with statement - - function parseWithStatement() { - var object, body; - - if (strict) { - // TODO(ikarienator): Should we update the test cases instead? - skipComment(); - throwErrorTolerant({}, Messages.StrictModeWith); - } - - expectKeyword('with'); - - expect('('); - - object = parseExpression(); - - expect(')'); - - body = parseStatement(); - - return delegate.createWithStatement(object, body); - } - - // 12.10 The swith statement - - function parseSwitchCase() { - var test, consequent = [], statement, startToken; - - startToken = lookahead; - if (matchKeyword('default')) { - lex(); - test = null; - } else { - expectKeyword('case'); - test = parseExpression(); - } - expect(':'); - - while (index < length) { - if (match('}') || matchKeyword('default') || matchKeyword('case')) { - break; - } - statement = parseStatement(); - consequent.push(statement); - } - - return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken); - } - - function parseSwitchStatement() { - var discriminant, cases, clause, oldInSwitch, defaultFound; - - expectKeyword('switch'); - - expect('('); - - discriminant = parseExpression(); - - expect(')'); - - expect('{'); - - cases = []; - - if (match('}')) { - lex(); - return delegate.createSwitchStatement(discriminant, cases); - } - - oldInSwitch = state.inSwitch; - state.inSwitch = true; - defaultFound = false; - - while (index < length) { - if (match('}')) { - break; - } - clause = parseSwitchCase(); - if (clause.test === null) { - if (defaultFound) { - throwError({}, Messages.MultipleDefaultsInSwitch); - } - defaultFound = true; - } - cases.push(clause); - } - - state.inSwitch = oldInSwitch; - - expect('}'); - - return delegate.createSwitchStatement(discriminant, cases); - } - - // 12.13 The throw statement - - function parseThrowStatement() { - var argument; - - expectKeyword('throw'); - - if (peekLineTerminator()) { - throwError({}, Messages.NewlineAfterThrow); - } - - argument = parseExpression(); - - consumeSemicolon(); - - return delegate.createThrowStatement(argument); - } - - // 12.14 The try statement - - function parseCatchClause() { - var param, body, startToken; - - startToken = lookahead; - expectKeyword('catch'); - - expect('('); - if (match(')')) { - throwUnexpected(lookahead); - } - - param = parseVariableIdentifier(); - // 12.14.1 - if (strict && isRestrictedWord(param.name)) { - throwErrorTolerant({}, Messages.StrictCatchVariable); - } - - expect(')'); - body = parseBlock(); - return delegate.markEnd(delegate.createCatchClause(param, body), startToken); - } - - function parseTryStatement() { - var block, handlers = [], finalizer = null; - - expectKeyword('try'); - - block = parseBlock(); - - if (matchKeyword('catch')) { - handlers.push(parseCatchClause()); - } - - if (matchKeyword('finally')) { - lex(); - finalizer = parseBlock(); - } - - if (handlers.length === 0 && !finalizer) { - throwError({}, Messages.NoCatchOrFinally); - } - - return delegate.createTryStatement(block, [], handlers, finalizer); - } - - // 12.15 The debugger statement - - function parseDebuggerStatement() { - expectKeyword('debugger'); - - consumeSemicolon(); - - return delegate.createDebuggerStatement(); - } - - // 12 Statements - - function parseStatement() { - var type = lookahead.type, - expr, - labeledBody, - key, - startToken; - - if (type === Token.EOF) { - throwUnexpected(lookahead); - } - - if (type === Token.Punctuator && lookahead.value === '{') { - return parseBlock(); - } - - startToken = lookahead; - - if (type === Token.Punctuator) { - switch (lookahead.value) { - case ';': - return delegate.markEnd(parseEmptyStatement(), startToken); - case '(': - return delegate.markEnd(parseExpressionStatement(), startToken); - default: - break; - } - } - - if (type === Token.Keyword) { - switch (lookahead.value) { - case 'break': - return delegate.markEnd(parseBreakStatement(), startToken); - case 'continue': - return delegate.markEnd(parseContinueStatement(), startToken); - case 'debugger': - return delegate.markEnd(parseDebuggerStatement(), startToken); - case 'do': - return delegate.markEnd(parseDoWhileStatement(), startToken); - case 'for': - return delegate.markEnd(parseForStatement(), startToken); - case 'function': - return delegate.markEnd(parseFunctionDeclaration(), startToken); - case 'if': - return delegate.markEnd(parseIfStatement(), startToken); - case 'return': - return delegate.markEnd(parseReturnStatement(), startToken); - case 'switch': - return delegate.markEnd(parseSwitchStatement(), startToken); - case 'throw': - return delegate.markEnd(parseThrowStatement(), startToken); - case 'try': - return delegate.markEnd(parseTryStatement(), startToken); - case 'var': - return delegate.markEnd(parseVariableStatement(), startToken); - case 'while': - return delegate.markEnd(parseWhileStatement(), startToken); - case 'with': - return delegate.markEnd(parseWithStatement(), startToken); - default: - break; - } - } - - expr = parseExpression(); - - // 12.12 Labelled Statements - if ((expr.type === Syntax.Identifier) && match(':')) { - lex(); - - key = '$' + expr.name; - if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { - throwError({}, Messages.Redeclaration, 'Label', expr.name); - } - - state.labelSet[key] = true; - labeledBody = parseStatement(); - delete state.labelSet[key]; - return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken); - } - - consumeSemicolon(); - - return delegate.markEnd(delegate.createExpressionStatement(expr), startToken); - } - - // 13 Function Definition - - function parseFunctionSourceElements() { - var sourceElement, sourceElements = [], token, directive, firstRestricted, - oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken; - - startToken = lookahead; - expect('{'); - - while (index < length) { - if (lookahead.type !== Token.StringLiteral) { - break; - } - token = lookahead; - - sourceElement = parseSourceElement(); - sourceElements.push(sourceElement); - if (sourceElement.expression.type !== Syntax.Literal) { - // this is not directive - break; - } - directive = source.slice(token.start + 1, token.end - 1); - if (directive === 'use strict') { - strict = true; - if (firstRestricted) { - throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); - } - } else { - if (!firstRestricted && token.octal) { - firstRestricted = token; - } - } - } - - oldLabelSet = state.labelSet; - oldInIteration = state.inIteration; - oldInSwitch = state.inSwitch; - oldInFunctionBody = state.inFunctionBody; - - state.labelSet = {}; - state.inIteration = false; - state.inSwitch = false; - state.inFunctionBody = true; - - while (index < length) { - if (match('}')) { - break; - } - sourceElement = parseSourceElement(); - if (typeof sourceElement === 'undefined') { - break; - } - sourceElements.push(sourceElement); - } - - expect('}'); - - state.labelSet = oldLabelSet; - state.inIteration = oldInIteration; - state.inSwitch = oldInSwitch; - state.inFunctionBody = oldInFunctionBody; - - return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken); - } - - function parseParams(firstRestricted) { - var param, params = [], token, stricted, paramSet, key, message; - expect('('); - - if (!match(')')) { - paramSet = {}; - while (index < length) { - token = lookahead; - param = parseVariableIdentifier(); - key = '$' + token.value; - if (strict) { - if (isRestrictedWord(token.value)) { - stricted = token; - message = Messages.StrictParamName; - } - if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - stricted = token; - message = Messages.StrictParamDupe; - } - } else if (!firstRestricted) { - if (isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictParamName; - } else if (isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; - } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - firstRestricted = token; - message = Messages.StrictParamDupe; - } - } - params.push(param); - paramSet[key] = true; - if (match(')')) { - break; - } - expect(','); - } - } - - expect(')'); - - return { - params: params, - stricted: stricted, - firstRestricted: firstRestricted, - message: message - }; - } - - function parseFunctionDeclaration() { - var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken; - - startToken = lookahead; - - expectKeyword('function'); - token = lookahead; - id = parseVariableIdentifier(); - if (strict) { - if (isRestrictedWord(token.value)) { - throwErrorTolerant(token, Messages.StrictFunctionName); - } - } else { - if (isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictFunctionName; - } else if (isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; - } - } - - tmp = parseParams(firstRestricted); - params = tmp.params; - stricted = tmp.stricted; - firstRestricted = tmp.firstRestricted; - if (tmp.message) { - message = tmp.message; - } - - previousStrict = strict; - body = parseFunctionSourceElements(); - if (strict && firstRestricted) { - throwError(firstRestricted, message); - } - if (strict && stricted) { - throwErrorTolerant(stricted, message); - } - strict = previousStrict; - - return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken); - } - - function parseFunctionExpression() { - var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken; - - startToken = lookahead; - expectKeyword('function'); - - if (!match('(')) { - token = lookahead; - id = parseVariableIdentifier(); - if (strict) { - if (isRestrictedWord(token.value)) { - throwErrorTolerant(token, Messages.StrictFunctionName); - } - } else { - if (isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictFunctionName; - } else if (isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; - } - } - } - - tmp = parseParams(firstRestricted); - params = tmp.params; - stricted = tmp.stricted; - firstRestricted = tmp.firstRestricted; - if (tmp.message) { - message = tmp.message; - } - - previousStrict = strict; - body = parseFunctionSourceElements(); - if (strict && firstRestricted) { - throwError(firstRestricted, message); - } - if (strict && stricted) { - throwErrorTolerant(stricted, message); - } - strict = previousStrict; - - return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken); - } - - // 14 Program - - function parseSourceElement() { - if (lookahead.type === Token.Keyword) { - switch (lookahead.value) { - case 'const': - case 'let': - return parseConstLetDeclaration(lookahead.value); - case 'function': - return parseFunctionDeclaration(); - default: - return parseStatement(); - } - } - - if (lookahead.type !== Token.EOF) { - return parseStatement(); - } - } - - function parseSourceElements() { - var sourceElement, sourceElements = [], token, directive, firstRestricted; - - while (index < length) { - token = lookahead; - if (token.type !== Token.StringLiteral) { - break; - } - - sourceElement = parseSourceElement(); - sourceElements.push(sourceElement); - if (sourceElement.expression.type !== Syntax.Literal) { - // this is not directive - break; - } - directive = source.slice(token.start + 1, token.end - 1); - if (directive === 'use strict') { - strict = true; - if (firstRestricted) { - throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); - } - } else { - if (!firstRestricted && token.octal) { - firstRestricted = token; - } - } - } - - while (index < length) { - sourceElement = parseSourceElement(); - /* istanbul ignore if */ - if (typeof sourceElement === 'undefined') { - break; - } - sourceElements.push(sourceElement); - } - return sourceElements; - } - - function parseProgram() { - var body, startToken; - - skipComment(); - peek(); - startToken = lookahead; - strict = false; - - body = parseSourceElements(); - return delegate.markEnd(delegate.createProgram(body), startToken); - } - - function filterTokenLocation() { - var i, entry, token, tokens = []; - - for (i = 0; i < extra.tokens.length; ++i) { - entry = extra.tokens[i]; - token = { - type: entry.type, - value: entry.value - }; - if (extra.range) { - token.range = entry.range; - } - if (extra.loc) { - token.loc = entry.loc; - } - tokens.push(token); - } - - extra.tokens = tokens; - } - - function tokenize(code, options) { - var toString, - token, - tokens; - - toString = String; - if (typeof code !== 'string' && !(code instanceof String)) { - code = toString(code); - } - - delegate = SyntaxTreeDelegate; - source = code; - index = 0; - lineNumber = (source.length > 0) ? 1 : 0; - lineStart = 0; - length = source.length; - lookahead = null; - state = { - allowIn: true, - labelSet: {}, - inFunctionBody: false, - inIteration: false, - inSwitch: false, - lastCommentStart: -1 - }; - - extra = {}; - - // Options matching. - options = options || {}; - - // Of course we collect tokens here. - options.tokens = true; - extra.tokens = []; - extra.tokenize = true; - // The following two fields are necessary to compute the Regex tokens. - extra.openParenToken = -1; - extra.openCurlyToken = -1; - - extra.range = (typeof options.range === 'boolean') && options.range; - extra.loc = (typeof options.loc === 'boolean') && options.loc; - - if (typeof options.comment === 'boolean' && options.comment) { - extra.comments = []; - } - if (typeof options.tolerant === 'boolean' && options.tolerant) { - extra.errors = []; - } - - try { - peek(); - if (lookahead.type === Token.EOF) { - return extra.tokens; - } - - token = lex(); - while (lookahead.type !== Token.EOF) { - try { - token = lex(); - } catch (lexError) { - token = lookahead; - if (extra.errors) { - extra.errors.push(lexError); - // We have to break on the first error - // to avoid infinite loops. - break; - } else { - throw lexError; - } - } - } - - filterTokenLocation(); - tokens = extra.tokens; - if (typeof extra.comments !== 'undefined') { - tokens.comments = extra.comments; - } - if (typeof extra.errors !== 'undefined') { - tokens.errors = extra.errors; - } - } catch (e) { - throw e; - } finally { - extra = {}; - } - return tokens; - } - - function parse(code, options) { - var program, toString; - - toString = String; - if (typeof code !== 'string' && !(code instanceof String)) { - code = toString(code); - } - - delegate = SyntaxTreeDelegate; - source = code; - index = 0; - lineNumber = (source.length > 0) ? 1 : 0; - lineStart = 0; - length = source.length; - lookahead = null; - state = { - allowIn: true, - labelSet: {}, - inFunctionBody: false, - inIteration: false, - inSwitch: false, - lastCommentStart: -1 - }; - - extra = {}; - if (typeof options !== 'undefined') { - extra.range = (typeof options.range === 'boolean') && options.range; - extra.loc = (typeof options.loc === 'boolean') && options.loc; - extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; - - if (extra.loc && options.source !== null && options.source !== undefined) { - extra.source = toString(options.source); - } - - if (typeof options.tokens === 'boolean' && options.tokens) { - extra.tokens = []; - } - if (typeof options.comment === 'boolean' && options.comment) { - extra.comments = []; - } - if (typeof options.tolerant === 'boolean' && options.tolerant) { - extra.errors = []; - } - if (extra.attachComment) { - extra.range = true; - extra.comments = []; - extra.bottomRightStack = []; - extra.trailingComments = []; - extra.leadingComments = []; - } - } - - try { - program = parseProgram(); - if (typeof extra.comments !== 'undefined') { - program.comments = extra.comments; - } - if (typeof extra.tokens !== 'undefined') { - filterTokenLocation(); - program.tokens = extra.tokens; - } - if (typeof extra.errors !== 'undefined') { - program.errors = extra.errors; - } - } catch (e) { - throw e; - } finally { - extra = {}; - } - - return program; - } - - // Sync with *.json manifests. - exports.version = '1.2.2'; - - exports.tokenize = tokenize; - - exports.parse = parse; - - // Deep copy. - /* istanbul ignore next */ - exports.Syntax = (function () { - var name, types = {}; - - if (typeof Object.create === 'function') { - types = Object.create(null); - } - - for (name in Syntax) { - if (Syntax.hasOwnProperty(name)) { - types[name] = Syntax[name]; - } - } - - if (typeof Object.freeze === 'function') { - Object.freeze(types); - } - - return types; - }()); - - })); - /* vim: set sw=4 ts=4 et tw=80 : */ - - },{}],1:[function(require,module,exports){ - (function (process){ - /* parser generated by jison 0.4.13 */ - /* - Returns a Parser object of the following structure: - - Parser: { - yy: {} - } - - Parser.prototype: { - yy: {}, - trace: function(), - symbols_: {associative list: name ==> number}, - terminals_: {associative list: number ==> name}, - productions_: [...], - performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), - table: [...], - defaultActions: {...}, - parseError: function(str, hash), - parse: function(input), - - lexer: { - EOF: 1, - parseError: function(str, hash), - setInput: function(input), - input: function(), - unput: function(str), - more: function(), - less: function(n), - pastInput: function(), - upcomingInput: function(), - showPosition: function(), - test_match: function(regex_match_array, rule_index), - next: function(), - lex: function(), - begin: function(condition), - popState: function(), - _currentRules: function(), - topState: function(), - pushState: function(condition), - - options: { - ranges: boolean (optional: true ==> token location info will include a .range[] member) - flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) - backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) - }, - - performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), - rules: [...], - conditions: {associative list: name ==> set}, - } - } - - - token location info (@$, _$, etc.): { - first_line: n, - last_line: n, - first_column: n, - last_column: n, - range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) - } - - - the parseError function receives a 'hash' object with these members for lexer and parser errors: { - text: (matched text) - token: (the produced terminal token, if any) - line: (yylineno) - } - while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { - loc: (yylloc) - expected: (string describing the set of expected tokens) - recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) - } - */ - var parser = (function(){ - var parser = {trace: function trace() { }, - yy: {}, - symbols_: {"error":2,"JSON_PATH":3,"DOLLAR":4,"PATH_COMPONENTS":5,"LEADING_CHILD_MEMBER_EXPRESSION":6,"PATH_COMPONENT":7,"MEMBER_COMPONENT":8,"SUBSCRIPT_COMPONENT":9,"CHILD_MEMBER_COMPONENT":10,"DESCENDANT_MEMBER_COMPONENT":11,"DOT":12,"MEMBER_EXPRESSION":13,"DOT_DOT":14,"STAR":15,"IDENTIFIER":16,"SCRIPT_EXPRESSION":17,"INTEGER":18,"END":19,"CHILD_SUBSCRIPT_COMPONENT":20,"DESCENDANT_SUBSCRIPT_COMPONENT":21,"[":22,"SUBSCRIPT":23,"]":24,"SUBSCRIPT_EXPRESSION":25,"SUBSCRIPT_EXPRESSION_LIST":26,"SUBSCRIPT_EXPRESSION_LISTABLE":27,",":28,"STRING_LITERAL":29,"ARRAY_SLICE":30,"FILTER_EXPRESSION":31,"QQ_STRING":32,"Q_STRING":33,"$accept":0,"$end":1}, - terminals_: {2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"}, - productions_: [0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]], - performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */ - /**/) { - /* this == yyval */ - if (!yy.ast) { - yy.ast = _ast; - _ast.initialize(); - } - - var $0 = $$.length - 1; - switch (yystate) { - case 1:yy.ast.set({ expression: { type: "root", value: $$[$0] } }); yy.ast.unshift(); return yy.ast.yield() - break; - case 2:yy.ast.set({ expression: { type: "root", value: $$[$0-1] } }); yy.ast.unshift(); return yy.ast.yield() - break; - case 3:yy.ast.unshift(); return yy.ast.yield() - break; - case 4:yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $$[$0-1] }}); yy.ast.unshift(); return yy.ast.yield() - break; - case 5: - break; - case 6: - break; - case 7:yy.ast.set({ operation: "member" }); yy.ast.push(); - break; - case 8:yy.ast.set({ operation: "subscript" }); yy.ast.push(); - break; - case 9:yy.ast.set({ scope: "child" }); - break; - case 10:yy.ast.set({ scope: "descendant" }); - break; - case 11: - break; - case 12:yy.ast.set({ scope: "child", operation: "member" }); - break; - case 13: - break; - case 14:yy.ast.set({ expression: { type: "wildcard", value: $$[$0] } }); - break; - case 15:yy.ast.set({ expression: { type: "identifier", value: $$[$0] } }); - break; - case 16:yy.ast.set({ expression: { type: "script_expression", value: $$[$0] } }); - break; - case 17:yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($$[$0]) } }); - break; - case 18: - break; - case 19:yy.ast.set({ scope: "child" }); - break; - case 20:yy.ast.set({ scope: "descendant" }); - break; - case 21: - break; - case 22: - break; - case 23: - break; - case 24:$$[$0].length > 1? yy.ast.set({ expression: { type: "union", value: $$[$0] } }) : this.$ = $$[$0]; - break; - case 25:this.$ = [$$[$0]]; - break; - case 26:this.$ = $$[$0-2].concat($$[$0]); - break; - case 27:this.$ = { expression: { type: "numeric_literal", value: parseInt($$[$0]) } }; yy.ast.set(this.$); - break; - case 28:this.$ = { expression: { type: "string_literal", value: $$[$0] } }; yy.ast.set(this.$); - break; - case 29:this.$ = { expression: { type: "slice", value: $$[$0] } }; yy.ast.set(this.$); - break; - case 30:this.$ = { expression: { type: "wildcard", value: $$[$0] } }; yy.ast.set(this.$); - break; - case 31:this.$ = { expression: { type: "script_expression", value: $$[$0] } }; yy.ast.set(this.$); - break; - case 32:this.$ = { expression: { type: "filter_expression", value: $$[$0] } }; yy.ast.set(this.$); - break; - case 33:this.$ = $$[$0]; - break; - case 34:this.$ = $$[$0]; - break; - } - }, - table: [{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}], - defaultActions: {27:[2,23],29:[2,30],30:[2,31],31:[2,32]}, - parseError: function parseError(str, hash) { - if (hash.recoverable) { - this.trace(str); - } else { - throw new Error(str); - } - }, - parse: function parse(input) { - var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, TERROR = 2, EOF = 1; - var args = lstack.slice.call(arguments, 1); - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - this.yy.parser = this; - if (typeof this.lexer.yylloc == 'undefined') { - this.lexer.yylloc = {}; - } - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - var ranges = this.lexer.options && this.lexer.options.ranges; - if (typeof this.yy.parseError === 'function') { - this.parseError = this.yy.parseError; - } else { - this.parseError = Object.getPrototypeOf(this).parseError; - } - function lex() { - var token; - token = self.lexer.lex() || EOF; - if (typeof token !== 'number') { - token = self.symbols_[token] || token; - } - return token; - } - var symbol, preErrorSymbol, state, action, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol === null || typeof symbol == 'undefined') { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === 'undefined' || !action.length || !action[0]) { - var errStr = ''; - expected = []; - for (p in table[state]) { - if (this.terminals_[p] && p > TERROR) { - expected.push('\'' + this.terminals_[p] + '\''); - } - } - if (this.lexer.showPosition) { - errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + this.lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; - } else { - errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); - } - this.parseError(errStr, { - text: this.lexer.match, - token: this.terminals_[symbol] || symbol, - line: this.lexer.yylineno, - loc: yyloc, - expected: expected - }); - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = { - first_line: lstack[lstack.length - (len || 1)].first_line, - last_line: lstack[lstack.length - 1].last_line, - first_column: lstack[lstack.length - (len || 1)].first_column, - last_column: lstack[lstack.length - 1].last_column - }; - if (ranges) { - yyval._$.range = [ - lstack[lstack.length - (len || 1)].range[0], - lstack[lstack.length - 1].range[1] - ]; - } - r = this.performAction.apply(yyval, [ - yytext, - yyleng, - yylineno, - this.yy, - action[1], - vstack, - lstack - ].concat(args)); - if (typeof r !== 'undefined') { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; - }}; - var _ast = { - - initialize: function() { - this._nodes = []; - this._node = {}; - this._stash = []; - }, - - set: function(props) { - for (var k in props) this._node[k] = props[k]; - return this._node; - }, - - node: function(obj) { - if (arguments.length) this._node = obj; - return this._node; - }, - - push: function() { - this._nodes.push(this._node); - this._node = {}; - }, - - unshift: function() { - this._nodes.unshift(this._node); - this._node = {}; - }, - - yield: function() { - var _nodes = this._nodes; - this.initialize(); - return _nodes; - } - }; - /* generated by jison-lex 0.2.1 */ - var lexer = (function(){ - var lexer = { - - EOF:1, - - parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, - - // resets the lexer, sets new input - setInput:function (input) { - this._input = input; - this._more = this._backtrack = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = { - first_line: 1, - first_column: 0, - last_line: 1, - last_column: 0 - }; - if (this.options.ranges) { - this.yylloc.range = [0,0]; - } - this.offset = 0; - return this; - }, - - // consumes and returns one char from the input - input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) { - this.yylloc.range[1]++; - } - - this._input = this._input.slice(1); - return ch; - }, - - // unshifts one char (or a string) into the input - unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length - 1); - this.matched = this.matched.substr(0, this.matched.length - 1); - - if (lines.length - 1) { - this.yylineno -= lines.length - 1; - } - var r = this.yylloc.range; - - this.yylloc = { - first_line: this.yylloc.first_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) - + oldLines[oldLines.length - lines.length].length - lines[0].length : - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - this.yyleng = this.yytext.length; - return this; - }, - - // When called from action, caches matched text and appends it on next action - more:function () { - this._more = true; - return this; - }, - - // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. - reject:function () { - if (this.options.backtrack_lexer) { - this._backtrack = true; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); - - } - return this; - }, - - // retain first n characters of the match - less:function (n) { - this.unput(this.match.slice(n)); - }, - - // displays already matched input, i.e. for error messages - pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, - - // displays upcoming input, i.e. for error messages - upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); - }, - - // displays the character position where the lexing error occurred, i.e. for error messages - showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c + "^"; - }, - - // test the lexed token: return FALSE when not a match, otherwise return token - test_match:function (match, indexed_rule) { - var token, - lines, - backup; - - if (this.options.backtrack_lexer) { - // save context - backup = { - yylineno: this.yylineno, - yylloc: { - first_line: this.yylloc.first_line, - last_line: this.last_line, - first_column: this.yylloc.first_column, - last_column: this.yylloc.last_column - }, - yytext: this.yytext, - match: this.match, - matches: this.matches, - matched: this.matched, - yyleng: this.yyleng, - offset: this.offset, - _more: this._more, - _input: this._input, - yy: this.yy, - conditionStack: this.conditionStack.slice(0), - done: this.done - }; - if (this.options.ranges) { - backup.yylloc.range = this.yylloc.range.slice(0); - } - } - - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno += lines.length; - } - this.yylloc = { - first_line: this.yylloc.last_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.last_column, - last_column: lines ? - lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : - this.yylloc.last_column + match[0].length - }; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._backtrack = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); - if (this.done && this._input) { - this.done = false; - } - if (token) { - return token; - } else if (this._backtrack) { - // recover context - for (var k in backup) { - this[k] = backup[k]; - } - return false; // rule action called reject() implying the next rule should be tested instead. - } - return false; - }, - - // return next match in input - next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) { - this.done = true; - } - - var token, - match, - tempMatch, - index; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i = 0; i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (this.options.backtrack_lexer) { - token = this.test_match(tempMatch, rules[i]); - if (token !== false) { - return token; - } else if (this._backtrack) { - match = false; - continue; // rule action called reject() implying a rule MISmatch. - } else { - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - } else if (!this.options.flex) { - break; - } - } - } - if (match) { - token = this.test_match(match, rules[index]); - if (token !== false) { - return token; - } - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); - } - }, - - // return next match that has a token - lex:function lex() { - var r = this.next(); - if (r) { - return r; - } else { - return this.lex(); - } - }, - - // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) - begin:function begin(condition) { - this.conditionStack.push(condition); - }, - - // pop the previously active lexer condition state off the condition stack - popState:function popState() { - var n = this.conditionStack.length - 1; - if (n > 0) { - return this.conditionStack.pop(); - } else { - return this.conditionStack[0]; - } - }, - - // produce the lexer rule set which is active for the currently active lexer condition state - _currentRules:function _currentRules() { - if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { - return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; - } else { - return this.conditions["INITIAL"].rules; - } - }, - - // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available - topState:function topState(n) { - n = this.conditionStack.length - 1 - Math.abs(n || 0); - if (n >= 0) { - return this.conditionStack[n]; - } else { - return "INITIAL"; - } - }, - - // alias for begin(condition) - pushState:function pushState(condition) { - this.begin(condition); - }, - - // return the number of states currently on the stack - stateStackSize:function stateStackSize() { - return this.conditionStack.length; - }, - options: {}, - performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START - /**/) { - switch($avoiding_name_collisions) { - case 0:return 4 - break; - case 1:return 14 - break; - case 2:return 12 - break; - case 3:return 15 - break; - case 4:return 16 - break; - case 5:return 22 - break; - case 6:return 24 - break; - case 7:return 28 - break; - case 8:return 30 - break; - case 9:return 18 - break; - case 10:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 32; - break; - case 11:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 33; - break; - case 12:return 17 - break; - case 13:return 31 - break; - } - }, - rules: [/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/], - conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}} - }; - return lexer; - })(); - parser.lexer = lexer; - function Parser () { - this.yy = {}; - } - Parser.prototype = parser;parser.Parser = Parser; - return new Parser; - })(); - - - if (typeof require !== 'undefined' && typeof exports !== 'undefined') { - exports.parser = parser; - exports.Parser = parser.Parser; - exports.parse = function () { return parser.parse.apply(parser, arguments); }; - exports.main = function commonjsMain(args) { - if (!args[1]) { - console.log('Usage: '+args[0]+' FILE'); - process.exit(1); - } - var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8"); - return exports.parser.parse(source); - }; - if (typeof module !== 'undefined' && require.main === module) { - exports.main(process.argv.slice(1)); - } - } - - }).call(this,require('_process')); - },{"_process":12,"fs":8,"path":11}],2:[function(require,module,exports){ - module.exports = { - identifier: "[a-zA-Z_]+[a-zA-Z0-9_]*", - integer: "-?(?:0|[1-9][0-9]*)", - qq_string: "\"(?:\\\\[\"bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\"\\\\])*\"", - q_string: "'(?:\\\\[\'bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\'\\\\])*'" - }; - - },{}],3:[function(require,module,exports){ - var dict = require('./dict'); - var fs = require('fs'); - var grammar = { - - lex: { - - macros: { - esc: "\\\\", - int: dict.integer - }, - - rules: [ - ["\\$", "return 'DOLLAR'"], - ["\\.\\.", "return 'DOT_DOT'"], - ["\\.", "return 'DOT'"], - ["\\*", "return 'STAR'"], - [dict.identifier, "return 'IDENTIFIER'"], - ["\\[", "return '['"], - ["\\]", "return ']'"], - [",", "return ','"], - ["({int})?\\:({int})?(\\:({int})?)?", "return 'ARRAY_SLICE'"], - ["{int}", "return 'INTEGER'"], - [dict.qq_string, "yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"], - [dict.q_string, "yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"], - ["\\(.+?\\)(?=\\])", "return 'SCRIPT_EXPRESSION'"], - ["\\?\\(.+?\\)(?=\\])", "return 'FILTER_EXPRESSION'"] - ] - }, - - start: "JSON_PATH", - - bnf: { - - JSON_PATH: [ - [ 'DOLLAR', 'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()' ], - [ 'DOLLAR PATH_COMPONENTS', 'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()' ], - [ 'LEADING_CHILD_MEMBER_EXPRESSION', 'yy.ast.unshift(); return yy.ast.yield()' ], - [ 'LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS', 'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()' ] ], - - PATH_COMPONENTS: [ - [ 'PATH_COMPONENT', '' ], - [ 'PATH_COMPONENTS PATH_COMPONENT', '' ] ], - - PATH_COMPONENT: [ - [ 'MEMBER_COMPONENT', 'yy.ast.set({ operation: "member" }); yy.ast.push()' ], - [ 'SUBSCRIPT_COMPONENT', 'yy.ast.set({ operation: "subscript" }); yy.ast.push() ' ] ], - - MEMBER_COMPONENT: [ - [ 'CHILD_MEMBER_COMPONENT', 'yy.ast.set({ scope: "child" })' ], - [ 'DESCENDANT_MEMBER_COMPONENT', 'yy.ast.set({ scope: "descendant" })' ] ], - - CHILD_MEMBER_COMPONENT: [ - [ 'DOT MEMBER_EXPRESSION', '' ] ], - - LEADING_CHILD_MEMBER_EXPRESSION: [ - [ 'MEMBER_EXPRESSION', 'yy.ast.set({ scope: "child", operation: "member" })' ] ], - - DESCENDANT_MEMBER_COMPONENT: [ - [ 'DOT_DOT MEMBER_EXPRESSION', '' ] ], - - MEMBER_EXPRESSION: [ - [ 'STAR', 'yy.ast.set({ expression: { type: "wildcard", value: $1 } })' ], - [ 'IDENTIFIER', 'yy.ast.set({ expression: { type: "identifier", value: $1 } })' ], - [ 'SCRIPT_EXPRESSION', 'yy.ast.set({ expression: { type: "script_expression", value: $1 } })' ], - [ 'INTEGER', 'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })' ], - [ 'END', '' ] ], - - SUBSCRIPT_COMPONENT: [ - [ 'CHILD_SUBSCRIPT_COMPONENT', 'yy.ast.set({ scope: "child" })' ], - [ 'DESCENDANT_SUBSCRIPT_COMPONENT', 'yy.ast.set({ scope: "descendant" })' ] ], - - CHILD_SUBSCRIPT_COMPONENT: [ - [ '[ SUBSCRIPT ]', '' ] ], - - DESCENDANT_SUBSCRIPT_COMPONENT: [ - [ 'DOT_DOT [ SUBSCRIPT ]', '' ] ], - - SUBSCRIPT: [ - [ 'SUBSCRIPT_EXPRESSION', '' ], - [ 'SUBSCRIPT_EXPRESSION_LIST', '$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1' ] ], - - SUBSCRIPT_EXPRESSION_LIST: [ - [ 'SUBSCRIPT_EXPRESSION_LISTABLE', '$$ = [$1]'], - [ 'SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE', '$$ = $1.concat($3)' ] ], - - SUBSCRIPT_EXPRESSION_LISTABLE: [ - [ 'INTEGER', '$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)' ], - [ 'STRING_LITERAL', '$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)' ], - [ 'ARRAY_SLICE', '$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)' ] ], - - SUBSCRIPT_EXPRESSION: [ - [ 'STAR', '$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)' ], - [ 'SCRIPT_EXPRESSION', '$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)' ], - [ 'FILTER_EXPRESSION', '$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)' ] ], - - STRING_LITERAL: [ - [ 'QQ_STRING', "$$ = $1" ], - [ 'Q_STRING', "$$ = $1" ] ] - } - }; - if (fs.readFileSync) { - grammar.moduleInclude = fs.readFileSync(require.resolve("../include/module.js")); - grammar.actionInclude = fs.readFileSync(require.resolve("../include/action.js")); - } - - module.exports = grammar; - - },{"./dict":2,"fs":8}],4:[function(require,module,exports){ - var aesprim = require('./aesprim'); - var slice = require('./slice'); - var _evaluate = require('static-eval'); - var _uniq = require('underscore').uniq; - - var Handlers = function() { - return this.initialize.apply(this, arguments); - }; - - Handlers.prototype.initialize = function() { - this.traverse = traverser(true); - this.descend = traverser(); - }; - - Handlers.prototype.keys = Object.keys; - - Handlers.prototype.resolve = function(component) { - - var key = [ component.operation, component.scope, component.expression.type ].join('-'); - var method = this._fns[key]; - - if (!method) throw new Error("couldn't resolve key: " + key); - return method.bind(this); - }; - - Handlers.prototype.register = function(key, handler) { - - if (!handler instanceof Function) { - throw new Error("handler must be a function"); - } - - this._fns[key] = handler; - }; - - Handlers.prototype._fns = { - - 'member-child-identifier': function(component, partial) { - var key = component.expression.value; - var value = partial.value; - if (value instanceof Object && key in value) { - return [ { value: value[key], path: partial.path.concat(key) } ] - } - }, - - 'member-descendant-identifier': - _traverse(function(key, value, ref) { return key == ref }), - - 'subscript-child-numeric_literal': - _descend(function(key, value, ref) { return key === ref }), - - 'member-child-numeric_literal': - _descend(function(key, value, ref) { return String(key) === String(ref) }), - - 'subscript-descendant-numeric_literal': - _traverse(function(key, value, ref) { return key === ref }), - - 'member-child-wildcard': - _descend(function() { return true }), - - 'member-descendant-wildcard': - _traverse(function() { return true }), - - 'subscript-descendant-wildcard': - _traverse(function() { return true }), - - 'subscript-child-wildcard': - _descend(function() { return true }), - - 'subscript-child-slice': function(component, partial) { - if (is_array(partial.value)) { - var args = component.expression.value.split(':').map(_parse_nullable_int); - var values = partial.value.map(function(v, i) { return { value: v, path: partial.path.concat(i) } }); - return slice.apply(null, [values].concat(args)); - } - }, - - 'subscript-child-union': function(component, partial) { - var results = []; - component.expression.value.forEach(function(component) { - var _component = { operation: 'subscript', scope: 'child', expression: component.expression }; - var handler = this.resolve(_component); - var _results = handler(_component, partial); - if (_results) { - results = results.concat(_results); - } - }, this); - - return unique(results); - }, - - 'subscript-descendant-union': function(component, partial, count) { - - var jp = require('..'); - var self = this; - - var results = []; - var nodes = jp.nodes(partial, '$..*').slice(1); - - nodes.forEach(function(node) { - if (results.length >= count) return; - component.expression.value.forEach(function(component) { - var _component = { operation: 'subscript', scope: 'child', expression: component.expression }; - var handler = self.resolve(_component); - var _results = handler(_component, node); - results = results.concat(_results); - }); - }); - - return unique(results); - }, - - 'subscript-child-filter_expression': function(component, partial, count) { - - // slice out the expression from ?(expression) - var src = component.expression.value.slice(2, -1); - var ast = aesprim.parse(src).body[0].expression; - - var passable = function(key, value) { - return evaluate(ast, { '@': value }); - }; - - return this.descend(partial, null, passable, count); - - }, - - 'subscript-descendant-filter_expression': function(component, partial, count) { - - // slice out the expression from ?(expression) - var src = component.expression.value.slice(2, -1); - var ast = aesprim.parse(src).body[0].expression; - - var passable = function(key, value) { - return evaluate(ast, { '@': value }); - }; - - return this.traverse(partial, null, passable, count); - }, - - 'subscript-child-script_expression': function(component, partial) { - var exp = component.expression.value.slice(1, -1); - return eval_recurse(partial, exp, '$[{{value}}]'); - }, - - 'member-child-script_expression': function(component, partial) { - var exp = component.expression.value.slice(1, -1); - return eval_recurse(partial, exp, '$.{{value}}'); - }, - - 'member-descendant-script_expression': function(component, partial) { - var exp = component.expression.value.slice(1, -1); - return eval_recurse(partial, exp, '$..value'); - } - }; - - Handlers.prototype._fns['subscript-child-string_literal'] = - Handlers.prototype._fns['member-child-identifier']; - - Handlers.prototype._fns['member-descendant-numeric_literal'] = - Handlers.prototype._fns['subscript-descendant-string_literal'] = - Handlers.prototype._fns['member-descendant-identifier']; - - function eval_recurse(partial, src, template) { - - var jp = require('./index'); - var ast = aesprim.parse(src).body[0].expression; - var value = evaluate(ast, { '@': partial.value }); - var path = template.replace(/\{\{\s*value\s*\}\}/g, value); - - var results = jp.nodes(partial.value, path); - results.forEach(function(r) { - r.path = partial.path.concat(r.path.slice(1)); - }); - - return results; - } - - function is_array(val) { - return Array.isArray(val); - } - - function is_object(val) { - // is this a non-array, non-null object? - return val && !(val instanceof Array) && val instanceof Object; - } - - function traverser(recurse) { - - return function(partial, ref, passable, count) { - - var value = partial.value; - var path = partial.path; - - var results = []; - - var descend = function(value, path) { - - if (is_array(value)) { - value.forEach(function(element, index) { - if (results.length >= count) { return } - if (passable(index, element, ref)) { - results.push({ path: path.concat(index), value: element }); - } - }); - value.forEach(function(element, index) { - if (results.length >= count) { return } - if (recurse) { - descend(element, path.concat(index)); - } - }); - } else if (is_object(value)) { - this.keys(value).forEach(function(k) { - if (results.length >= count) { return } - if (passable(k, value[k], ref)) { - results.push({ path: path.concat(k), value: value[k] }); - } - }); - this.keys(value).forEach(function(k) { - if (results.length >= count) { return } - if (recurse) { - descend(value[k], path.concat(k)); - } - }); - } - }.bind(this); - descend(value, path); - return results; - } - } - - function _descend(passable) { - return function(component, partial, count) { - return this.descend(partial, component.expression.value, passable, count); - } - } - - function _traverse(passable) { - return function(component, partial, count) { - return this.traverse(partial, component.expression.value, passable, count); - } - } - - function evaluate() { - try { return _evaluate.apply(this, arguments) } - catch (e) { } - } - - function unique(results) { - results = results.filter(function(d) { return d }); - return _uniq( - results, - function(r) { return r.path.map(function(c) { return String(c).replace('-', '--') }).join('-') } - ); - } - - function _parse_nullable_int(val) { - var sval = String(val); - return sval.match(/^-?[0-9]+$/) ? parseInt(sval) : null; - } - - module.exports = Handlers; - - },{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,"underscore":8}],5:[function(require,module,exports){ - var assert = require('assert'); - var dict = require('./dict'); - var Parser = require('./parser'); - var Handlers = require('./handlers'); - - var JSONPath = function() { - this.initialize.apply(this, arguments); - }; - - JSONPath.prototype.initialize = function() { - this.parser = new Parser(); - this.handlers = new Handlers(); - }; - - JSONPath.prototype.parse = function(string) { - assert.ok(_is_string(string), "we need a path"); - return this.parser.parse(string); - }; - - JSONPath.prototype.parent = function(obj, string) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(string, "we need a path"); - - var node = this.nodes(obj, string)[0]; - var key = node.path.pop(); /* jshint unused:false */ - return this.value(obj, node.path); - }; - - JSONPath.prototype.apply = function(obj, string, fn) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(string, "we need a path"); - assert.equal(typeof fn, "function", "fn needs to be function"); - - var nodes = this.nodes(obj, string).sort(function(a, b) { - // sort nodes so we apply from the bottom up - return b.path.length - a.path.length; - }); - - nodes.forEach(function(node) { - var key = node.path.pop(); - var parent = this.value(obj, this.stringify(node.path)); - var val = node.value = fn.call(obj, parent[key]); - parent[key] = val; - }, this); - - return nodes; - }; - - JSONPath.prototype.value = function(obj, path, value) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(path, "we need a path"); - - if (arguments.length >= 3) { - var node = this.nodes(obj, path).shift(); - if (!node) return this._vivify(obj, path, value); - var key = node.path.slice(-1).shift(); - var parent = this.parent(obj, this.stringify(node.path)); - parent[key] = value; - } - return this.query(obj, this.stringify(path), 1).shift(); - }; - - JSONPath.prototype._vivify = function(obj, string, value) { - - var self = this; - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(string, "we need a path"); - - var path = this.parser.parse(string) - .map(function(component) { return component.expression.value }); - - var setValue = function(path, value) { - var key = path.pop(); - var node = self.value(obj, path); - if (!node) { - setValue(path.concat(), typeof key === 'string' ? {} : []); - node = self.value(obj, path); - } - node[key] = value; - }; - setValue(path, value); - return this.query(obj, string)[0]; - }; - - JSONPath.prototype.query = function(obj, string, count) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(_is_string(string), "we need a path"); - - var results = this.nodes(obj, string, count) - .map(function(r) { return r.value }); - - return results; - }; - - JSONPath.prototype.paths = function(obj, string, count) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(string, "we need a path"); - - var results = this.nodes(obj, string, count) - .map(function(r) { return r.path }); - - return results; - }; - - JSONPath.prototype.nodes = function(obj, string, count) { - - assert.ok(obj instanceof Object, "obj needs to be an object"); - assert.ok(string, "we need a path"); - - if (count === 0) return []; - - var path = this.parser.parse(string); - var handlers = this.handlers; - - var partials = [ { path: ['$'], value: obj } ]; - var matches = []; - - if (path.length && path[0].expression.type == 'root') path.shift(); - - if (!path.length) return partials; - - path.forEach(function(component, index) { - - if (matches.length >= count) return; - var handler = handlers.resolve(component); - var _partials = []; - - partials.forEach(function(p) { - - if (matches.length >= count) return; - var results = handler(component, p, count); - - if (index == path.length - 1) { - // if we're through the components we're done - matches = matches.concat(results || []); - } else { - // otherwise accumulate and carry on through - _partials = _partials.concat(results || []); - } - }); - - partials = _partials; - - }); - - return count ? matches.slice(0, count) : matches; - }; - - JSONPath.prototype.stringify = function(path) { - - assert.ok(path, "we need a path"); - - var string = '$'; - - var templates = { - 'descendant-member': '..{{value}}', - 'child-member': '.{{value}}', - 'descendant-subscript': '..[{{value}}]', - 'child-subscript': '[{{value}}]' - }; - - path = this._normalize(path); - - path.forEach(function(component) { - - if (component.expression.type == 'root') return; - - var key = [component.scope, component.operation].join('-'); - var template = templates[key]; - var value; - - if (component.expression.type == 'string_literal') { - value = JSON.stringify(component.expression.value); - } else { - value = component.expression.value; - } - - if (!template) throw new Error("couldn't find template " + key); - - string += template.replace(/{{value}}/, value); - }); - - return string; - }; - - JSONPath.prototype._normalize = function(path) { - - assert.ok(path, "we need a path"); - - if (typeof path == "string") { - - return this.parser.parse(path); - - } else if (Array.isArray(path) && typeof path[0] == "string") { - - var _path = [ { expression: { type: "root", value: "$" } } ]; - - path.forEach(function(component, index) { - - if (component == '$' && index === 0) return; - - if (typeof component == "string" && component.match("^" + dict.identifier + "$")) { - - _path.push({ - operation: 'member', - scope: 'child', - expression: { value: component, type: 'identifier' } - }); - - } else { - - var type = typeof component == "number" ? - 'numeric_literal' : 'string_literal'; - - _path.push({ - operation: 'subscript', - scope: 'child', - expression: { value: component, type: type } - }); - } - }); - - return _path; - - } else if (Array.isArray(path) && typeof path[0] == "object") { - - return path - } - - throw new Error("couldn't understand path " + path); - }; - - function _is_string(obj) { - return Object.prototype.toString.call(obj) == '[object String]'; - } - - JSONPath.Handlers = Handlers; - JSONPath.Parser = Parser; - - var instance = new JSONPath; - instance.JSONPath = JSONPath; - - module.exports = instance; - - },{"./dict":2,"./handlers":4,"./parser":6,"assert":9}],6:[function(require,module,exports){ - var grammar = require('./grammar'); - var gparser = require('../generated/parser'); - - var Parser = function() { - - var parser = new gparser.Parser(); - - var _parseError = parser.parseError; - parser.yy.parseError = function() { - if (parser.yy.ast) { - parser.yy.ast.initialize(); - } - _parseError.apply(parser, arguments); - }; - - return parser; - - }; - - Parser.grammar = grammar; - module.exports = Parser; - - },{"../generated/parser":1,"./grammar":3}],7:[function(require,module,exports){ - module.exports = function(arr, start, end, step) { - - if (typeof start == 'string') throw new Error("start cannot be a string"); - if (typeof end == 'string') throw new Error("end cannot be a string"); - if (typeof step == 'string') throw new Error("step cannot be a string"); - - var len = arr.length; - - if (step === 0) throw new Error("step cannot be zero"); - step = step ? integer(step) : 1; - - // normalize negative values - start = start < 0 ? len + start : start; - end = end < 0 ? len + end : end; - - // default extents to extents - start = integer(start === 0 ? 0 : !start ? (step > 0 ? 0 : len - 1) : start); - end = integer(end === 0 ? 0 : !end ? (step > 0 ? len : -1) : end); - - // clamp extents - start = step > 0 ? Math.max(0, start) : Math.min(len, start); - end = step > 0 ? Math.min(end, len) : Math.max(-1, end); - - // return empty if extents are backwards - if (step > 0 && end <= start) return []; - if (step < 0 && start <= end) return []; - - var result = []; - - for (var i = start; i != end; i += step) { - if ((step < 0 && i <= end) || (step > 0 && i >= end)) break; - result.push(arr[i]); - } - - return result; - }; - - function integer(val) { - return String(val).match(/^[0-9]+$/) ? parseInt(val) : - Number.isFinite(val) ? parseInt(val, 10) : 0; - } - - },{}],8:[function(require,module,exports){ - - },{}],9:[function(require,module,exports){ - // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 - // - // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! - // - // Originally from narwhal.js (http://narwhaljs.org) - // Copyright (c) 2009 Thomas Robinson <280north.com> - // - // Permission is hereby granted, free of charge, to any person obtaining a copy - // of this software and associated documentation files (the 'Software'), to - // deal in the Software without restriction, including without limitation the - // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - // sell copies of the Software, and to permit persons to whom the Software is - // furnished to do so, subject to the following conditions: - // - // The above copyright notice and this permission notice shall be included in - // all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - // when used in node, this will actually load the util module we depend on - // versus loading the builtin util module as happens otherwise - // this is a bug in node module loading as far as I am concerned - var util = require('util/'); - - var pSlice = Array.prototype.slice; - var hasOwn = Object.prototype.hasOwnProperty; - - // 1. The assert module provides functions that throw - // AssertionError's when particular conditions are not met. The - // assert module must conform to the following interface. - - var assert = module.exports = ok; - - // 2. The AssertionError is defined in assert. - // new assert.AssertionError({ message: message, - // actual: actual, - // expected: expected }) - - assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } - }; - - // assert.AssertionError instanceof Error - util.inherits(assert.AssertionError, Error); - - function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && !isFinite(value)) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; - } - - function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } - } - - function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); - } - - // At present only the three keys mentioned above are used and - // understood by the spec. Implementations or sub modules can pass - // other keys to the AssertionError's constructor - they will be - // ignored. - - // 3. All of the following functions must throw an AssertionError - // when a corresponding condition is not met, with a message that - // may be undefined if not provided. All assertion methods provide - // both the actual and expected values to the assertion error for - // display purposes. - - function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); - } - - // EXTENSION! allows for well behaved errors defined elsewhere. - assert.fail = fail; - - // 4. Pure assertion tests whether a value is truthy, as determined - // by !!guard. - // assert.ok(guard, message_opt); - // This statement is equivalent to assert.equal(true, !!guard, - // message_opt);. To test strictly for the value true, use - // assert.strictEqual(true, guard, message_opt);. - - function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); - } - assert.ok = ok; - - // 5. The equality assertion tests shallow, coercive equality with - // ==. - // assert.equal(actual, expected, message_opt); - - assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); - }; - - // 6. The non-equality assertion tests for whether two objects are not equal - // with != assert.notEqual(actual, expected, message_opt); - - assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } - }; - - // 7. The equivalence assertion tests a deep equality relation. - // assert.deepEqual(actual, expected, message_opt); - - assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } - }; - - function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } - } - - function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; - } - - function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) { - return a === b; - } - var aIsArgs = isArguments(a), - bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; - } - - // 8. The non-equivalence assertion tests for any deep inequality. - // assert.notDeepEqual(actual, expected, message_opt); - - assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } - }; - - // 9. The strict equality assertion tests strict equality, as determined by ===. - // assert.strictEqual(actual, expected, message_opt); - - assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } - }; - - // 10. The strict non-equality assertion tests for strict inequality, as - // determined by !==. assert.notStrictEqual(actual, expected, message_opt); - - assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } - }; - - function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; - } - - function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } - } - - // 11. Expected to throw an error: - // assert.throws(block, Error_opt, message_opt); - - assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); - }; - - // EXTENSION! This is annoying to write outside this module. - assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); - }; - - assert.ifError = function(err) { if (err) {throw err;}}; - - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; - }; - - },{"util/":14}],10:[function(require,module,exports){ - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - - },{}],11:[function(require,module,exports){ - (function (process){ - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); - }; - - // path.resolve([from ...], to) - // posix version - exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - }; - - // path.normalize(path) - // posix version - exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; - }; - - // posix version - exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; - }; - - // posix version - exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); - }; - - - // path.relative(from, to) - // posix version - exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - }; - - exports.sep = '/'; - exports.delimiter = ':'; - - exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - }; - - - exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; - }; - - - exports.extname = function(path) { - return splitPath(path)[3]; - }; - - function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; - } - - // String.prototype.substr - negative index don't work in IE8 - var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } - ; - - }).call(this,require('_process')); - },{"_process":12}],12:[function(require,module,exports){ - // shim for using process in browser - - var process = module.exports = {}; - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = setTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - clearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - setTimeout(drainQueue, 0); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - },{}],13:[function(require,module,exports){ - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - }; - },{}],14:[function(require,module,exports){ - (function (process,global){ - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.warn('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = require('./support/isBuffer'); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = require('inherits'); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - }).call(this,require('_process'),typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); - },{"./support/isBuffer":13,"_process":12,"inherits":10}],15:[function(require,module,exports){ - var unparse = require('escodegen').generate; - - module.exports = function (ast, vars) { - if (!vars) vars = {}; - var FAIL = {}; - - var result = (function walk (node) { - if (node.type === 'Literal') { - return node.value; - } - else if (node.type === 'UnaryExpression'){ - var val = walk(node.argument); - if (node.operator === '+') return +val - if (node.operator === '-') return -val - if (node.operator === '~') return ~val - if (node.operator === '!') return !val - return FAIL - } - else if (node.type === 'ArrayExpression') { - var xs = []; - for (var i = 0, l = node.elements.length; i < l; i++) { - var x = walk(node.elements[i]); - if (x === FAIL) return FAIL; - xs.push(x); - } - return xs; - } - else if (node.type === 'ObjectExpression') { - var obj = {}; - for (var i = 0; i < node.properties.length; i++) { - var prop = node.properties[i]; - var value = prop.value === null - ? prop.value - : walk(prop.value) - ; - if (value === FAIL) return FAIL; - obj[prop.key.value || prop.key.name] = value; - } - return obj; - } - else if (node.type === 'BinaryExpression' || - node.type === 'LogicalExpression') { - var l = walk(node.left); - if (l === FAIL) return FAIL; - var r = walk(node.right); - if (r === FAIL) return FAIL; - - var op = node.operator; - if (op === '==') return l == r; - if (op === '===') return l === r; - if (op === '!=') return l != r; - if (op === '!==') return l !== r; - if (op === '+') return l + r; - if (op === '-') return l - r; - if (op === '*') return l * r; - if (op === '/') return l / r; - if (op === '%') return l % r; - if (op === '<') return l < r; - if (op === '<=') return l <= r; - if (op === '>') return l > r; - if (op === '>=') return l >= r; - if (op === '|') return l | r; - if (op === '&') return l & r; - if (op === '^') return l ^ r; - if (op === '&&') return l && r; - if (op === '||') return l || r; - - return FAIL; - } - else if (node.type === 'Identifier') { - if ({}.hasOwnProperty.call(vars, node.name)) { - return vars[node.name]; - } - else return FAIL; - } - else if (node.type === 'CallExpression') { - var callee = walk(node.callee); - if (callee === FAIL) return FAIL; - - var ctx = node.callee.object ? walk(node.callee.object) : FAIL; - if (ctx === FAIL) ctx = null; - - var args = []; - for (var i = 0, l = node.arguments.length; i < l; i++) { - var x = walk(node.arguments[i]); - if (x === FAIL) return FAIL; - args.push(x); - } - return callee.apply(ctx, args); - } - else if (node.type === 'MemberExpression') { - var obj = walk(node.object); - if (obj === FAIL) return FAIL; - if (node.property.type === 'Identifier') { - return obj[node.property.name]; - } - var prop = walk(node.property); - if (prop === FAIL) return FAIL; - return obj[prop]; - } - else if (node.type === 'ConditionalExpression') { - var val = walk(node.test); - if (val === FAIL) return FAIL; - return val ? walk(node.consequent) : walk(node.alternate) - } - else if (node.type === 'FunctionExpression') { - return Function('return ' + unparse(node))(); - } - else return FAIL; - })(ast); - - return result === FAIL ? undefined : result; - }; - - },{"escodegen":8}],"jsonpath":[function(require,module,exports){ - module.exports = require('./lib/index'); - - },{"./lib/index":5}]},{},["jsonpath"])("jsonpath") - }); - }); - - var jsonSchemaRefParser = createCommonjsModule(function(module, exports) {/*! -* JSON Schema $Ref Parser v5.0.0 (March 18th 2018) -* -* https://github.com/BigstickCarpet/json-schema-ref-parser -* -* @author James Messinger (http://bigstickcarpet.com) -* @license MIT -*/ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.$RefParser = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - keys.splice(0, 0, keys.splice(defs, 1)[0]); - } - - keys.forEach(function (key) { - var keyPath = Pointer.join(path, key); - var keyPathFromRoot = Pointer.join(pathFromRoot, key); - var value = obj[key]; - - if ($Ref.isAllowed$Ref(value)) { - inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options); - } - else { - crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options); - } - }); - } -} -} - -/** -* Inventories the given JSON Reference (i.e. records detailed information about it so we can -* optimize all $refs in the schema), and then crawls the resolved value. -* -* @param {object} $refParent - The object that contains a JSON Reference as one of its keys -* @param {string} $refKey - The key in `$refParent` that is a JSON Reference -* @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash -* @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root -* @param {object[]} inventory - An array of already-inventoried $ref pointers -* @param {$Refs} $refs -* @param {$RefParserOptions} options -*/ -function inventory$Ref ($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) { -var $ref = $refKey === null ? $refParent : $refParent[$refKey]; -var $refPath = url.resolve(path, $ref.$ref); -var pointer = $refs._resolve($refPath, options); -var depth = Pointer.parse(pathFromRoot).length; -var file = url.stripHash(pointer.path); -var hash = url.getHash(pointer.path); -var external = file !== $refs._root$Ref.path; -var extended = $Ref.isExtended$Ref($ref); -indirections += pointer.indirections; - -var existingEntry = findInInventory(inventory, $refParent, $refKey); -if (existingEntry) { - // This $Ref has already been inventoried, so we don't need to process it again - if (depth < existingEntry.depth || indirections < existingEntry.indirections) { - removeFromInventory(inventory, existingEntry); - } - else { - return; - } -} - -inventory.push({ - $ref: $ref, // The JSON Reference (e.g. {$ref: string}) - parent: $refParent, // The object that contains this $ref pointer - key: $refKey, // The key in `parent` that is the $ref pointer - pathFromRoot: pathFromRoot, // The path to the $ref pointer, from the JSON Schema root - depth: depth, // How far from the JSON Schema root is this $ref pointer? - file: file, // The file that the $ref pointer resolves to - hash: hash, // The hash within `file` that the $ref pointer resolves to - value: pointer.value, // The resolved value of the $ref pointer - circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself) - extended: extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref") - external: external, // Does this $ref pointer point to a file other than the main JSON Schema file? - indirections: indirections, // The number of indirect references that were traversed to resolve the value -}); - -// Recursively crawl the resolved value -crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options); -} - -/** -* Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema. -* Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same -* value are re-mapped to point to the first reference. -* -* @example: -* { -* first: { $ref: somefile.json#/some/part }, -* second: { $ref: somefile.json#/another/part }, -* third: { $ref: somefile.json }, -* fourth: { $ref: somefile.json#/some/part/sub/part } -* } -* -* In this example, there are four references to the same file, but since the third reference points -* to the ENTIRE file, that's the only one we need to dereference. The other three can just be -* remapped to point inside the third one. -* -* On the other hand, if the third reference DIDN'T exist, then the first and second would both need -* to be dereferenced, since they point to different parts of the file. The fourth reference does NOT -* need to be dereferenced, because it can be remapped to point inside the first one. -* -* @param {object[]} inventory -*/ -function remap (inventory) { -// Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them -inventory.sort(function (a, b) { - if (a.file !== b.file) { - return a.file < b.file ? -1 : +1; // Group all the $refs that point to the same file - } - else if (a.hash !== b.hash) { - return a.hash < b.hash ? -1 : +1; // Group all the $refs that point to the same part of the file - } - else if (a.circular !== b.circular) { - return a.circular ? -1 : +1; // If the $ref points to itself, then sort it higher than other $refs that point to this $ref - } - else if (a.extended !== b.extended) { - return a.extended ? +1 : -1; // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value - } - else if (a.indirections !== b.indirections) { - return a.indirections - b.indirections; // Sort direct references higher than indirect references - } - else if (a.depth !== b.depth) { - return a.depth - b.depth; // Sort $refs by how close they are to the JSON Schema root - } - else { - // If all else is equal, use the $ref that's in the "definitions" property - return b.pathFromRoot.lastIndexOf('/definitions') - a.pathFromRoot.lastIndexOf('/definitions'); - } -}); - -var file, hash, pathFromRoot; -inventory.forEach(function (entry) { - debug('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot); - - if (!entry.external) { - // This $ref already resolves to the main JSON Schema file - entry.$ref.$ref = entry.hash; - } - else if (entry.file === file && entry.hash === hash) { - // This $ref points to the same value as the prevous $ref, so remap it to the same path - entry.$ref.$ref = pathFromRoot; - } - else if (entry.file === file && entry.hash.indexOf(hash + '/') === 0) { - // This $ref points to the a sub-value as the prevous $ref, so remap it beneath that path - entry.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(entry.hash)); - } - else { - // We've moved to a new file or new hash - file = entry.file; - hash = entry.hash; - pathFromRoot = entry.pathFromRoot; - - // This is the first $ref to point to this value, so dereference the value. - // Any other $refs that point to the same value will point to this $ref instead - entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value); - - if (entry.circular) { - // This $ref points to itself - entry.$ref.$ref = entry.pathFromRoot; - } - } - - debug(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]'); -}); -} - -/** -* TODO -*/ -function findInInventory (inventory, $refParent, $refKey) { -for (var i = 0; i < inventory.length; i++) { - var existingEntry = inventory[i]; - if (existingEntry.parent === $refParent && existingEntry.key === $refKey) { - return existingEntry; - } -} -} - -function removeFromInventory (inventory, entry) { -var index = inventory.indexOf(entry); -inventory.splice(index, 1); -} - -},{"./pointer":11,"./ref":12,"./util/debug":17,"./util/url":19}],2:[function(_dereq_,module,exports){ -'use strict'; - -var $Ref = _dereq_('./ref'), - Pointer = _dereq_('./pointer'), - ono = _dereq_('ono'), - debug = _dereq_('./util/debug'), - url = _dereq_('./util/url'); - -module.exports = dereference; - -/** -* Crawls the JSON schema, finds all JSON references, and dereferences them. -* This method mutates the JSON schema object, replacing JSON references with their resolved value. -* -* @param {$RefParser} parser -* @param {$RefParserOptions} options -*/ -function dereference (parser, options) { -debug('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path); -var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, '#', [], parser.$refs, options); -parser.$refs.circular = dereferenced.circular; -parser.schema = dereferenced.value; -} - -/** -* Recursively crawls the given value, and dereferences any JSON references. -* -* @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. -* @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash -* @param {string} pathFromRoot - The path of `obj` from the schema root -* @param {object[]} parents - An array of the parent objects that have already been dereferenced -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* @returns {{value: object, circular: boolean}} -*/ -function crawl (obj, path, pathFromRoot, parents, $refs, options) { -var dereferenced; -var result = { - value: obj, - circular: false -}; - -if (obj && typeof obj === 'object') { - parents.push(obj); - - if ($Ref.isAllowed$Ref(obj, options)) { - dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options); - result.circular = dereferenced.circular; - result.value = dereferenced.value; - } - else { - Object.keys(obj).forEach(function (key) { - var keyPath = Pointer.join(path, key); - var keyPathFromRoot = Pointer.join(pathFromRoot, key); - var value = obj[key]; - var circular = false; - - if ($Ref.isAllowed$Ref(value, options)) { - dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options); - circular = dereferenced.circular; - obj[key] = dereferenced.value; - } - else { - if (parents.indexOf(value) === -1) { - dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options); - circular = dereferenced.circular; - obj[key] = dereferenced.value; - } - else { - circular = foundCircularReference(keyPath, $refs, options); - } - } - - // Set the "isCircular" flag if this or any other property is circular - result.circular = result.circular || circular; - }); - } - - parents.pop(); -} - -return result; -} - -/** -* Dereferences the given JSON Reference, and then crawls the resulting value. -* -* @param {{$ref: string}} $ref - The JSON Reference to resolve -* @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash -* @param {string} pathFromRoot - The path of `$ref` from the schema root -* @param {object[]} parents - An array of the parent objects that have already been dereferenced -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* @returns {{value: object, circular: boolean}} -*/ -function dereference$Ref ($ref, path, pathFromRoot, parents, $refs, options) { -debug('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path); - -var $refPath = url.resolve(path, $ref.$ref); -var pointer = $refs._resolve($refPath, options); - -// Check for circular references -var directCircular = pointer.circular; -var circular = directCircular || parents.indexOf(pointer.value) !== -1; -circular && foundCircularReference(path, $refs, options); - -// Dereference the JSON reference -var dereferencedValue = $Ref.dereference($ref, pointer.value); - -// Crawl the dereferenced value (unless it's circular) -if (!circular) { - // Determine if the dereferenced value is circular - var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options); - circular = dereferenced.circular; - dereferencedValue = dereferenced.value; -} - -if (circular && !directCircular && options.dereference.circular === 'ignore') { - // The user has chosen to "ignore" circular references, so don't change the value - dereferencedValue = $ref; -} - -if (directCircular) { - // The pointer is a DIRECT circular reference (i.e. it references itself). - // So replace the $ref path with the absolute path from the JSON Schema root - dereferencedValue.$ref = pathFromRoot; -} - -return { - circular: circular, - value: dereferencedValue -}; -} - -/** -* Called when a circular reference is found. -* It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false. -* -* @param {string} keyPath - The JSON Reference path of the circular reference -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* @returns {boolean} - always returns true, to indicate that a circular reference was found -*/ -function foundCircularReference (keyPath, $refs, options) { -$refs.circular = true; -if (!options.dereference.circular) { - throw ono.reference('Circular $ref pointer found at %s', keyPath); -} -return true; -} - -},{"./pointer":11,"./ref":12,"./util/debug":17,"./util/url":19,"ono":67}],3:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -var Options = _dereq_('./options'), - $Refs = _dereq_('./refs'), - parse = _dereq_('./parse'), - normalizeArgs = _dereq_('./normalize-args'), - resolveExternal = _dereq_('./resolve-external'), - bundle = _dereq_('./bundle'), - dereference = _dereq_('./dereference'), - url = _dereq_('./util/url'), - maybe = _dereq_('call-me-maybe'), - ono = _dereq_('ono'); - -module.exports = $RefParser; -module.exports.YAML = _dereq_('./util/yaml'); - -/** -* This class parses a JSON schema, builds a map of its JSON references and their resolved values, -* and provides methods for traversing, manipulating, and dereferencing those references. -* -* @constructor -*/ -function $RefParser () { -/** - * The parsed (and possibly dereferenced) JSON schema object - * - * @type {object} - * @readonly - */ -this.schema = null; - -/** - * The resolved JSON references - * - * @type {$Refs} - * @readonly - */ -this.$refs = new $Refs(); -} - -/** -* Parses the given JSON schema. -* This method does not resolve any JSON references. -* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed -* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. -* @returns {Promise} - The returned promise resolves with the parsed JSON schema object. -*/ -$RefParser.parse = function (path, schema, options, callback) { -var Class = this; // eslint-disable-line consistent-this -var instance = new Class(); -return instance.parse.apply(instance, arguments); -}; - -/** -* Parses the given JSON schema. -* This method does not resolve any JSON references. -* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed -* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. -* @returns {Promise} - The returned promise resolves with the parsed JSON schema object. -*/ -$RefParser.prototype.parse = function (path, schema, options, callback) { -var args = normalizeArgs(arguments); -var promise; - -if (!args.path && !args.schema) { - var err = ono('Expected a file path, URL, or object. Got %s', args.path || args.schema); - return maybe(args.callback, Promise.reject(err)); -} - -// Reset everything -this.schema = null; -this.$refs = new $Refs(); - -// If the path is a filesystem path, then convert it to a URL. -// NOTE: According to the JSON Reference spec, these should already be URLs, -// but, in practice, many people use local filesystem paths instead. -// So we're being generous here and doing the conversion automatically. -// This is not intended to be a 100% bulletproof solution. -// If it doesn't work for your use-case, then use a URL instead. -var pathType = 'http'; -if (url.isFileSystemPath(args.path)) { - args.path = url.fromFileSystemPath(args.path); - pathType = 'file'; -} - -// Resolve the absolute path of the schema -args.path = url.resolve(url.cwd(), args.path); - -if (args.schema && typeof args.schema === 'object') { - // A schema object was passed-in. - // So immediately add a new $Ref with the schema object as its value - var $ref = this.$refs._add(args.path); - $ref.value = args.schema; - $ref.pathType = pathType; - promise = Promise.resolve(args.schema); -} -else { - // Parse the schema file/url - promise = parse(args.path, this.$refs, args.options); -} - -var me = this; -return promise - .then(function (result) { - if (!result || typeof result !== 'object' || Buffer.isBuffer(result)) { - throw ono.syntax('"%s" is not a valid JSON Schema', me.$refs._root$Ref.path || result); - } - else { - me.schema = result; - return maybe(args.callback, Promise.resolve(me.schema)); - } - }) - .catch(function (e) { - return maybe(args.callback, Promise.reject(e)); - }); -}; - -/** -* Parses the given JSON schema and resolves any JSON references, including references in -* externally-referenced files. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved -* @param {function} [callback] -* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references -* -* @returns {Promise} -* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references -*/ -$RefParser.resolve = function (path, schema, options, callback) { -var Class = this; // eslint-disable-line consistent-this -var instance = new Class(); -return instance.resolve.apply(instance, arguments); -}; - -/** -* Parses the given JSON schema and resolves any JSON references, including references in -* externally-referenced files. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved -* @param {function} [callback] -* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references -* -* @returns {Promise} -* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references -*/ -$RefParser.prototype.resolve = function (path, schema, options, callback) { -var me = this; -var args = normalizeArgs(arguments); - -return this.parse(args.path, args.schema, args.options) - .then(function () { - return resolveExternal(me, args.options); - }) - .then(function () { - return maybe(args.callback, Promise.resolve(me.$refs)); - }) - .catch(function (err) { - return maybe(args.callback, Promise.reject(err)); - }); -}; - -/** -* Parses the given JSON schema, resolves any JSON references, and bundles all external references -* into the main JSON schema. This produces a JSON schema that only has *internal* references, -* not any *external* references. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced -* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object -* @returns {Promise} - The returned promise resolves with the bundled JSON schema object. -*/ -$RefParser.bundle = function (path, schema, options, callback) { -var Class = this; // eslint-disable-line consistent-this -var instance = new Class(); -return instance.bundle.apply(instance, arguments); -}; - -/** -* Parses the given JSON schema, resolves any JSON references, and bundles all external references -* into the main JSON schema. This produces a JSON schema that only has *internal* references, -* not any *external* references. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced -* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object -* @returns {Promise} - The returned promise resolves with the bundled JSON schema object. -*/ -$RefParser.prototype.bundle = function (path, schema, options, callback) { -var me = this; -var args = normalizeArgs(arguments); - -return this.resolve(args.path, args.schema, args.options) - .then(function () { - bundle(me, args.options); - return maybe(args.callback, Promise.resolve(me.schema)); - }) - .catch(function (err) { - return maybe(args.callback, Promise.reject(err)); - }); -}; - -/** -* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. -* That is, all JSON references are replaced with their resolved values. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced -* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object -* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. -*/ -$RefParser.dereference = function (path, schema, options, callback) { -var Class = this; // eslint-disable-line consistent-this -var instance = new Class(); -return instance.dereference.apply(instance, arguments); -}; - -/** -* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. -* That is, all JSON references are replaced with their resolved values. -* -* @param {string} [path] - The file path or URL of the JSON schema -* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. -* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced -* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object -* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. -*/ -$RefParser.prototype.dereference = function (path, schema, options, callback) { -var me = this; -var args = normalizeArgs(arguments); - -return this.resolve(args.path, args.schema, args.options) - .then(function () { - dereference(me, args.options); - return maybe(args.callback, Promise.resolve(me.schema)); - }) - .catch(function (err) { - return maybe(args.callback, Promise.reject(err)); - }); -}; - -}).call(this,{"isBuffer":_dereq_("../node_modules/is-buffer/index.js")}) - -},{"../node_modules/is-buffer/index.js":34,"./bundle":1,"./dereference":2,"./normalize-args":4,"./options":5,"./parse":6,"./refs":13,"./resolve-external":14,"./util/url":19,"./util/yaml":20,"call-me-maybe":25,"ono":67}],4:[function(_dereq_,module,exports){ -'use strict'; - -var Options = _dereq_('./options'); - -module.exports = normalizeArgs; - -/** -* Normalizes the given arguments, accounting for optional args. -* -* @param {Arguments} args -* @returns {object} -*/ -function normalizeArgs (args) { -var path, schema, options, callback; -args = Array.prototype.slice.call(args); - -if (typeof args[args.length - 1] === 'function') { - // The last parameter is a callback function - callback = args.pop(); -} - -if (typeof args[0] === 'string') { - // The first parameter is the path - path = args[0]; - if (typeof args[2] === 'object') { - // The second parameter is the schema, and the third parameter is the options - schema = args[1]; - options = args[2]; - } - else { - // The second parameter is the options - schema = undefined; - options = args[1]; - } -} -else { - // The first parameter is the schema - path = ''; - schema = args[0]; - options = args[1]; -} - -if (!(options instanceof Options)) { - options = new Options(options); -} - -return { - path: path, - schema: schema, - options: options, - callback: callback -}; -} - -},{"./options":5}],5:[function(_dereq_,module,exports){ -/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */ -'use strict'; - -var jsonParser = _dereq_('./parsers/json'), - yamlParser = _dereq_('./parsers/yaml'), - textParser = _dereq_('./parsers/text'), - binaryParser = _dereq_('./parsers/binary'), - fileResolver = _dereq_('./resolvers/file'), - httpResolver = _dereq_('./resolvers/http'); - -module.exports = $RefParserOptions; - -/** -* Options that determine how JSON schemas are parsed, resolved, and dereferenced. -* -* @param {object|$RefParserOptions} [options] - Overridden options -* @constructor -*/ -function $RefParserOptions (options) { -merge(this, $RefParserOptions.defaults); -merge(this, options); -} - -$RefParserOptions.defaults = { -/** - * Determines how different types of files will be parsed. - * - * You can add additional parsers of your own, replace an existing one with - * your own implemenation, or disable any parser by setting it to false. - */ -parse: { - json: jsonParser, - yaml: yamlParser, - text: textParser, - binary: binaryParser, -}, - -/** - * Determines how JSON References will be resolved. - * - * You can add additional resolvers of your own, replace an existing one with - * your own implemenation, or disable any resolver by setting it to false. - */ -resolve: { - file: fileResolver, - http: httpResolver, - - /** - * Determines whether external $ref pointers will be resolved. - * If this option is disabled, then none of above resolvers will be called. - * Instead, external $ref pointers will simply be ignored. - * - * @type {boolean} - */ - external: true, -}, - -/** - * Determines the types of JSON references that are allowed. - */ -dereference: { - /** - * Dereference circular (recursive) JSON references? - * If false, then a {@link ReferenceError} will be thrown if a circular reference is found. - * If "ignore", then circular references will not be dereferenced. - * - * @type {boolean|string} - */ - circular: true -}, -}; - -/** -* Merges the properties of the source object into the target object. -* -* @param {object} target - The object that we're populating -* @param {?object} source - The options that are being merged -* @returns {object} -*/ -function merge (target, source) { -if (isMergeable(source)) { - var keys = Object.keys(source); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var sourceSetting = source[key]; - var targetSetting = target[key]; - - if (isMergeable(sourceSetting)) { - // It's a nested object, so merge it recursively - target[key] = merge(targetSetting || {}, sourceSetting); - } - else if (sourceSetting !== undefined) { - // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value. - target[key] = sourceSetting; - } - } -} -return target; -} - -/** -* Determines whether the given value can be merged, -* or if it is a scalar value that should just override the target value. -* -* @param {*} val -* @returns {Boolean} -*/ -function isMergeable (val) { -return val && - (typeof val === 'object') && - !Array.isArray(val) && - !(val instanceof RegExp) && - !(val instanceof Date); -} - -},{"./parsers/binary":7,"./parsers/json":8,"./parsers/text":9,"./parsers/yaml":10,"./resolvers/file":15,"./resolvers/http":16}],6:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -var ono = _dereq_('ono'), - debug = _dereq_('./util/debug'), - url = _dereq_('./util/url'), - plugins = _dereq_('./util/plugins'); - -module.exports = parse; - -/** -* Reads and parses the specified file path or URL. -* -* @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* -* @returns {Promise} -* The promise resolves with the parsed file contents, NOT the raw (Buffer) contents. -*/ -function parse (path, $refs, options) { -try { - // Remove the URL fragment, if any - path = url.stripHash(path); - - // Add a new $Ref for this file, even though we don't have the value yet. - // This ensures that we don't simultaneously read & parse the same file multiple times - var $ref = $refs._add(path); - - // This "file object" will be passed to all resolvers and parsers. - var file = { - url: path, - extension: url.getExtension(path), - }; - - // Read the file and then parse the data - return readFile(file, options) - .then(function (resolver) { - $ref.pathType = resolver.plugin.name; - file.data = resolver.result; - return parseFile(file, options); - }) - .then(function (parser) { - $ref.value = parser.result; - return parser.result; - }); -} -catch (e) { - return Promise.reject(e); -} -} - -/** -* Reads the given file, using the configured resolver plugins -* -* @param {object} file - An object containing information about the referenced file -* @param {string} file.url - The full URL of the referenced file -* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) -* @param {$RefParserOptions} options -* -* @returns {Promise} -* The promise resolves with the raw file contents and the resolver that was used. -*/ -function readFile (file, options) { -return new Promise(function (resolve, reject) { - debug('Reading %s', file.url); - - // Find the resolvers that can read this file - var resolvers = plugins.all(options.resolve); - resolvers = plugins.filter(resolvers, 'canRead', file); - - // Run the resolvers, in order, until one of them succeeds - plugins.sort(resolvers); - plugins.run(resolvers, 'read', file) - .then(resolve, onError); - - function onError (err) { - // Throw the original error, if it's one of our own (user-friendly) errors. - // Otherwise, throw a generic, friendly error. - if (err && !(err instanceof SyntaxError)) { - reject(err); - } - else { - reject(ono.syntax('Unable to resolve $ref pointer "%s"', file.url)); - } - } -}); -} - -/** -* Parses the given file's contents, using the configured parser plugins. -* -* @param {object} file - An object containing information about the referenced file -* @param {string} file.url - The full URL of the referenced file -* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) -* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver -* @param {$RefParserOptions} options -* -* @returns {Promise} -* The promise resolves with the parsed file contents and the parser that was used. -*/ -function parseFile (file, options) { -return new Promise(function (resolve, reject) { - debug('Parsing %s', file.url); - - // Find the parsers that can read this file type. - // If none of the parsers are an exact match for this file, then we'll try ALL of them. - // This handles situations where the file IS a supported type, just with an unknown extension. - var allParsers = plugins.all(options.parse); - var filteredParsers = plugins.filter(allParsers, 'canParse', file); - var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers; - - // Run the parsers, in order, until one of them succeeds - plugins.sort(parsers); - plugins.run(parsers, 'parse', file) - .then(onParsed, onError); - - function onParsed (parser) { - if (!parser.plugin.allowEmpty && isEmpty(parser.result)) { - reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name)); - } - else { - resolve(parser); - } - } - - function onError (err) { - if (err) { - err = err instanceof Error ? err : new Error(err); - reject(ono.syntax(err, 'Error parsing %s', file.url)); - } - else { - reject(ono.syntax('Unable to parse %s', file.url)); - } - } -}); -} - -/** -* Determines whether the parsed value is "empty". -* -* @param {*} value -* @returns {boolean} -*/ -function isEmpty (value) { -return value === undefined || - (typeof value === 'object' && Object.keys(value).length === 0) || - (typeof value === 'string' && value.trim().length === 0) || - (Buffer.isBuffer(value) && value.length === 0); -} - -}).call(this,{"isBuffer":_dereq_("../node_modules/is-buffer/index.js")}) - -},{"../node_modules/is-buffer/index.js":34,"./util/debug":17,"./util/plugins":18,"./util/url":19,"ono":67}],7:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -var BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i; - -module.exports = { -/** - * The order that this parser will run, in relation to other parsers. - * - * @type {number} - */ -order: 400, - -/** - * Whether to allow "empty" files (zero bytes). - * - * @type {boolean} - */ -allowEmpty: true, - -/** - * Determines whether this parser can parse a given file reference. - * Parsers that return true will be tried, in order, until one successfully parses the file. - * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case - * every parser will be tried. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {boolean} - */ -canParse: function isBinary (file) { - // Use this parser if the file is a Buffer, and has a known binary extension - return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url); -}, - -/** - * Parses the given data as a Buffer (byte array). - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {Promise} - */ -parse: function parseBinary (file) { - if (Buffer.isBuffer(file.data)) { - return file.data; - } - else { - // This will reject if data is anything other than a string or typed array - return new Buffer(file.data); - } -} -}; - -}).call(this,_dereq_("buffer").Buffer) - -},{"buffer":23}],8:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -module.exports = { -/** - * The order that this parser will run, in relation to other parsers. - * - * @type {number} - */ -order: 100, - -/** - * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. - * - * @type {boolean} - */ -allowEmpty: true, - -/** - * Determines whether this parser can parse a given file reference. - * Parsers that match will be tried, in order, until one successfully parses the file. - * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case - * every parser will be tried. - * - * @type {RegExp|string[]|function} - */ -canParse: '.json', - -/** - * Parses the given file as JSON - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {Promise} - */ -parse: function parseJSON (file) { - return new Promise(function (resolve, reject) { - var data = file.data; - if (Buffer.isBuffer(data)) { - data = data.toString(); - } - - if (typeof data === 'string') { - if (data.trim().length === 0) { - resolve(undefined); // This mirrors the YAML behavior - } - else { - resolve(JSON.parse(data)); - } - } - else { - // data is already a JavaScript value (object, array, number, null, NaN, etc.) - resolve(data); - } - }); -} -}; - -}).call(this,{"isBuffer":_dereq_("../../node_modules/is-buffer/index.js")}) - -},{"../../node_modules/is-buffer/index.js":34}],9:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -var TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i; - -module.exports = { -/** - * The order that this parser will run, in relation to other parsers. - * - * @type {number} - */ -order: 300, - -/** - * Whether to allow "empty" files (zero bytes). - * - * @type {boolean} - */ -allowEmpty: true, - -/** - * The encoding that the text is expected to be in. - * - * @type {string} - */ -encoding: 'utf8', - -/** - * Determines whether this parser can parse a given file reference. - * Parsers that return true will be tried, in order, until one successfully parses the file. - * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case - * every parser will be tried. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {boolean} - */ -canParse: function isText (file) { - // Use this parser if the file is a string or Buffer, and has a known text-based extension - return (typeof file.data === 'string' || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url); -}, - -/** - * Parses the given file as text - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {Promise} - */ -parse: function parseText (file) { - if (typeof file.data === 'string') { - return file.data; - } - else if (Buffer.isBuffer(file.data)) { - return file.data.toString(this.encoding); - } - else { - throw new Error('data is not text'); - } -} -}; - -}).call(this,{"isBuffer":_dereq_("../../node_modules/is-buffer/index.js")}) - -},{"../../node_modules/is-buffer/index.js":34}],10:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; - -var YAML = _dereq_('../util/yaml'); - -module.exports = { -/** - * The order that this parser will run, in relation to other parsers. - * - * @type {number} - */ -order: 200, - -/** - * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. - * - * @type {boolean} - */ -allowEmpty: true, - -/** - * Determines whether this parser can parse a given file reference. - * Parsers that match will be tried, in order, until one successfully parses the file. - * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case - * every parser will be tried. - * - * @type {RegExp|string[]|function} - */ -canParse: ['.yaml', '.yml', '.json'], // JSON is valid YAML - -/** - * Parses the given file as YAML - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver - * @returns {Promise} - */ -parse: function parseYAML (file) { - return new Promise(function (resolve, reject) { - var data = file.data; - if (Buffer.isBuffer(data)) { - data = data.toString(); - } - - if (typeof data === 'string') { - resolve(YAML.parse(data)); - } - else { - // data is already a JavaScript value (object, array, number, null, NaN, etc.) - resolve(data); - } - }); -} -}; - -}).call(this,{"isBuffer":_dereq_("../../node_modules/is-buffer/index.js")}) - -},{"../../node_modules/is-buffer/index.js":34,"../util/yaml":20}],11:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = Pointer; - -var $Ref = _dereq_('./ref'), - url = _dereq_('./util/url'), - ono = _dereq_('ono'), - slashes = /\//g, - tildes = /~/g, - escapedSlash = /~1/g, - escapedTilde = /~0/g; - -/** -* This class represents a single JSON pointer and its resolved value. -* -* @param {$Ref} $ref -* @param {string} path -* @param {string} [friendlyPath] - The original user-specified path (used for error messages) -* @constructor -*/ -function Pointer ($ref, path, friendlyPath) { -/** - * The {@link $Ref} object that contains this {@link Pointer} object. - * @type {$Ref} - */ -this.$ref = $ref; - -/** - * The file path or URL, containing the JSON pointer in the hash. - * This path is relative to the path of the main JSON schema file. - * @type {string} - */ -this.path = path; - -/** - * The original path or URL, used for error messages. - * @type {string} - */ -this.originalPath = friendlyPath || path; - -/** - * The value of the JSON pointer. - * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). - * @type {?*} - */ -this.value = undefined; - -/** - * Indicates whether the pointer references itself. - * @type {boolean} - */ -this.circular = false; - -/** - * The number of indirect references that were traversed to resolve the value. - * Resolving a single pointer may _dereq_ resolving multiple $Refs. - * @type {number} - */ -this.indirections = 0; -} - -/** -* Resolves the value of a nested property within the given object. -* -* @param {*} obj - The object that will be crawled -* @param {$RefParserOptions} options -* -* @returns {Pointer} -* Returns a JSON pointer whose {@link Pointer#value} is the resolved value. -* If resolving this value required resolving other JSON references, then -* the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path -* of the resolved value. -*/ -Pointer.prototype.resolve = function (obj, options) { -var tokens = Pointer.parse(this.path); - -// Crawl the object, one token at a time -this.value = obj; -for (var i = 0; i < tokens.length; i++) { - if (resolveIf$Ref(this, options)) { - // The $ref path has changed, so append the remaining tokens to the path - this.path = Pointer.join(this.path, tokens.slice(i)); - } - - var token = tokens[i]; - if (this.value[token] === undefined) { - throw ono.syntax('Error resolving $ref pointer "%s". \nToken "%s" does not exist.', this.originalPath, token); - } - else { - this.value = this.value[token]; - } -} - -// Resolve the final value -resolveIf$Ref(this, options); -return this; -}; - -/** -* Sets the value of a nested property within the given object. -* -* @param {*} obj - The object that will be crawled -* @param {*} value - the value to assign -* @param {$RefParserOptions} options -* -* @returns {*} -* Returns the modified object, or an entirely new object if the entire object is overwritten. -*/ -Pointer.prototype.set = function (obj, value, options) { -var tokens = Pointer.parse(this.path); -var token; - -if (tokens.length === 0) { - // There are no tokens, replace the entire object with the new value - this.value = value; - return value; -} - -// Crawl the object, one token at a time -this.value = obj; -for (var i = 0; i < tokens.length - 1; i++) { - resolveIf$Ref(this, options); - - token = tokens[i]; - if (this.value && this.value[token] !== undefined) { - // The token exists - this.value = this.value[token]; - } - else { - // The token doesn't exist, so create it - this.value = setValue(this, token, {}); - } -} - -// Set the value of the final token -resolveIf$Ref(this, options); -token = tokens[tokens.length - 1]; -setValue(this, token, value); - -// Return the updated object -return obj; -}; - -/** -* Parses a JSON pointer (or a path containing a JSON pointer in the hash) -* and returns an array of the pointer's tokens. -* (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"]) -* -* The pointer is parsed according to RFC 6901 -* {@link https://tools.ietf.org/html/rfc6901#section-3} -* -* @param {string} path -* @returns {string[]} -*/ -Pointer.parse = function (path) { -// Get the JSON pointer from the path's hash -var pointer = url.getHash(path).substr(1); - -// If there's no pointer, then there are no tokens, -// so return an empty array -if (!pointer) { - return []; -} - -// Split into an array -pointer = pointer.split('/'); - -// Decode each part, according to RFC 6901 -for (var i = 0; i < pointer.length; i++) { - pointer[i] = decodeURI(pointer[i].replace(escapedSlash, '/').replace(escapedTilde, '~')); -} - -if (pointer[0] !== '') { - throw ono.syntax('Invalid $ref pointer "%s". Pointers must begin with "#/"', pointer); -} - -return pointer.slice(1); -}; - -/** -* Creates a JSON pointer path, by joining one or more tokens to a base path. -* -* @param {string} base - The base path (e.g. "schema.json#/definitions/person") -* @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"]) -* @returns {string} -*/ -Pointer.join = function (base, tokens) { -// Ensure that the base path contains a hash -if (base.indexOf('#') === -1) { - base += '#'; -} - -// Append each token to the base path -tokens = Array.isArray(tokens) ? tokens : [tokens]; -for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - // Encode the token, according to RFC 6901 - base += '/' + encodeURI(token.replace(tildes, '~0').replace(slashes, '~1')); -} - -return base; -}; - -/** -* If the given pointer's {@link Pointer#value} is a JSON reference, -* then the reference is resolved and {@link Pointer#value} is replaced with the resolved value. -* In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the -* resolution path of the new value. -* -* @param {Pointer} pointer -* @param {$RefParserOptions} options -* @returns {boolean} - Returns `true` if the resolution path changed -*/ -function resolveIf$Ref (pointer, options) { -// Is the value a JSON reference? (and allowed?) - -if ($Ref.isAllowed$Ref(pointer.value, options)) { - var $refPath = url.resolve(pointer.path, pointer.value.$ref); - - if ($refPath === pointer.path) { - // The value is a reference to itself, so there's nothing to do. - pointer.circular = true; - } - else { - var resolved = pointer.$ref.$refs._resolve($refPath, options); - pointer.indirections += resolved.indirections + 1; - - if ($Ref.isExtended$Ref(pointer.value)) { - // This JSON reference "extends" the resolved value, rather than simply pointing to it. - // So the resolved path does NOT change. Just the value does. - pointer.value = $Ref.dereference(pointer.value, resolved.value); - return false; - } - else { - // Resolve the reference - pointer.$ref = resolved.$ref; - pointer.path = resolved.path; - pointer.value = resolved.value; - } - - return true; - } -} -} - -/** -* Sets the specified token value of the {@link Pointer#value}. -* -* The token is evaluated according to RFC 6901. -* {@link https://tools.ietf.org/html/rfc6901#section-4} -* -* @param {Pointer} pointer - The JSON Pointer whose value will be modified -* @param {string} token - A JSON Pointer token that indicates how to modify `obj` -* @param {*} value - The value to assign -* @returns {*} - Returns the assigned value -*/ -function setValue (pointer, token, value) { -if (pointer.value && typeof pointer.value === 'object') { - if (token === '-' && Array.isArray(pointer.value)) { - pointer.value.push(value); - } - else { - pointer.value[token] = value; - } -} -else { - throw ono.syntax('Error assigning $ref pointer "%s". \nCannot set "%s" of a non-object.', pointer.path, token); -} -return value; -} - -},{"./ref":12,"./util/url":19,"ono":67}],12:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = $Ref; - -var Pointer = _dereq_('./pointer'); - -/** -* This class represents a single JSON reference and its resolved value. -* -* @constructor -*/ -function $Ref () { -/** - * The file path or URL of the referenced file. - * This path is relative to the path of the main JSON schema file. - * - * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file. - * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get - * specific JSON pointers within the file. - * - * @type {string} - */ -this.path = undefined; - -/** - * The resolved value of the JSON reference. - * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). - * @type {?*} - */ -this.value = undefined; - -/** - * The {@link $Refs} object that contains this {@link $Ref} object. - * @type {$Refs} - */ -this.$refs = undefined; - -/** - * Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.) - * @type {?string} - */ -this.pathType = undefined; -} - -/** -* Determines whether the given JSON reference exists within this {@link $Ref#value}. -* -* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash -* @param {$RefParserOptions} options -* @returns {boolean} -*/ -$Ref.prototype.exists = function (path, options) { -try { - this.resolve(path, options); - return true; -} -catch (e) { - return false; -} -}; - -/** -* Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value. -* -* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash -* @param {$RefParserOptions} options -* @returns {*} - Returns the resolved value -*/ -$Ref.prototype.get = function (path, options) { -return this.resolve(path, options).value; -}; - -/** -* Resolves the given JSON reference within this {@link $Ref#value}. -* -* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash -* @param {$RefParserOptions} options -* @param {string} [friendlyPath] - The original user-specified path (used for error messages) -* @returns {Pointer} -*/ -$Ref.prototype.resolve = function (path, options, friendlyPath) { -var pointer = new Pointer(this, path, friendlyPath); -return pointer.resolve(this.value, options); -}; - -/** -* Sets the value of a nested property within this {@link $Ref#value}. -* If the property, or any of its parents don't exist, they will be created. -* -* @param {string} path - The full path of the property to set, optionally with a JSON pointer in the hash -* @param {*} value - The value to assign -*/ -$Ref.prototype.set = function (path, value) { -var pointer = new Pointer(this, path); -this.value = pointer.set(this.value, value); -}; - -/** -* Determines whether the given value is a JSON reference. -* -* @param {*} value - The value to inspect -* @returns {boolean} -*/ -$Ref.is$Ref = function (value) { -return value && typeof value === 'object' && typeof value.$ref === 'string' && value.$ref.length > 0; -}; - -/** -* Determines whether the given value is an external JSON reference. -* -* @param {*} value - The value to inspect -* @returns {boolean} -*/ -$Ref.isExternal$Ref = function (value) { -return $Ref.is$Ref(value) && value.$ref[0] !== '#'; -}; - -/** -* Determines whether the given value is a JSON reference, and whether it is allowed by the options. -* For example, if it references an external file, then options.resolve.external must be true. -* -* @param {*} value - The value to inspect -* @param {$RefParserOptions} options -* @returns {boolean} -*/ -$Ref.isAllowed$Ref = function (value, options) { -if ($Ref.is$Ref(value)) { - if (value.$ref.substr(0, 2) === '#/' || value.$ref === '#') { - // It's a JSON Pointer reference, which is always allowed - return true; - } - else if (value.$ref[0] !== '#' && (!options || options.resolve.external)) { - // It's an external reference, which is allowed by the options - return true; - } -} -}; - -/** -* Determines whether the given value is a JSON reference that "extends" its resolved value. -* That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to -* an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved -* value, plus the extra properties. -* -* @example: -* { -* person: { -* properties: { -* firstName: { type: string } -* lastName: { type: string } -* } -* } -* employee: { -* properties: { -* $ref: #/person/properties -* salary: { type: number } -* } -* } -* } -* -* In this example, "employee" is an extended $ref, since it extends "person" with an additional -* property (salary). The result is a NEW value that looks like this: -* -* { -* properties: { -* firstName: { type: string } -* lastName: { type: string } -* salary: { type: number } -* } -* } -* -* @param {*} value - The value to inspect -* @returns {boolean} -*/ -$Ref.isExtended$Ref = function (value) { -return $Ref.is$Ref(value) && Object.keys(value).length > 1; -}; - -/** -* Returns the resolved value of a JSON Reference. -* If necessary, the resolved value is merged with the JSON Reference to create a new object -* -* @example: -* { -* person: { -* properties: { -* firstName: { type: string } -* lastName: { type: string } -* } -* } -* employee: { -* properties: { -* $ref: #/person/properties -* salary: { type: number } -* } -* } -* } -* -* When "person" and "employee" are merged, you end up with the following object: -* -* { -* properties: { -* firstName: { type: string } -* lastName: { type: string } -* salary: { type: number } -* } -* } -* -* @param {object} $ref - The JSON reference object (the one with the "$ref" property) -* @param {*} resolvedValue - The resolved value, which can be any type -* @returns {*} - Returns the dereferenced value -*/ -$Ref.dereference = function ($ref, resolvedValue) { -if (resolvedValue && typeof resolvedValue === 'object' && $Ref.isExtended$Ref($ref)) { - var merged = {}; - Object.keys($ref).forEach(function (key) { - if (key !== '$ref') { - merged[key] = $ref[key]; - } - }); - Object.keys(resolvedValue).forEach(function (key) { - if (!(key in merged)) { - merged[key] = resolvedValue[key]; - } - }); - return merged; -} -else { - // Completely replace the original reference with the resolved value - return resolvedValue; -} -}; - -},{"./pointer":11}],13:[function(_dereq_,module,exports){ -'use strict'; - -var ono = _dereq_('ono'), - $Ref = _dereq_('./ref'), - url = _dereq_('./util/url'); - -module.exports = $Refs; - -/** -* This class is a map of JSON references and their resolved values. -*/ -function $Refs () { -/** - * Indicates whether the schema contains any circular references. - * - * @type {boolean} - */ -this.circular = false; - -/** - * A map of paths/urls to {@link $Ref} objects - * - * @type {object} - * @protected - */ -this._$refs = {}; - -/** - * The {@link $Ref} object that is the root of the JSON schema. - * - * @type {$Ref} - * @protected - */ -this._root$Ref = null; -} - -/** -* Returns the paths of all the files/URLs that are referenced by the JSON schema, -* including the schema itself. -* -* @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) -* @returns {string[]} -*/ -$Refs.prototype.paths = function (types) { -var paths = getPaths(this._$refs, arguments); -return paths.map(function (path) { - return path.decoded; -}); -}; - -/** -* Returns the map of JSON references and their resolved values. -* -* @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.) -* @returns {object} -*/ -$Refs.prototype.values = function (types) { -var $refs = this._$refs; -var paths = getPaths($refs, arguments); -return paths.reduce(function (obj, path) { - obj[path.decoded] = $refs[path.encoded].value; - return obj; -}, {}); -}; - -/** -* Returns a POJO (plain old JavaScript object) for serialization as JSON. -* -* @returns {object} -*/ -$Refs.prototype.toJSON = $Refs.prototype.values; - -/** -* Determines whether the given JSON reference exists. -* -* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash -* @param {$RefParserOptions} [options] -* @returns {boolean} -*/ -$Refs.prototype.exists = function (path, options) { -try { - this._resolve(path, options); - return true; -} -catch (e) { - return false; -} -}; - -/** -* Resolves the given JSON reference and returns the resolved value. -* -* @param {string} path - The path being resolved, with a JSON pointer in the hash -* @param {$RefParserOptions} [options] -* @returns {*} - Returns the resolved value -*/ -$Refs.prototype.get = function (path, options) { -return this._resolve(path, options).value; -}; - -/** -* Sets the value of a nested property within this {@link $Ref#value}. -* If the property, or any of its parents don't exist, they will be created. -* -* @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash -* @param {*} value - The value to assign -*/ -$Refs.prototype.set = function (path, value) { -var absPath = url.resolve(this._root$Ref.path, path); -var withoutHash = url.stripHash(absPath); -var $ref = this._$refs[withoutHash]; - -if (!$ref) { - throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash); -} - -$ref.set(absPath, value); -}; - -/** -* Creates a new {@link $Ref} object and adds it to this {@link $Refs} object. -* -* @param {string} path - The file path or URL of the referenced file -*/ -$Refs.prototype._add = function (path) { -var withoutHash = url.stripHash(path); - -var $ref = new $Ref(); -$ref.path = withoutHash; -$ref.$refs = this; - -this._$refs[withoutHash] = $ref; -this._root$Ref = this._root$Ref || $ref; - -return $ref; -}; - -/** -* Resolves the given JSON reference. -* -* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash -* @param {$RefParserOptions} [options] -* @returns {Pointer} -* @protected -*/ -$Refs.prototype._resolve = function (path, options) { -var absPath = url.resolve(this._root$Ref.path, path); -var withoutHash = url.stripHash(absPath); -var $ref = this._$refs[withoutHash]; - -if (!$ref) { - throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash); -} - -return $ref.resolve(absPath, options, path); -}; - -/** -* Returns the specified {@link $Ref} object, or undefined. -* -* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash -* @returns {$Ref|undefined} -* @protected -*/ -$Refs.prototype._get$Ref = function (path) { -path = url.resolve(this._root$Ref.path, path); -var withoutHash = url.stripHash(path); -return this._$refs[withoutHash]; -}; - -/** -* Returns the encoded and decoded paths keys of the given object. -* -* @param {object} $refs - The object whose keys are URL-encoded paths -* @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) -* @returns {object[]} -*/ -function getPaths ($refs, types) { -var paths = Object.keys($refs); - -// Filter the paths by type -types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); -if (types.length > 0 && types[0]) { - paths = paths.filter(function (key) { - return types.indexOf($refs[key].pathType) !== -1; - }); -} - -// Decode local filesystem paths -return paths.map(function (path) { - return { - encoded: path, - decoded: $refs[path].pathType === 'file' ? url.toFileSystemPath(path, true) : path - }; -}); -} - -},{"./ref":12,"./util/url":19,"ono":67}],14:[function(_dereq_,module,exports){ -'use strict'; - -var $Ref = _dereq_('./ref'), - Pointer = _dereq_('./pointer'), - parse = _dereq_('./parse'), - debug = _dereq_('./util/debug'), - url = _dereq_('./util/url'); - -module.exports = resolveExternal; - -/** -* Crawls the JSON schema, finds all external JSON references, and resolves their values. -* This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}. -* -* NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing. -* -* @param {$RefParser} parser -* @param {$RefParserOptions} options -* -* @returns {Promise} -* The promise resolves once all JSON references in the schema have been resolved, -* including nested references that are contained in externally-referenced files. -*/ -function resolveExternal (parser, options) { -if (!options.resolve.external) { - // Nothing to resolve, so exit early - return Promise.resolve(); -} - -try { - debug('Resolving $ref pointers in %s', parser.$refs._root$Ref.path); - var promises = crawl(parser.schema, parser.$refs._root$Ref.path + '#', parser.$refs, options); - return Promise.all(promises); -} -catch (e) { - return Promise.reject(e); -} -} - -/** -* Recursively crawls the given value, and resolves any external JSON references. -* -* @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. -* @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* -* @returns {Promise[]} -* Returns an array of promises. There will be one promise for each JSON reference in `obj`. -* If `obj` does not contain any JSON references, then the array will be empty. -* If any of the JSON references point to files that contain additional JSON references, -* then the corresponding promise will internally reference an array of promises. -*/ -function crawl (obj, path, $refs, options) { -var promises = []; - -if (obj && typeof obj === 'object') { - if ($Ref.isExternal$Ref(obj)) { - promises.push(resolve$Ref(obj, path, $refs, options)); - } - else { - Object.keys(obj).forEach(function (key) { - var keyPath = Pointer.join(path, key); - var value = obj[key]; - - if ($Ref.isExternal$Ref(value)) { - promises.push(resolve$Ref(value, keyPath, $refs, options)); - } - else { - promises = promises.concat(crawl(value, keyPath, $refs, options)); - } - }); - } -} - -return promises; -} - -/** -* Resolves the given JSON Reference, and then crawls the resulting value. -* -* @param {{$ref: string}} $ref - The JSON Reference to resolve -* @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash -* @param {$Refs} $refs -* @param {$RefParserOptions} options -* -* @returns {Promise} -* The promise resolves once all JSON references in the object have been resolved, -* including nested references that are contained in externally-referenced files. -*/ -function resolve$Ref ($ref, path, $refs, options) { -debug('Resolving $ref pointer "%s" at %s', $ref.$ref, path); - -var resolvedPath = url.resolve(path, $ref.$ref); -var withoutHash = url.stripHash(resolvedPath); - -// Do we already have this $ref? -$ref = $refs._$refs[withoutHash]; -if ($ref) { - // We've already parsed this $ref, so use the existing value - return Promise.resolve($ref.value); -} - -// Parse the $referenced file/url -return parse(resolvedPath, $refs, options) - .then(function (result) { - // Crawl the parsed value - debug('Resolving $ref pointers in %s', withoutHash); - var promises = crawl(result, withoutHash + '#', $refs, options); - return Promise.all(promises); - }); -} - -},{"./parse":6,"./pointer":11,"./ref":12,"./util/debug":17,"./util/url":19}],15:[function(_dereq_,module,exports){ -'use strict'; -var fs = _dereq_('fs'), - ono = _dereq_('ono'), - url = _dereq_('../util/url'), - debug = _dereq_('../util/debug'); - -module.exports = { -/** - * The order that this resolver will run, in relation to other resolvers. - * - * @type {number} - */ -order: 100, - -/** - * Determines whether this resolver can read a given file reference. - * Resolvers that return true will be tried, in order, until one successfully resolves the file. - * Resolvers that return false will not be given a chance to resolve the file. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @returns {boolean} - */ -canRead: function isFile (file) { - return url.isFileSystemPath(file.url); -}, - -/** - * Reads the given file and returns its raw contents as a Buffer. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @returns {Promise} - */ -read: function readFile (file) { - return new Promise(function (resolve, reject) { - var path; - try { - path = url.toFileSystemPath(file.url); - } - catch (err) { - reject(ono.uri(err, 'Malformed URI: %s', file.url)); - } - - debug('Opening file: %s', path); - - try { - fs.readFile(path, function (err, data) { - if (err) { - reject(ono(err, 'Error opening file "%s"', path)); - } - else { - resolve(data); - } - }); - } - catch (err) { - reject(ono(err, 'Error opening file "%s"', path)); - } - }); -} -}; - -},{"../util/debug":17,"../util/url":19,"fs":22,"ono":67}],16:[function(_dereq_,module,exports){ -(function (process,Buffer){ -'use strict'; - -var http = _dereq_('http'), - https = _dereq_('https'), - ono = _dereq_('ono'), - url = _dereq_('../util/url'), - debug = _dereq_('../util/debug'); - -module.exports = { -/** - * The order that this resolver will run, in relation to other resolvers. - * - * @type {number} - */ -order: 200, - -/** - * HTTP headers to send when downloading files. - * - * @example: - * { - * "User-Agent": "JSON Schema $Ref Parser", - * Accept: "application/json" - * } - * - * @type {object} - */ -headers: null, - -/** - * HTTP request timeout (in milliseconds). - * - * @type {number} - */ -timeout: 5000, // 5 seconds - -/** - * The maximum number of HTTP redirects to follow. - * To disable automatic following of redirects, set this to zero. - * - * @type {number} - */ -redirects: 5, - -/** - * The `withCredentials` option of XMLHttpRequest. - * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication - * - * @type {boolean} - */ -withCredentials: false, - -/** - * Determines whether this resolver can read a given file reference. - * Resolvers that return true will be tried in order, until one successfully resolves the file. - * Resolvers that return false will not be given a chance to resolve the file. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @returns {boolean} - */ -canRead: function isHttp (file) { - return url.isHttp(file.url); -}, - -/** - * Reads the given URL and returns its raw contents as a Buffer. - * - * @param {object} file - An object containing information about the referenced file - * @param {string} file.url - The full URL of the referenced file - * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) - * @returns {Promise} - */ -read: function readHttp (file) { - var u = url.parse(file.url); - - if (process.browser && !u.protocol) { - // Use the protocol of the current page - u.protocol = url.parse(location.href).protocol; - } - - return download(u, this); -} -}; - -/** -* Downloads the given file. -* -* @param {Url|string} u - The url to download (can be a parsed {@link Url} object) -* @param {object} httpOptions - The `options.resolve.http` object -* @param {number} [redirects] - The redirect URLs that have already been followed -* -* @returns {Promise} -* The promise resolves with the raw downloaded data, or rejects if there is an HTTP error. -*/ -function download (u, httpOptions, redirects) { -return new Promise(function (resolve, reject) { - u = url.parse(u); - redirects = redirects || []; - redirects.push(u.href); - - get(u, httpOptions) - .then(function (res) { - if (res.statusCode >= 400) { - throw ono({ status: res.statusCode }, 'HTTP ERROR %d', res.statusCode); - } - else if (res.statusCode >= 300) { - if (redirects.length > httpOptions.redirects) { - reject(ono({ status: res.statusCode }, 'Error downloading %s. \nToo many redirects: \n %s', - redirects[0], redirects.join(' \n '))); - } - else if (!res.headers.location) { - throw ono({ status: res.statusCode }, 'HTTP %d redirect with no location header', res.statusCode); - } - else { - debug('HTTP %d redirect %s -> %s', res.statusCode, u.href, res.headers.location); - var redirectTo = url.resolve(u, res.headers.location); - download(redirectTo, httpOptions, redirects).then(resolve, reject); - } - } - else { - resolve(res.body || new Buffer(0)); - } - }) - .catch(function (err) { - reject(ono(err, 'Error downloading', u.href)); - }); -}); -} - -/** -* Sends an HTTP GET request. -* -* @param {Url} u - A parsed {@link Url} object -* @param {object} httpOptions - The `options.resolve.http` object -* -* @returns {Promise} -* The promise resolves with the HTTP Response object. -*/ -function get (u, httpOptions) { -return new Promise(function (resolve, reject) { - debug('GET', u.href); - - var protocol = u.protocol === 'https:' ? https : http; - var req = protocol.get({ - hostname: u.hostname, - port: u.port, - path: u.path, - auth: u.auth, - protocol: u.protocol, - headers: httpOptions.headers || {}, - withCredentials: httpOptions.withCredentials - }); - - if (typeof req.setTimeout === 'function') { - req.setTimeout(httpOptions.timeout); - } - - req.on('timeout', function () { - req.abort(); - }); - - req.on('error', reject); - - req.once('response', function (res) { - res.body = new Buffer(0); - - res.on('data', function (data) { - res.body = Buffer.concat([res.body, new Buffer(data)]); - }); - - res.on('error', reject); - - res.on('end', function () { - resolve(res); - }); - }); -}); -} - -}).call(this,_dereq_('_process'),_dereq_("buffer").Buffer) - -},{"../util/debug":17,"../util/url":19,"_process":69,"buffer":23,"http":84,"https":31,"ono":67}],17:[function(_dereq_,module,exports){ -'use strict'; - -var debug = _dereq_('debug'); - -/** -* Writes messages to stdout. -* Log messages are suppressed by default, but can be enabled by setting the DEBUG variable. -* @type {function} -*/ -module.exports = debug('json-schema-ref-parser'); - -},{"debug":27}],18:[function(_dereq_,module,exports){ -'use strict'; - -var debug = _dereq_('./debug'); - -/** -* Returns the given plugins as an array, rather than an object map. -* All other methods in this module expect an array of plugins rather than an object map. -* -* @param {object} plugins - A map of plugin objects -* @return {object[]} -*/ -exports.all = function (plugins) { -return Object.keys(plugins) - .filter(function (key) { - return typeof plugins[key] === 'object'; - }) - .map(function (key) { - plugins[key].name = key; - return plugins[key]; - }); -}; - -/** -* Filters the given plugins, returning only the ones return `true` for the given method. -* -* @param {object[]} plugins - An array of plugin objects -* @param {string} method - The name of the filter method to invoke for each plugin -* @param {object} file - A file info object, which will be passed to each method -* @return {object[]} -*/ -exports.filter = function (plugins, method, file) { -return plugins - .filter(function (plugin) { - return !!getResult(plugin, method, file); - }); -}; - -/** -* Sorts the given plugins, in place, by their `order` property. -* -* @param {object[]} plugins - An array of plugin objects -* @returns {object[]} -*/ -exports.sort = function (plugins) { -plugins.forEach(function (plugin) { - plugin.order = plugin.order || Number.MAX_SAFE_INTEGER; -}); - -return plugins.sort(function (a, b) { return a.order - b.order; }); -}; - -/** -* Runs the specified method of the given plugins, in order, until one of them returns a successful result. -* Each method can return a synchronous value, a Promise, or call an error-first callback. -* If the promise resolves successfully, or the callback is called without an error, then the result -* is immediately returned and no further plugins are called. -* If the promise rejects, or the callback is called with an error, then the next plugin is called. -* If ALL plugins fail, then the last error is thrown. -* -* @param {object[]} plugins - An array of plugin objects -* @param {string} method - The name of the method to invoke for each plugin -* @param {object} file - A file info object, which will be passed to each method -* @returns {Promise} -*/ -exports.run = function (plugins, method, file) { -var plugin, lastError, index = 0; - -return new Promise(function (resolve, reject) { - runNextPlugin(); - - function runNextPlugin () { - plugin = plugins[index++]; - if (!plugin) { - // There are no more functions, so re-throw the last error - return reject(lastError); - } - - try { - debug(' %s', plugin.name); - var result = getResult(plugin, method, file, callback); - if (result && typeof result.then === 'function') { - // A promise was returned - result.then(onSuccess, onError); - } - else if (result !== undefined) { - // A synchronous result was returned - onSuccess(result); - } - // else { the callback will be called } - } - catch (e) { - onError(e); - } - } - - function callback (err, result) { - if (err) { - onError(err); - } - else { - onSuccess(result); - } - } - - function onSuccess (result) { - debug(' success'); - resolve({ - plugin: plugin, - result: result - }); - } - - function onError (err) { - debug(' %s', err.message || err); - lastError = err; - runNextPlugin(); - } -}); -}; - -/** -* Returns the value of the given property. -* If the property is a function, then the result of the function is returned. -* If the value is a RegExp, then it will be tested against the file URL. -* If the value is an aray, then it will be compared against the file extension. -* -* @param {object} obj - The object whose property/method is called -* @param {string} prop - The name of the property/method to invoke -* @param {object} file - A file info object, which will be passed to the method -* @param {function} [callback] - A callback function, which will be passed to the method -* @returns {*} -*/ -function getResult (obj, prop, file, callback) { -var value = obj[prop]; - -if (typeof value === 'function') { - return value.apply(obj, [file, callback]); -} - -if (!callback) { - // The synchronous plugin functions (canParse and canRead) - // allow a "shorthand" syntax, where the user can match - // files by RegExp or by file extension. - if (value instanceof RegExp) { - return value.test(file.url); - } - else if (typeof value === 'string') { - return value === file.extension; - } - else if (Array.isArray(value)) { - return value.indexOf(file.extension) !== -1; - } -} - -return value; -} - -},{"./debug":17}],19:[function(_dereq_,module,exports){ -(function (process){ -'use strict'; - -var isWindows = /^win/.test(process.platform), - forwardSlashPattern = /\//g, - protocolPattern = /^([a-z0-9.+-]+):\/\//i, - url = module.exports; - -// RegExp patterns to URL-encode special characters in local filesystem paths -var urlEncodePatterns = [ -/\?/g, '%3F', -/\#/g, '%23', -isWindows ? /\\/g : /\//, '/' -]; - -// RegExp patterns to URL-decode special characters for local filesystem paths -var urlDecodePatterns = [ -/\%23/g, '#', -/\%24/g, '$', -/\%26/g, '&', -/\%2C/g, ',', -/\%40/g, '@' -]; - -exports.parse = _dereq_('url').parse; -exports.resolve = _dereq_('url').resolve; - -/** -* Returns the current working directory (in Node) or the current page URL (in browsers). -* -* @returns {string} -*/ -exports.cwd = function cwd () { -return process.browser ? location.href : process.cwd() + '/'; -}; - -/** -* Returns the protocol of the given URL, or `undefined` if it has no protocol. -* -* @param {string} path -* @returns {?string} -*/ -exports.getProtocol = function getProtocol (path) { -var match = protocolPattern.exec(path); -if (match) { - return match[1].toLowerCase(); -} -}; - -/** -* Returns the lowercased file extension of the given URL, -* or an empty string if it has no extension. -* -* @param {string} path -* @returns {string} -*/ -exports.getExtension = function getExtension (path) { -var lastDot = path.lastIndexOf('.'); -if (lastDot >= 0) { - return path.substr(lastDot).toLowerCase(); -} -return ''; -}; - -/** -* Returns the hash (URL fragment), of the given path. -* If there is no hash, then the root hash ("#") is returned. -* -* @param {string} path -* @returns {string} -*/ -exports.getHash = function getHash (path) { -var hashIndex = path.indexOf('#'); -if (hashIndex >= 0) { - return path.substr(hashIndex); -} -return '#'; -}; - -/** -* Removes the hash (URL fragment), if any, from the given path. -* -* @param {string} path -* @returns {string} -*/ -exports.stripHash = function stripHash (path) { -var hashIndex = path.indexOf('#'); -if (hashIndex >= 0) { - path = path.substr(0, hashIndex); -} -return path; -}; - -/** -* Determines whether the given path is an HTTP(S) URL. -* -* @param {string} path -* @returns {boolean} -*/ -exports.isHttp = function isHttp (path) { -var protocol = url.getProtocol(path); -if (protocol === 'http' || protocol === 'https') { - return true; -} -else if (protocol === undefined) { - // There is no protocol. If we're running in a browser, then assume it's HTTP. - return process.browser; -} -else { - // It's some other protocol, such as "ftp://", "mongodb://", etc. - return false; -} -}; - -/** -* Determines whether the given path is a filesystem path. -* This includes "file://" URLs. -* -* @param {string} path -* @returns {boolean} -*/ -exports.isFileSystemPath = function isFileSystemPath (path) { -if (process.browser) { - // We're running in a browser, so assume that all paths are URLs. - // This way, even relative paths will be treated as URLs rather than as filesystem paths - return false; -} - -var protocol = url.getProtocol(path); -return protocol === undefined || protocol === 'file'; -}; - -/** -* Converts a filesystem path to a properly-encoded URL. -* -* This is intended to handle situations where JSON Schema $Ref Parser is called -* with a filesystem path that contains characters which are not allowed in URLs. -* -* @example -* The following filesystem paths would be converted to the following URLs: -* -* <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json -* C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json -* file://Project #42/file.json ==> file://Project%20%2342/file.json -* -* @param {string} path -* @returns {string} -*/ -exports.fromFileSystemPath = function fromFileSystemPath (path) { -// Step 1: Manually encode characters that are not encoded by `encodeURI`. -// This includes characters such as "#" and "?", which have special meaning in URLs, -// but are just normal characters in a filesystem path. -// On Windows, this will also replace backslashes with forward slashes, -// rather than encoding them as special characters. -for (var i = 0; i < urlEncodePatterns.length; i += 2) { - path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]); -} - -// Step 2: `encodeURI` will take care of all other characters -return encodeURI(path); -}; - -/** -* Converts a URL to a local filesystem path. -* -* @param {string} path -* @param {boolean} [keepFileProtocol] - If true, then "file://" will NOT be stripped -* @returns {string} -*/ -exports.toFileSystemPath = function toFileSystemPath (path, keepFileProtocol) { -// Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc. -path = decodeURI(path); - -// Step 2: Manually decode characters that are not decoded by `decodeURI`. -// This includes characters such as "#" and "?", which have special meaning in URLs, -// but are just normal characters in a filesystem path. -for (var i = 0; i < urlDecodePatterns.length; i += 2) { - path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]); -} - -// Step 3: If it's a "file://" URL, then format it consistently -// or convert it to a local filesystem path -var isFileUrl = path.substr(0, 7).toLowerCase() === 'file://'; -if (isFileUrl) { - // Strip-off the protocol, and the initial "/", if there is one - path = path[7] === '/' ? path.substr(8) : path.substr(7); - - // insert a colon (":") after the drive letter on Windows - if (isWindows && path[1] === '/') { - path = path[0] + ':' + path.substr(1); - } - - if (keepFileProtocol) { - // Return the consistently-formatted "file://" URL - path = 'file:///' + path; - } - else { - // Convert the "file://" URL to a local filesystem path. - // On Windows, it will start with something like "C:/". - // On Posix, it will start with "/" - isFileUrl = false; - path = isWindows ? path : '/' + path; - } -} - -// Step 4: Normalize Windows paths (unless it's a "file://" URL) -if (isWindows && !isFileUrl) { - // Replace forward slashes with backslashes - path = path.replace(forwardSlashPattern, '\\'); - - // Capitalize the drive letter - if (path.substr(1, 2) === ':\\') { - path = path[0].toUpperCase() + path.substr(1); - } -} - -return path; -}; - -}).call(this,_dereq_('_process')) - -},{"_process":69,"url":90}],20:[function(_dereq_,module,exports){ -/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */ -'use strict'; - -var yaml = _dereq_('js-yaml'), - ono = _dereq_('ono'); - -/** -* Simple YAML parsing functions, similar to {@link JSON.parse} and {@link JSON.stringify} -*/ -module.exports = { -/** - * Parses a YAML string and returns the value. - * - * @param {string} text - The YAML string to be parsed - * @param {function} [reviver] - Not currently supported. Provided for consistency with {@link JSON.parse} - * @returns {*} - */ -parse: function yamlParse (text, reviver) { - try { - return yaml.safeLoad(text); - } - catch (e) { - if (e instanceof Error) { - throw e; - } - else { - // https://github.com/nodeca/js-yaml/issues/153 - throw ono(e, e.message); - } - } -}, - -/** - * Converts a JavaScript value to a YAML string. - * - * @param {*} value - The value to convert to YAML - * @param {function|array} replacer - Not currently supported. Provided for consistency with {@link JSON.stringify} - * @param {string|number} space - The number of spaces to use for indentation, or a string containing the number of spaces. - * @returns {string} - */ -stringify: function yamlStringify (value, replacer, space) { - try { - var indent = (typeof space === 'string' ? space.length : space) || 2; - return yaml.safeDump(value, { indent: indent }); - } - catch (e) { - if (e instanceof Error) { - throw e; - } - else { - // https://github.com/nodeca/js-yaml/issues/153 - throw ono(e, e.message); - } - } -} -}; - -},{"js-yaml":36,"ono":67}],21:[function(_dereq_,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { -lookup[i] = code[i] -revLookup[code.charCodeAt(i)] = i -} - -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function placeHoldersCount (b64) { -var len = b64.length -if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') -} - -// the number of equal signs (place holders) -// if there are two placeholders, than the two characters before it -// represent one byte -// if there is only one, then the three characters before it represent 2 bytes -// this is just a cheap hack to not do indexOf twice -return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} - -function byteLength (b64) { -// base64 is 4/3 + up to two characters of the original data -return (b64.length * 3 / 4) - placeHoldersCount(b64) -} - -function toByteArray (b64) { -var i, l, tmp, placeHolders, arr -var len = b64.length -placeHolders = placeHoldersCount(b64) - -arr = new Arr((len * 3 / 4) - placeHolders) - -// if there are placeholders, only get up to the last complete 4 chars -l = placeHolders > 0 ? len - 4 : len - -var L = 0 - -for (i = 0; i < l; i += 4) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF -} - -if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF -} else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF -} - -return arr -} - -function tripletToBase64 (num) { -return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { -var tmp -var output = [] -for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) -} -return output.join('') -} - -function fromByteArray (uint8) { -var tmp -var len = uint8.length -var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes -var output = '' -var parts = [] -var maxChunkLength = 16383 // must be multiple of 3 - -// go through the array every three bytes, we'll deal with trailing stuff later -for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) -} - -// pad the end with zeros, but make sure to not forget the extra bytes -if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' -} else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' -} - -parts.push(output) - -return parts.join('') -} - -},{}],22:[function(_dereq_,module,exports){ - -},{}],23:[function(_dereq_,module,exports){ -/*! -* The buffer module from node.js, for the browser. -* -* @author Feross Aboukhadijeh -* @license MIT -*/ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = _dereq_('base64-js') -var ieee754 = _dereq_('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** -* If `Buffer.TYPED_ARRAY_SUPPORT`: -* === true Use Uint8Array implementation (fastest) -* === false Print warning and recommend using `buffer` v4.x which has an Object -* implementation (most compatible, even IE6) -* -* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, -* Opera 11.6+, iOS 4.2+. -* -* We report that the browser does not support typed arrays if the are not subclassable -* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` -* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support -* for __proto__ and has a buggy typed array implementation. -*/ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.warn === 'function') { -console.warn( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you _dereq_ old browser support.' -) -} - -function typedArraySupport () { -// Can typed array instances can be augmented? -try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 -} catch (e) { - return false -} -} - -function createBuffer (length) { -if (length > K_MAX_LENGTH) { - throw new RangeError('Invalid typed array length') -} -// Return an augmented `Uint8Array` instance -var buf = new Uint8Array(length) -buf.__proto__ = Buffer.prototype -return buf -} - -/** -* The Buffer constructor returns instances of `Uint8Array` that have their -* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of -* `Uint8Array`, so the returned instances will have all the node `Buffer` methods -* and the `Uint8Array` methods. Square bracket notation works as expected -- it -* returns a single octet. -* -* The `Uint8Array` prototype remains unmodified. -*/ - -function Buffer (arg, encodingOrOffset, length) { -// Common case. -if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(arg) -} -return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { -Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false -}) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { -if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') -} - -if (isArrayBuffer(value)) { - return fromArrayBuffer(value, encodingOrOffset, length) -} - -if (typeof value === 'string') { - return fromString(value, encodingOrOffset) -} - -return fromObject(value) -} - -/** -* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError -* if value is a number. -* Buffer.from(str[, encoding]) -* Buffer.from(array) -* Buffer.from(buffer) -* Buffer.from(arrayBuffer[, byteOffset[, length]]) -**/ -Buffer.from = function (value, encodingOrOffset, length) { -return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { -if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') -} else if (size < 0) { - throw new RangeError('"size" argument must not be negative') -} -} - -function alloc (size, fill, encoding) { -assertSize(size) -if (size <= 0) { - return createBuffer(size) -} -if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) -} -return createBuffer(size) -} - -/** -* Creates a new filled Buffer instance. -* alloc(size[, fill[, encoding]]) -**/ -Buffer.alloc = function (size, fill, encoding) { -return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { -assertSize(size) -return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** -* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. -* */ -Buffer.allocUnsafe = function (size) { -return allocUnsafe(size) -} -/** -* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. -*/ -Buffer.allocUnsafeSlow = function (size) { -return allocUnsafe(size) -} - -function fromString (string, encoding) { -if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' -} - -if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') -} - -var length = byteLength(string, encoding) | 0 -var buf = createBuffer(length) - -var actual = buf.write(string, encoding) - -if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) -} - -return buf -} - -function fromArrayLike (array) { -var length = array.length < 0 ? 0 : checked(array.length) | 0 -var buf = createBuffer(length) -for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 -} -return buf -} - -function fromArrayBuffer (array, byteOffset, length) { -if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') -} - -if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') -} - -var buf -if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) -} else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) -} else { - buf = new Uint8Array(array, byteOffset, length) -} - -// Return an augmented `Uint8Array` instance -buf.__proto__ = Buffer.prototype -return buf -} - -function fromObject (obj) { -if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf -} - -if (obj) { - if (isArrayBufferView(obj) || 'length' in obj) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { -// Note: cannot use `length < K_MAX_LENGTH` here because that fails when -// length is NaN (which is otherwise coerced to zero.) -if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') -} -return length | 0 -} - -function SlowBuffer (length) { -if (+length != length) { // eslint-disable-line eqeqeq - length = 0 -} -return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { -return b != null && b._isBuffer === true -} - -Buffer.compare = function compare (a, b) { -if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') -} - -if (a === b) return 0 - -var x = a.length -var y = b.length - -for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } -} - -if (x < y) return -1 -if (y < x) return 1 -return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { -switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false -} -} - -Buffer.concat = function concat (list, length) { -if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') -} - -if (list.length === 0) { - return Buffer.alloc(0) -} - -var i -if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } -} - -var buffer = Buffer.allocUnsafe(length) -var pos = 0 -for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length -} -return buffer -} - -function byteLength (string, encoding) { -if (Buffer.isBuffer(string)) { - return string.length -} -if (isArrayBufferView(string) || isArrayBuffer(string)) { - return string.byteLength -} -if (typeof string !== 'string') { - string = '' + string -} - -var len = string.length -if (len === 0) return 0 - -// Use a for loop to avoid recursion -var loweredCase = false -for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } -} -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { -var loweredCase = false - -// No need to verify that "this.length <= MAX_UINT32" since it's a read-only -// property of a typed array. - -// This behaves neither like String nor Uint8Array in that we set start/end -// to their upper/lower bounds if the value passed is out of range. -// undefined is handled specially as per ECMA-262 6th Edition, -// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. -if (start === undefined || start < 0) { - start = 0 -} -// Return early if start > this.length. Done here to prevent potential uint32 -// coercion fail below. -if (start > this.length) { - return '' -} - -if (end === undefined || end > this.length) { - end = this.length -} - -if (end <= 0) { - return '' -} - -// Force coersion to uint32. This will also coerce falsey/NaN values to 0. -end >>>= 0 -start >>>= 0 - -if (end <= start) { - return '' -} - -if (!encoding) encoding = 'utf8' - -while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } -} -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { -var i = b[n] -b[n] = b[m] -b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { -var len = this.length -if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') -} -for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) -} -return this -} - -Buffer.prototype.swap32 = function swap32 () { -var len = this.length -if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') -} -for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) -} -return this -} - -Buffer.prototype.swap64 = function swap64 () { -var len = this.length -if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') -} -for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) -} -return this -} - -Buffer.prototype.toString = function toString () { -var length = this.length -if (length === 0) return '' -if (arguments.length === 0) return utf8Slice(this, 0, length) -return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { -if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') -if (this === b) return true -return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { -var str = '' -var max = exports.INSPECT_MAX_BYTES -if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' -} -return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { -if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') -} - -if (start === undefined) { - start = 0 -} -if (end === undefined) { - end = target ? target.length : 0 -} -if (thisStart === undefined) { - thisStart = 0 -} -if (thisEnd === undefined) { - thisEnd = this.length -} - -if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') -} - -if (thisStart >= thisEnd && start >= end) { - return 0 -} -if (thisStart >= thisEnd) { - return -1 -} -if (start >= end) { - return 1 -} - -start >>>= 0 -end >>>= 0 -thisStart >>>= 0 -thisEnd >>>= 0 - -if (this === target) return 0 - -var x = thisEnd - thisStart -var y = end - start -var len = Math.min(x, y) - -var thisCopy = this.slice(thisStart, thisEnd) -var targetCopy = target.slice(start, end) - -for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } -} - -if (x < y) return -1 -if (y < x) return 1 -return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { -// Empty buffer means no match -if (buffer.length === 0) return -1 - -// Normalize byteOffset -if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 -} else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff -} else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 -} -byteOffset = +byteOffset // Coerce to Number. -if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) -} - -// Normalize byteOffset: negative offsets start from the end of the buffer -if (byteOffset < 0) byteOffset = buffer.length + byteOffset -if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 -} else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 -} - -// Normalize val -if (typeof val === 'string') { - val = Buffer.from(val, encoding) -} - -// Finally, search either indexOf (if dir is true) or lastIndexOf -if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) -} else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) -} - -throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { -var indexSize = 1 -var arrLength = arr.length -var valLength = val.length - -if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } -} - -function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } -} - -var i -if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } -} else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } -} - -return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { -return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { -return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { -return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { -offset = Number(offset) || 0 -var remaining = buf.length - offset -if (!length) { - length = remaining -} else { - length = Number(length) - if (length > remaining) { - length = remaining - } -} - -// must be an even number of digits -var strLen = string.length -if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - -if (length > strLen / 2) { - length = strLen / 2 -} -for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed -} -return i -} - -function utf8Write (buf, string, offset, length) { -return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { -return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { -return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { -return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { -return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { -// Buffer#write(string) -if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 -// Buffer#write(string, encoding) -} else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 -// Buffer#write(string, offset[, length][, encoding]) -} else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } -} else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) -} - -var remaining = this.length - offset -if (length === undefined || length > remaining) length = remaining - -if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') -} - -if (!encoding) encoding = 'utf8' - -var loweredCase = false -for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } -} -} - -Buffer.prototype.toJSON = function toJSON () { -return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) -} -} - -function base64Slice (buf, start, end) { -if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) -} else { - return base64.fromByteArray(buf.slice(start, end)) -} -} - -function utf8Slice (buf, start, end) { -end = Math.min(buf.length, end) -var res = [] - -var i = start -while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence -} - -return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { -var len = codePoints.length -if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() -} - -// Decode in chunks to avoid "call stack size exceeded". -var res = '' -var i = 0 -while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) -} -return res -} - -function asciiSlice (buf, start, end) { -var ret = '' -end = Math.min(buf.length, end) - -for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) -} -return ret -} - -function latin1Slice (buf, start, end) { -var ret = '' -end = Math.min(buf.length, end) - -for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) -} -return ret -} - -function hexSlice (buf, start, end) { -var len = buf.length - -if (!start || start < 0) start = 0 -if (!end || end < 0 || end > len) end = len - -var out = '' -for (var i = start; i < end; ++i) { - out += toHex(buf[i]) -} -return out -} - -function utf16leSlice (buf, start, end) { -var bytes = buf.slice(start, end) -var res = '' -for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) -} -return res -} - -Buffer.prototype.slice = function slice (start, end) { -var len = this.length -start = ~~start -end = end === undefined ? len : ~~end - -if (start < 0) { - start += len - if (start < 0) start = 0 -} else if (start > len) { - start = len -} - -if (end < 0) { - end += len - if (end < 0) end = 0 -} else if (end > len) { - end = len -} - -if (end < start) end = start - -var newBuf = this.subarray(start, end) -// Return an augmented `Uint8Array` instance -newBuf.__proto__ = Buffer.prototype -return newBuf -} - -/* -* Need to make sure that buffer isn't trying to write out of bounds. -*/ -function checkOffset (offset, ext, length) { -if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') -if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) checkOffset(offset, byteLength, this.length) - -var val = this[offset] -var mul = 1 -var i = 0 -while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul -} - -return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) { - checkOffset(offset, byteLength, this.length) -} - -var val = this[offset + --byteLength] -var mul = 1 -while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul -} - -return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 1, this.length) -return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 2, this.length) -return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 2, this.length) -return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) - -return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) - -return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) checkOffset(offset, byteLength, this.length) - -var val = this[offset] -var mul = 1 -var i = 0 -while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul -} -mul *= 0x80 - -if (val >= mul) val -= Math.pow(2, 8 * byteLength) - -return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) checkOffset(offset, byteLength, this.length) - -var i = byteLength -var mul = 1 -var val = this[offset + --i] -while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul -} -mul *= 0x80 - -if (val >= mul) val -= Math.pow(2, 8 * byteLength) - -return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 1, this.length) -if (!(this[offset] & 0x80)) return (this[offset]) -return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 2, this.length) -var val = this[offset] | (this[offset + 1] << 8) -return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 2, this.length) -var val = this[offset + 1] | (this[offset] << 8) -return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) - -return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) - -return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) -return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 4, this.length) -return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 8, this.length) -return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { -offset = offset >>> 0 -if (!noAssert) checkOffset(offset, 8, this.length) -return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { -if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') -if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') -if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { -value = +value -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) -} - -var mul = 1 -var i = 0 -this[offset] = value & 0xFF -while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF -} - -return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { -value = +value -offset = offset >>> 0 -byteLength = byteLength >>> 0 -if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) -} - -var i = byteLength - 1 -var mul = 1 -this[offset + i] = value & 0xFF -while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF -} - -return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) -this[offset] = (value & 0xff) -return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) -this[offset] = (value & 0xff) -this[offset + 1] = (value >>> 8) -return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) -this[offset] = (value >>> 8) -this[offset + 1] = (value & 0xff) -return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) -this[offset + 3] = (value >>> 24) -this[offset + 2] = (value >>> 16) -this[offset + 1] = (value >>> 8) -this[offset] = (value & 0xff) -return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) -this[offset] = (value >>> 24) -this[offset + 1] = (value >>> 16) -this[offset + 2] = (value >>> 8) -this[offset + 3] = (value & 0xff) -return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) -} - -var i = 0 -var mul = 1 -var sub = 0 -this[offset] = value & 0xFF -while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF -} - -return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) -} - -var i = byteLength - 1 -var mul = 1 -var sub = 0 -this[offset + i] = value & 0xFF -while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF -} - -return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) -if (value < 0) value = 0xff + value + 1 -this[offset] = (value & 0xff) -return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) -this[offset] = (value & 0xff) -this[offset + 1] = (value >>> 8) -return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) -this[offset] = (value >>> 8) -this[offset + 1] = (value & 0xff) -return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) -this[offset] = (value & 0xff) -this[offset + 1] = (value >>> 8) -this[offset + 2] = (value >>> 16) -this[offset + 3] = (value >>> 24) -return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) -if (value < 0) value = 0xffffffff + value + 1 -this[offset] = (value >>> 24) -this[offset + 1] = (value >>> 16) -this[offset + 2] = (value >>> 8) -this[offset + 3] = (value & 0xff) -return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { -if (offset + ext > buf.length) throw new RangeError('Index out of range') -if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) -} -ieee754.write(buf, value, offset, littleEndian, 23, 4) -return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { -return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { -return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { -value = +value -offset = offset >>> 0 -if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) -} -ieee754.write(buf, value, offset, littleEndian, 52, 8) -return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { -return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { -return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { -if (!start) start = 0 -if (!end && end !== 0) end = this.length -if (targetStart >= target.length) targetStart = target.length -if (!targetStart) targetStart = 0 -if (end > 0 && end < start) end = start - -// Copy 0 bytes; we're done -if (end === start) return 0 -if (target.length === 0 || this.length === 0) return 0 - -// Fatal error conditions -if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') -} -if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') -if (end < 0) throw new RangeError('sourceEnd out of bounds') - -// Are we oob? -if (end > this.length) end = this.length -if (target.length - targetStart < end - start) { - end = target.length - targetStart + start -} - -var len = end - start -var i - -if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } -} else if (len < 1000) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } -} else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) -} - -return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { -// Handle string cases: -if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } -} else if (typeof val === 'number') { - val = val & 255 -} - -// Invalid ranges are not set to a default, so can range check early. -if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') -} - -if (end <= start) { - return this -} - -start = start >>> 0 -end = end === undefined ? this.length : end >>> 0 - -if (!val) val = 0 - -var i -if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } -} else { - var bytes = Buffer.isBuffer(val) - ? val - : new Buffer(val, encoding) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } -} - -return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { -// Node strips out invalid characters like \n and \t from the string, base64-js does not -str = str.trim().replace(INVALID_BASE64_RE, '') -// Node converts strings with length < 2 to '' -if (str.length < 2) return '' -// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not -while (str.length % 4 !== 0) { - str = str + '=' -} -return str -} - -function toHex (n) { -if (n < 16) return '0' + n.toString(16) -return n.toString(16) -} - -function utf8ToBytes (string, units) { -units = units || Infinity -var codePoint -var length = string.length -var leadSurrogate = null -var bytes = [] - -for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } -} - -return bytes -} - -function asciiToBytes (str) { -var byteArray = [] -for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) -} -return byteArray -} - -function utf16leToBytes (str, units) { -var c, hi, lo -var byteArray = [] -for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) -} - -return byteArray -} - -function base64ToBytes (str) { -return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { -for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] -} -return i -} - -// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check -// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 -function isArrayBuffer (obj) { -return obj instanceof ArrayBuffer || - (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && - typeof obj.byteLength === 'number') -} - -// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` -function isArrayBufferView (obj) { -return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) -} - -function numberIsNaN (obj) { -return obj !== obj // eslint-disable-line no-self-compare -} - -},{"base64-js":21,"ieee754":32}],24:[function(_dereq_,module,exports){ -module.exports = { -"100": "Continue", -"101": "Switching Protocols", -"102": "Processing", -"200": "OK", -"201": "Created", -"202": "Accepted", -"203": "Non-Authoritative Information", -"204": "No Content", -"205": "Reset Content", -"206": "Partial Content", -"207": "Multi-Status", -"208": "Already Reported", -"226": "IM Used", -"300": "Multiple Choices", -"301": "Moved Permanently", -"302": "Found", -"303": "See Other", -"304": "Not Modified", -"305": "Use Proxy", -"307": "Temporary Redirect", -"308": "Permanent Redirect", -"400": "Bad Request", -"401": "Unauthorized", -"402": "Payment Required", -"403": "Forbidden", -"404": "Not Found", -"405": "Method Not Allowed", -"406": "Not Acceptable", -"407": "Proxy Authentication Required", -"408": "Request Timeout", -"409": "Conflict", -"410": "Gone", -"411": "Length Required", -"412": "Precondition Failed", -"413": "Payload Too Large", -"414": "URI Too Long", -"415": "Unsupported Media Type", -"416": "Range Not Satisfiable", -"417": "Expectation Failed", -"418": "I'm a teapot", -"421": "Misdirected Request", -"422": "Unprocessable Entity", -"423": "Locked", -"424": "Failed Dependency", -"425": "Unordered Collection", -"426": "Upgrade Required", -"428": "Precondition Required", -"429": "Too Many Requests", -"431": "Request Header Fields Too Large", -"451": "Unavailable For Legal Reasons", -"500": "Internal Server Error", -"501": "Not Implemented", -"502": "Bad Gateway", -"503": "Service Unavailable", -"504": "Gateway Timeout", -"505": "HTTP Version Not Supported", -"506": "Variant Also Negotiates", -"507": "Insufficient Storage", -"508": "Loop Detected", -"509": "Bandwidth Limit Exceeded", -"510": "Not Extended", -"511": "Network Authentication Required" -} - -},{}],25:[function(_dereq_,module,exports){ -(function (process,global){ -"use strict" - -var next = (global.process && process.nextTick) || global.setImmediate || function (f) { -setTimeout(f, 0) -} - -module.exports = function maybe (cb, promise) { -if (cb) { - promise - .then(function (result) { - next(function () { cb(null, result) }) - }, function (err) { - next(function () { cb(err) }) - }) - return undefined -} -else { - return promise -} -} - -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"_process":69}],26:[function(_dereq_,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { -if (Array.isArray) { - return Array.isArray(arg); -} -return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { -return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { -return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { -return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { -return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { -return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { -return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { -return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { -return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { -return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { -return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { -return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { -return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { -return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { -return Object.prototype.toString.call(o); -} - -}).call(this,{"isBuffer":_dereq_("../../is-buffer/index.js")}) - -},{"../../is-buffer/index.js":34}],27:[function(_dereq_,module,exports){ -(function (process){ -/** -* This is the web browser implementation of `debug()`. -* -* Expose `debug()` as the module. -*/ - -exports = module.exports = _dereq_('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** -* Colors. -*/ - -exports.colors = [ -'#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', -'#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', -'#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', -'#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', -'#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', -'#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', -'#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', -'#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', -'#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', -'#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', -'#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; - -/** -* Currently only WebKit-based Web Inspectors, Firefox >= v31, -* and the Firebug extension (any Firefox version) are known -* to support "%c" CSS customizations. -* -* TODO: add a `localStorage` variable to explicitly enable/disable colors -*/ - -function useColors() { -// NB: In an Electron preload script, document will be defined but not fully -// initialized. Since we know we're in Chrome, we'll just detect this case -// explicitly -if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; -} - -// Internet Explorer and Edge do not support colors. -if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; -} - -// is webkit? http://stackoverflow.com/a/16459606/376773 -// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 -return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** -* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. -*/ - -exports.formatters.j = function(v) { -try { - return JSON.stringify(v); -} catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; -} -}; - - -/** -* Colorize log arguments if enabled. -* -* @api public -*/ - -function formatArgs(args) { -var useColors = this.useColors; - -args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - -if (!useColors) return; - -var c = 'color: ' + this.color; -args.splice(1, 0, c, 'color: inherit') - -// the final "%c" is somewhat tricky, because there could be other -// arguments passed either before or after the %c, so we need to -// figure out the correct index to insert the CSS into -var index = 0; -var lastC = 0; -args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } -}); - -args.splice(lastC, 0, c); -} - -/** -* Invokes `console.log()` when available. -* No-op when `console.log` is not a "function". -* -* @api public -*/ - -function log() { -// this hackery is required for IE8/9, where -// the `console.log` function doesn't have 'apply' -return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** -* Save `namespaces`. -* -* @param {String} namespaces -* @api private -*/ - -function save(namespaces) { -try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } -} catch(e) {} -} - -/** -* Load `namespaces`. -* -* @return {String} returns the previously persisted debug modes -* @api private -*/ - -function load() { -var r; -try { - r = exports.storage.debug; -} catch(e) {} - -// If debug isn't set in LS, and we're in Electron, try to load $DEBUG -if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; -} - -return r; -} - -/** -* Enable namespaces listed in `localStorage.debug` initially. -*/ - -exports.enable(load()); - -/** -* Localstorage attempts to return the localstorage. -* -* This is necessary because safari throws -* when a user disables cookies/localstorage -* and you attempt to access it. -* -* @return {LocalStorage} -* @api private -*/ - -function localstorage() { -try { - return window.localStorage; -} catch (e) {} -} - -}).call(this,_dereq_('_process')) - -},{"./debug":28,"_process":69}],28:[function(_dereq_,module,exports){ - -/** -* This is the common logic for both the Node.js and web browser -* implementations of `debug()`. -* -* Expose `debug()` as the module. -*/ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = _dereq_('ms'); - -/** -* Active `debug` instances. -*/ -exports.instances = []; - -/** -* The currently active debug mode names, and names to skip. -*/ - -exports.names = []; -exports.skips = []; - -/** -* Map of special "%n" handling functions, for the debug "format" argument. -* -* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". -*/ - -exports.formatters = {}; - -/** -* Select a color. -* @param {String} namespace -* @return {Number} -* @api private -*/ - -function selectColor(namespace) { -var hash = 0, i; - -for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer -} - -return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** -* Create a debugger with the given `namespace`. -* -* @param {String} namespace -* @return {Function} -* @api public -*/ - -function createDebug(namespace) { - -var prevTime; - -function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); -} - -debug.namespace = namespace; -debug.enabled = exports.enabled(namespace); -debug.useColors = exports.useColors(); -debug.color = selectColor(namespace); -debug.destroy = destroy; - -// env-specific initialization logic for debug instances -if ('function' === typeof exports.init) { - exports.init(debug); -} - -exports.instances.push(debug); - -return debug; -} - -function destroy () { -var index = exports.instances.indexOf(this); -if (index !== -1) { - exports.instances.splice(index, 1); - return true; -} else { - return false; -} -} - -/** -* Enables a debug mode by namespaces. This can include modes -* separated by a colon and wildcards. -* -* @param {String} namespaces -* @api public -*/ - -function enable(namespaces) { -exports.save(namespaces); - -exports.names = []; -exports.skips = []; - -var i; -var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); -var len = split.length; - -for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } -} - -for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); -} -} - -/** -* Disable debug output. -* -* @api public -*/ - -function disable() { -exports.enable(''); -} - -/** -* Returns true if the given mode name is enabled, false otherwise. -* -* @param {String} name -* @return {Boolean} -* @api public -*/ - -function enabled(name) { -if (name[name.length - 1] === '*') { - return true; -} -var i, len; -for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } -} -for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } -} -return false; -} - -/** -* Coerce `val`. -* -* @param {Mixed} val -* @return {Mixed} -* @api private -*/ - -function coerce(val) { -if (val instanceof Error) return val.stack || val.message; -return val; -} - -},{"ms":66}],29:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { -this._events = this._events || {}; -this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { -if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); -this._maxListeners = n; -return this; -}; - -EventEmitter.prototype.emit = function(type) { -var er, handler, len, args, i, listeners; - -if (!this._events) - this._events = {}; - -// If there is no 'error' event listener then throw. -if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } -} - -handler = this._events[type]; - -if (isUndefined(handler)) - return false; - -if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } -} else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); -} - -return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { -var m; - -if (!isFunction(listener)) - throw TypeError('listener must be a function'); - -if (!this._events) - this._events = {}; - -// To avoid recursion in the case that type === "newListener"! Before -// adding it to the listeners, first emit "newListener". -if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - -if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; -else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); -else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - -// Check for listener leak -if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.warn('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } -} - -return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { -if (!isFunction(listener)) - throw TypeError('listener must be a function'); - -var fired = false; - -function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } -} - -g.listener = listener; -this.on(type, g); - -return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { -var list, position, length, i; - -if (!isFunction(listener)) - throw TypeError('listener must be a function'); - -if (!this._events || !this._events[type]) - return this; - -list = this._events[type]; -length = list.length; -position = -1; - -if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - -} else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); -} - -return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { -var key, listeners; - -if (!this._events) - return this; - -// not listening for removeListener, no need to emit -if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; -} - -// emit removeListener for all listeners on all events -if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; -} - -listeners = this._events[type]; - -if (isFunction(listeners)) { - this.removeListener(type, listeners); -} else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); -} -delete this._events[type]; - -return this; -}; - -EventEmitter.prototype.listeners = function(type) { -var ret; -if (!this._events || !this._events[type]) - ret = []; -else if (isFunction(this._events[type])) - ret = [this._events[type]]; -else - ret = this._events[type].slice(); -return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { -if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; -} -return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { -return emitter.listenerCount(type); -}; - -function isFunction(arg) { -return typeof arg === 'function'; -} - -function isNumber(arg) { -return typeof arg === 'number'; -} - -function isObject(arg) { -return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { -return arg === void 0; -} - -},{}],30:[function(_dereq_,module,exports){ -function format(fmt) { -var re = /(%?)(%([jds]))/g - , args = Array.prototype.slice.call(arguments, 1); -if(args.length) { - fmt = fmt.replace(re, function(match, escaped, ptn, flag) { - var arg = args.shift(); - switch(flag) { - case 's': - arg = '' + arg; - break; - case 'd': - arg = Number(arg); - break; - case 'j': - arg = JSON.stringify(arg); - break; - } - if(!escaped) { - return arg; - } - args.unshift(arg); - return match; - }) -} - -// arguments remain after formatting -if(args.length) { - fmt += ' ' + args.join(' '); -} - -// update escaped %% values -fmt = fmt.replace(/%{2,2}/g, '%'); - -return '' + fmt; -} - -module.exports = format; - -},{}],31:[function(_dereq_,module,exports){ -var http = _dereq_('http') -var url = _dereq_('url') - -var https = module.exports - -for (var key in http) { -if (http.hasOwnProperty(key)) https[key] = http[key] -} - -https.request = function (params, cb) { -params = validateParams(params) -return http.request.call(this, params, cb) -} - -https.get = function (params, cb) { -params = validateParams(params) -return http.get.call(this, params, cb) -} - -function validateParams (params) { -if (typeof params === 'string') { - params = url.parse(params) -} -if (!params.protocol) { - params.protocol = 'https:' -} -if (params.protocol !== 'https:') { - throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') -} -return params -} - -},{"http":84,"url":90}],32:[function(_dereq_,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { -var e, m -var eLen = nBytes * 8 - mLen - 1 -var eMax = (1 << eLen) - 1 -var eBias = eMax >> 1 -var nBits = -7 -var i = isLE ? (nBytes - 1) : 0 -var d = isLE ? -1 : 1 -var s = buffer[offset + i] - -i += d - -e = s & ((1 << (-nBits)) - 1) -s >>= (-nBits) -nBits += eLen -for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - -m = e & ((1 << (-nBits)) - 1) -e >>= (-nBits) -nBits += mLen -for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - -if (e === 0) { - e = 1 - eBias -} else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) -} else { - m = m + Math.pow(2, mLen) - e = e - eBias -} -return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { -var e, m, c -var eLen = nBytes * 8 - mLen - 1 -var eMax = (1 << eLen) - 1 -var eBias = eMax >> 1 -var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) -var i = isLE ? 0 : (nBytes - 1) -var d = isLE ? 1 : -1 -var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - -value = Math.abs(value) - -if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax -} else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } -} - -for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - -e = (e << mLen) | m -eLen += mLen -for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - -buffer[offset + i - d] |= s * 128 -} - -},{}],33:[function(_dereq_,module,exports){ -if (typeof Object.create === 'function') { -// implementation from standard node.js 'util' module -module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; -} else { -// old school shim for old browsers -module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor -} -} - -},{}],34:[function(_dereq_,module,exports){ -/*! -* Determine if an object is a Buffer -* -* @author Feross Aboukhadijeh -* @license MIT -*/ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { -return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { -return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { -return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],35:[function(_dereq_,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { -return toString.call(arr) == '[object Array]'; -}; - -},{}],36:[function(_dereq_,module,exports){ -'use strict'; - - -var yaml = _dereq_('./lib/js-yaml.js'); - - -module.exports = yaml; - -},{"./lib/js-yaml.js":37}],37:[function(_dereq_,module,exports){ -'use strict'; - - -var loader = _dereq_('./js-yaml/loader'); -var dumper = _dereq_('./js-yaml/dumper'); - - -function deprecated(name) { -return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); -}; -} - - -module.exports.Type = _dereq_('./js-yaml/type'); -module.exports.Schema = _dereq_('./js-yaml/schema'); -module.exports.FAILSAFE_SCHEMA = _dereq_('./js-yaml/schema/failsafe'); -module.exports.JSON_SCHEMA = _dereq_('./js-yaml/schema/json'); -module.exports.CORE_SCHEMA = _dereq_('./js-yaml/schema/core'); -module.exports.DEFAULT_SAFE_SCHEMA = _dereq_('./js-yaml/schema/default_safe'); -module.exports.DEFAULT_FULL_SCHEMA = _dereq_('./js-yaml/schema/default_full'); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.safeLoad = loader.safeLoad; -module.exports.safeLoadAll = loader.safeLoadAll; -module.exports.dump = dumper.dump; -module.exports.safeDump = dumper.safeDump; -module.exports.YAMLException = _dereq_('./js-yaml/exception'); - -// Deprecated schema names from JS-YAML 2.0.x -module.exports.MINIMAL_SCHEMA = _dereq_('./js-yaml/schema/failsafe'); -module.exports.SAFE_SCHEMA = _dereq_('./js-yaml/schema/default_safe'); -module.exports.DEFAULT_SCHEMA = _dereq_('./js-yaml/schema/default_full'); - -// Deprecated functions from JS-YAML 1.x.x -module.exports.scan = deprecated('scan'); -module.exports.parse = deprecated('parse'); -module.exports.compose = deprecated('compose'); -module.exports.addConstructor = deprecated('addConstructor'); - -},{"./js-yaml/dumper":39,"./js-yaml/exception":40,"./js-yaml/loader":41,"./js-yaml/schema":43,"./js-yaml/schema/core":44,"./js-yaml/schema/default_full":45,"./js-yaml/schema/default_safe":46,"./js-yaml/schema/failsafe":47,"./js-yaml/schema/json":48,"./js-yaml/type":49}],38:[function(_dereq_,module,exports){ -'use strict'; - - -function isNothing(subject) { -return (typeof subject === 'undefined') || (subject === null); -} - - -function isObject(subject) { -return (typeof subject === 'object') && (subject !== null); -} - - -function toArray(sequence) { -if (Array.isArray(sequence)) return sequence; -else if (isNothing(sequence)) return []; - -return [ sequence ]; -} - - -function extend(target, source) { -var index, length, key, sourceKeys; - -if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } -} - -return target; -} - - -function repeat(string, count) { -var result = '', cycle; - -for (cycle = 0; cycle < count; cycle += 1) { - result += string; -} - -return result; -} - - -function isNegativeZero(number) { -return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} - - -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; - -},{}],39:[function(_dereq_,module,exports){ -'use strict'; - -/*eslint-disable no-use-before-define*/ - -var common = _dereq_('./common'); -var YAMLException = _dereq_('./exception'); -var DEFAULT_FULL_SCHEMA = _dereq_('./schema/default_full'); -var DEFAULT_SAFE_SCHEMA = _dereq_('./schema/default_safe'); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ -'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', -'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { -var result, keys, index, length, tag, style, type; - -if (map === null) return {}; - -result = {}; -keys = Object.keys(map); - -for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } - - result[tag] = style; -} - -return result; -} - -function encodeHex(character) { -var string, handle, length; - -string = character.toString(16).toUpperCase(); - -if (character <= 0xFF) { - handle = 'x'; - length = 2; -} else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; -} else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; -} else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); -} - -return '\\' + handle + common.repeat('0', length - string.length) + string; -} - -function State(options) { -this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; -this.indent = Math.max(1, (options['indent'] || 2)); -this.skipInvalid = options['skipInvalid'] || false; -this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); -this.styleMap = compileStyleMap(this.schema, options['styles'] || null); -this.sortKeys = options['sortKeys'] || false; -this.lineWidth = options['lineWidth'] || 80; -this.noRefs = options['noRefs'] || false; -this.noCompatMode = options['noCompatMode'] || false; -this.condenseFlow = options['condenseFlow'] || false; - -this.implicitTypes = this.schema.compiledImplicit; -this.explicitTypes = this.schema.compiledExplicit; - -this.tag = null; -this.result = ''; - -this.duplicates = []; -this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { -var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - -while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } - - if (line.length && line !== '\n') result += ind; - - result += line; -} - -return result; -} - -function generateNextLine(state, level) { -return '\n' + common.repeat(' ', state.indent * level); -} - -function testImplicitResolving(state, str) { -var index, length, type; - -for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } -} - -return false; -} - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { -return c === CHAR_SPACE || c === CHAR_TAB; -} - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { -return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); -} - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c) { -// Uses a subset of nb-char - c-flow-indicator - ":" - "#" -// where nb-char ::= c-printable - b-char - c-byte-order-mark. -return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - && c !== CHAR_COLON - && c !== CHAR_SHARP; -} - -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { -// Uses a subset of ns-char - c-indicator -// where ns-char = nb-char - s-white. -return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} - -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { -var i; -var char; -var hasLineBreak = false; -var hasFoldableLine = false; // only checked if shouldTrackWidth -var shouldTrackWidth = lineWidth !== -1; -var previousLineBreak = -1; // count the first line correctly -var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); - -if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char); - } -} else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char); - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); -} -// Although every style can represent \n without escaping, prefer block styles -// for multiline, since they're more readable and they don't add empty lines. -// Also prefer folding a super-long line. -if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; -} -// Edge case: block indentation indicator can only have one digit. -if (string[0] === ' ' && indentPerLevel > 9) { - return STYLE_DOUBLE; -} -// At this point we know block styles are valid. -// Prefer literal style unless we want to fold. -return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { -state.dump = (function () { - if (string.length === 0) { - return "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } -}()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { -var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : ''; - -// note the special case: the string '\n' counts as a "trailing" empty line. -var clip = string[string.length - 1] === '\n'; -var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); -var chomp = keep ? '+' : (clip ? '' : '-'); - -return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { -return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { -// In folded style, $k$ consecutive newlines output as $k+1$ newlines— -// unless they're before or after a more-indented line, or at the very -// beginning or end, in which case $k$ maps to $k$. -// Therefore, parse each chunk as newline(s) followed by a content line. -var lineRe = /(\n+)([^\n]*)/g; - -// first line (possibly an empty line) -var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); -}()); -// If we haven't reached the first content line yet, don't add an extra \n. -var prevMoreIndented = string[0] === '\n' || string[0] === ' '; -var moreIndented; - -// rest of the lines -var match; -while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; -} - -return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { -if (line === '' || line[0] === ' ') return line; - -// Since a more-indented line adds a \n, breaks can't be followed by a space. -var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. -var match; -// start is an inclusive index. end, curr, and next are exclusive. -var start = 0, end, curr = 0, next = 0; -var result = ''; - -// Invariants: 0 <= start <= length-1. -// 0 <= curr <= next <= max(0, length-2). curr - start <= width. -// Inside the loop: -// A match implies length >= 2, so curr and next are <= length-2. -while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; -} - -// By the invariants, start <= length-1, so there is something left over. -// It is either the whole string or a part starting from non-whitespace. -result += '\n'; -// Insert a break if the remainder is too long and there is a break available. -if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); -} else { - result += line.slice(start); -} - -return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { -var result = ''; -var char, nextChar; -var escapeSeq; - -for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } - } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); -} - -return result; -} - -function writeFlowSequence(state, level, object) { -var _result = '', - _tag = state.tag, - index, - length; - -for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } -} - -state.tag = _tag; -state.dump = '[' + _result + ']'; -} - -function writeBlockSequence(state, level, object, compact) { -var _result = '', - _tag = state.tag, - index, - length; - -for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } - - _result += state.dump; - } -} - -state.tag = _tag; -state.dump = _result || '[]'; // Empty sequence if no valid values. -} - -function writeFlowMapping(state, level, object) { -var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - -for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = state.condenseFlow ? '"' : ''; - - if (index !== 0) pairBuffer += ', '; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; -} - -state.tag = _tag; -state.dump = '{' + _result + '}'; -} - -function writeBlockMapping(state, level, object, compact) { -var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - -// Allow sorting keys so that the output file is deterministic -if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); -} else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); -} else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); -} - -for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; -} - -state.tag = _tag; -state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { -var _result, typeList, index, length, type, style; - -typeList = explicit ? state.explicitTypes : state.implicitTypes; - -for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - state.tag = explicit ? type.tag : '?'; - - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; - - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } - - state.dump = _result; - } - - return true; - } -} - -return false; -} - -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { -state.tag = null; -state.dump = object; - -if (!detectType(state, object, false)) { - detectType(state, object, true); -} - -var type = _toString.call(state.dump); - -if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); -} - -var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; - -if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; -} - -if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; -} - -if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; -} else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; - } -} - -return true; -} - -function getDuplicateReferences(object, state) { -var objects = [], - duplicatesIndexes = [], - index, - length; - -inspectNode(object, objects, duplicatesIndexes); - -for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); -} -state.usedDuplicates = new Array(length); -} - -function inspectNode(object, objects, duplicatesIndexes) { -var objectKeyList, - index, - length; - -if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } - } -} -} - -function dump(input, options) { -options = options || {}; - -var state = new State(options); - -if (!state.noRefs) getDuplicateReferences(input, state); - -if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; - -return ''; -} - -function safeDump(input, options) { -return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - -module.exports.dump = dump; -module.exports.safeDump = safeDump; - -},{"./common":38,"./exception":40,"./schema/default_full":45,"./schema/default_safe":46}],40:[function(_dereq_,module,exports){ -// YAML error class. http://stackoverflow.com/questions/8458984 -// -'use strict'; - -function YAMLException(reason, mark) { -// Super constructor -Error.call(this); - -this.name = 'YAMLException'; -this.reason = reason; -this.mark = mark; -this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - -// Include stack trace in error object -if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); -} else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; -} -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { -var result = this.name + ': '; - -result += this.reason || '(unknown reason)'; - -if (!compact && this.mark) { - result += ' ' + this.mark.toString(); -} - -return result; -}; - - -module.exports = YAMLException; - -},{}],41:[function(_dereq_,module,exports){ -'use strict'; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = _dereq_('./common'); -var YAMLException = _dereq_('./exception'); -var Mark = _dereq_('./mark'); -var DEFAULT_SAFE_SCHEMA = _dereq_('./schema/default_safe'); -var DEFAULT_FULL_SCHEMA = _dereq_('./schema/default_full'); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function is_EOL(c) { -return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { -return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { -return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { -return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} - -function fromHexCode(c) { -var lc; - -if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; -} - -/*eslint-disable no-bitwise*/ -lc = c | 0x20; - -if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; -} - -return -1; -} - -function escapedHexLen(c) { -if (c === 0x78/* x */) { return 2; } -if (c === 0x75/* u */) { return 4; } -if (c === 0x55/* U */) { return 8; } -return 0; -} - -function fromDecimalCode(c) { -if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; -} - -return -1; -} - -function simpleEscapeSequence(c) { -/* eslint-disable indent */ -return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} - -function charFromCodepoint(c) { -if (c <= 0xFFFF) { - return String.fromCharCode(c); -} -// Encode UTF-16 surrogate pair -// https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF -return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 -); -} - -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { -simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; -simpleEscapeMap[i] = simpleEscapeSequence(i); -} - - -function State(input, options) { -this.input = input; - -this.filename = options['filename'] || null; -this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; -this.onWarning = options['onWarning'] || null; -this.legacy = options['legacy'] || false; -this.json = options['json'] || false; -this.listener = options['listener'] || null; - -this.implicitTypes = this.schema.compiledImplicit; -this.typeMap = this.schema.compiledTypeMap; - -this.length = input.length; -this.position = 0; -this.line = 0; -this.lineStart = 0; -this.lineIndent = 0; - -this.documents = []; - -/* -this.version; -this.checkLineBreaks; -this.tagMap; -this.anchorMap; -this.tag; -this.anchor; -this.kind; -this.result;*/ - -} - - -function generateError(state, message) { -return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} - -function throwError(state, message) { -throw generateError(state, message); -} - -function throwWarning(state, message) { -if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); -} -} - - -var directiveHandlers = { - -YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } -}, - -TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - state.tagMap[handle] = prefix; -} -}; - - -function captureSegment(state, start, end, checkJson) { -var _position, _length, _character, _result; - -if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; -} -} - -function mergeMappings(state, destination, source, overridableKeys) { -var sourceKeys, key, index, quantity; - -if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); -} - -sourceKeys = Object.keys(source); - -for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } -} -} - -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { -var index, quantity; - -keyNode = String(keyNode); - -if (_result === null) { - _result = {}; -} - -if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } -} else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; -} - -return _result; -} - -function readLineBreak(state) { -var ch; - -ch = state.input.charCodeAt(state.position); - -if (ch === 0x0A/* LF */) { - state.position++; -} else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } -} else { - throwError(state, 'a line break is expected'); -} - -state.line += 1; -state.lineStart = state.position; -} - -function skipSeparationSpace(state, allowComments, checkIndent) { -var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - -while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } -} - -if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); -} - -return lineBreaks; -} - -function testDocumentSeparator(state) { -var _position = state.position, - ch; - -ch = state.input.charCodeAt(_position); - -// Condition state.position === state.lineStart is tested -// in parent on each call, for efficiency. No needs to test here again. -if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } -} - -return false; -} - -function writeFoldedLines(state, count) { -if (count === 1) { - state.result += ' '; -} else if (count > 1) { - state.result += common.repeat('\n', count - 1); -} -} - - -function readPlainScalar(state, nodeIndent, withinFlowCollection) { -var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - -ch = state.input.charCodeAt(state.position); - -if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; -} - -if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } -} - -state.kind = 'scalar'; -state.result = ''; -captureStart = captureEnd = state.position; -hasPendingContent = false; - -while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); -} - -captureSegment(state, captureStart, captureEnd, false); - -if (state.result) { - return true; -} - -state.kind = _kind; -state.result = _result; -return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { -var ch, - captureStart, captureEnd; - -ch = state.input.charCodeAt(state.position); - -if (ch !== 0x27/* ' */) { - return false; -} - -state.kind = 'scalar'; -state.result = ''; -state.position++; -captureStart = captureEnd = state.position; - -while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } -} - -throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} - -function readDoubleQuotedScalar(state, nodeIndent) { -var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch !== 0x22/* " */) { - return false; -} - -state.kind = 'scalar'; -state.result = ''; -state.position++; -captureStart = captureEnd = state.position; - -while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } -} - -throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { -var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; -} else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; -} else { - return false; -} - -if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; -} - -ch = state.input.charCodeAt(++state.position); - -while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } -} - -throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { -var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch === 0x7C/* | */) { - folding = false; -} else if (ch === 0x3E/* > */) { - folding = true; -} else { - return false; -} - -state.kind = 'scalar'; -state.result = ''; - -while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } -} - -if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } -} - -while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); -} - -return true; -} - -function readBlockSequence(state, nodeIndent) { -var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - -if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; -} - -ch = state.input.charCodeAt(state.position); - -while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } -} - -if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; -} -return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { -var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - -if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; -} - -ch = state.input.charCodeAt(state.position); - -while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } -} - -// -// Epilogue. -// - -// Special case: last mapping's node contains only the key in explicit notation. -if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); -} - -// Expose the resulting mapping. -if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; -} - -return detected; -} - -function readTagProperty(state) { -var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch !== 0x21/* ! */) return false; - -if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); -} - -ch = state.input.charCodeAt(++state.position); - -if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - -} else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - -} else { - tagHandle = '!'; -} - -_position = state.position; - -if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } -} else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } -} - -if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); -} - -if (isVerbatim) { - state.tag = tagName; - -} else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - -} else if (tagHandle === '!') { - state.tag = '!' + tagName; - -} else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - -} else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); -} - -return true; -} - -function readAnchorProperty(state) { -var _position, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch !== 0x26/* & */) return false; - -if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); -} - -ch = state.input.charCodeAt(++state.position); -_position = state.position; - -while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); -} - -if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); -} - -state.anchor = state.input.slice(_position, state.position); -return true; -} - -function readAlias(state) { -var _position, alias, - ch; - -ch = state.input.charCodeAt(state.position); - -if (ch !== 0x2A/* * */) return false; - -ch = state.input.charCodeAt(++state.position); -_position = state.position; - -while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); -} - -if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); -} - -alias = state.input.slice(_position, state.position); - -if (!state.anchorMap.hasOwnProperty(alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); -} - -state.result = state.anchorMap[alias]; -skipSeparationSpace(state, true, -1); -return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { -var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } -} - -if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } -} - -if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; -} - -if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } -} - -if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only assigned to plain scalars. So, it isn't - // needed to check for 'kind' conformity. - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } -} - -if (state.listener !== null) { - state.listener('close', state); -} -return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { -var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - -state.version = null; -state.checkLineBreaks = state.legacy; -state.tagMap = {}; -state.anchorMap = {}; - -while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } -} - -skipSeparationSpace(state, true, -1); - -if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - -} else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); -} - -composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); -skipSeparationSpace(state, true, -1); - -if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); -} - -state.documents.push(state.result); - -if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; -} - -if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); -} else { - return; -} -} - - -function loadDocuments(input, options) { -input = String(input); -options = options || {}; - -if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } -} - -var state = new State(input, options); - -// Use 0 as string terminator. That significantly simplifies bounds check. -state.input += '\0'; - -while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; -} - -while (state.position < (state.length - 1)) { - readDocument(state); -} - -return state.documents; -} - - -function loadAll(input, iterator, options) { -var documents = loadDocuments(input, options), index, length; - -if (typeof iterator !== 'function') { - return documents; -} - -for (index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); -} -} - - -function load(input, options) { -var documents = loadDocuments(input, options); - -if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; -} else if (documents.length === 1) { - return documents[0]; -} -throw new YAMLException('expected a single document in the stream, but found more'); -} - - -function safeLoadAll(input, output, options) { -if (typeof output === 'function') { - loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} else { - return loadAll(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} -} - - -function safeLoad(input, options) { -return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; - -},{"./common":38,"./exception":40,"./mark":42,"./schema/default_full":45,"./schema/default_safe":46}],42:[function(_dereq_,module,exports){ -'use strict'; - - -var common = _dereq_('./common'); - - -function Mark(name, buffer, position, line, column) { -this.name = name; -this.buffer = buffer; -this.position = position; -this.line = line; -this.column = column; -} - - -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { -var head, start, tail, end, snippet; - -if (!this.buffer) return null; - -indent = indent || 4; -maxLength = maxLength || 75; - -head = ''; -start = this.position; - -while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } -} - -tail = ''; -end = this.position; - -while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } -} - -snippet = this.buffer.slice(start, end); - -return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { -var snippet, where = ''; - -if (this.name) { - where += 'in "' + this.name + '" '; -} - -where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - -if (!compact) { - snippet = this.getSnippet(); - - if (snippet) { - where += ':\n' + snippet; - } -} - -return where; -}; - - -module.exports = Mark; - -},{"./common":38}],43:[function(_dereq_,module,exports){ -'use strict'; - -/*eslint-disable max-len*/ - -var common = _dereq_('./common'); -var YAMLException = _dereq_('./exception'); -var Type = _dereq_('./type'); - - -function compileList(schema, name, result) { -var exclude = []; - -schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); -}); - -schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); - } - }); - - result.push(currentType); -}); - -return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; -}); -} - - -function compileMap(/* lists... */) { -var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; - -function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; -} - -for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); -} -return result; -} - - -function Schema(definition) { -this.include = definition.include || []; -this.implicit = definition.implicit || []; -this.explicit = definition.explicit || []; - -this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } -}); - -this.compiledImplicit = compileList(this, 'implicit', []); -this.compiledExplicit = compileList(this, 'explicit', []); -this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} - - -Schema.DEFAULT = null; - - -Schema.create = function createSchema() { -var schemas, types; - -switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; - - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); -} - -schemas = common.toArray(schemas); -types = common.toArray(types); - -if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); -} - -if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); -} - -return new Schema({ - include: schemas, - explicit: types -}); -}; - - -module.exports = Schema; - -},{"./common":38,"./exception":40,"./type":49}],44:[function(_dereq_,module,exports){ -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - - -'use strict'; - - -var Schema = _dereq_('../schema'); - - -module.exports = new Schema({ -include: [ - _dereq_('./json') -] -}); - -},{"../schema":43,"./json":48}],45:[function(_dereq_,module,exports){ -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. - - -'use strict'; - - -var Schema = _dereq_('../schema'); - - -module.exports = Schema.DEFAULT = new Schema({ -include: [ - _dereq_('./default_safe') -], -explicit: [ - _dereq_('../type/js/undefined'), - _dereq_('../type/js/regexp'), - _dereq_('../type/js/function') -] -}); - -},{"../schema":43,"../type/js/function":54,"../type/js/regexp":55,"../type/js/undefined":56,"./default_safe":46}],46:[function(_dereq_,module,exports){ -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - -'use strict'; - - -var Schema = _dereq_('../schema'); - - -module.exports = new Schema({ -include: [ - _dereq_('./core') -], -implicit: [ - _dereq_('../type/timestamp'), - _dereq_('../type/merge') -], -explicit: [ - _dereq_('../type/binary'), - _dereq_('../type/omap'), - _dereq_('../type/pairs'), - _dereq_('../type/set') -] -}); - -},{"../schema":43,"../type/binary":50,"../type/merge":58,"../type/omap":60,"../type/pairs":61,"../type/set":63,"../type/timestamp":65,"./core":44}],47:[function(_dereq_,module,exports){ -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - -'use strict'; - - -var Schema = _dereq_('../schema'); - - -module.exports = new Schema({ -explicit: [ - _dereq_('../type/str'), - _dereq_('../type/seq'), - _dereq_('../type/map') -] -}); - -},{"../schema":43,"../type/map":57,"../type/seq":62,"../type/str":64}],48:[function(_dereq_,module,exports){ -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - - -'use strict'; - - -var Schema = _dereq_('../schema'); - - -module.exports = new Schema({ -include: [ - _dereq_('./failsafe') -], -implicit: [ - _dereq_('../type/null'), - _dereq_('../type/bool'), - _dereq_('../type/int'), - _dereq_('../type/float') -] -}); - -},{"../schema":43,"../type/bool":51,"../type/float":52,"../type/int":53,"../type/null":59,"./failsafe":47}],49:[function(_dereq_,module,exports){ -'use strict'; - -var YAMLException = _dereq_('./exception'); - -var TYPE_CONSTRUCTOR_OPTIONS = [ -'kind', -'resolve', -'construct', -'instanceOf', -'predicate', -'represent', -'defaultStyle', -'styleAliases' -]; - -var YAML_NODE_KINDS = [ -'scalar', -'sequence', -'mapping' -]; - -function compileStyleAliases(map) { -var result = {}; - -if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); -} - -return result; -} - -function Type(tag, options) { -options = options || {}; - -Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } -}); - -// TODO: Add tag format check. -this.tag = tag; -this.kind = options['kind'] || null; -this.resolve = options['resolve'] || function () { return true; }; -this.construct = options['construct'] || function (data) { return data; }; -this.instanceOf = options['instanceOf'] || null; -this.predicate = options['predicate'] || null; -this.represent = options['represent'] || null; -this.defaultStyle = options['defaultStyle'] || null; -this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - -if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); -} -} - -module.exports = Type; - -},{"./exception":40}],50:[function(_dereq_,module,exports){ -'use strict'; - -/*eslint-disable no-bitwise*/ - -var NodeBuffer; - -try { -// A trick for browserified version, to not include `Buffer` shim -var _require = _dereq_; -NodeBuffer = _require('buffer').Buffer; -} catch (__) {} - -var Type = _dereq_('../type'); - - -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - -function resolveYamlBinary(data) { -if (data === null) return false; - -var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - -// Convert one by one. -for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; -} - -// If there are any bits left, source was corrupted -return (bitlen % 8) === 0; -} - -function constructYamlBinary(data) { -var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - -// Collect by 6*4 bits (3 bytes) - -for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); -} - -// Dump tail - -tailbits = (max % 4) * 6; - -if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); -} else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); -} else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); -} - -// Wrap into Buffer for NodeJS and leave Array for browser -if (NodeBuffer) { - // Support node 6.+ Buffer API when available - return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); -} - -return result; -} - -function representYamlBinary(object /*, style*/) { -var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - -// Convert every three bytes to 4 ASCII characters. - -for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; -} - -// Dump tail - -tail = max % 3; - -if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; -} else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; -} else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; -} - -return result; -} - -function isBinary(object) { -return NodeBuffer && NodeBuffer.isBuffer(object); -} - -module.exports = new Type('tag:yaml.org,2002:binary', { -kind: 'scalar', -resolve: resolveYamlBinary, -construct: constructYamlBinary, -predicate: isBinary, -represent: representYamlBinary -}); - -},{"../type":49}],51:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -function resolveYamlBoolean(data) { -if (data === null) return false; - -var max = data.length; - -return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { -return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { -return Object.prototype.toString.call(object) === '[object Boolean]'; -} - -module.exports = new Type('tag:yaml.org,2002:bool', { -kind: 'scalar', -resolve: resolveYamlBoolean, -construct: constructYamlBoolean, -predicate: isBoolean, -represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } -}, -defaultStyle: 'lowercase' -}); - -},{"../type":49}],52:[function(_dereq_,module,exports){ -'use strict'; - -var common = _dereq_('../common'); -var Type = _dereq_('../type'); - -var YAML_FLOAT_PATTERN = new RegExp( -// 2.5e4, 2.5 and integers -'^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + -// .2e4, .2 -// special case, seems not from spec -'|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + -// 20:59 -'|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + -// .inf -'|[-+]?\\.(?:inf|Inf|INF)' + -// .nan -'|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { -if (data === null) return false; - -if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; -} - -return true; -} - -function constructYamlFloat(data) { -var value, sign, base, digits; - -value = data.replace(/_/g, '').toLowerCase(); -sign = value[0] === '-' ? -1 : 1; -digits = []; - -if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); -} - -if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - -} else if (value === '.nan') { - return NaN; - -} else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); - - value = 0.0; - base = 1; - - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); - - return sign * value; - -} -return sign * parseFloat(value, 10); -} - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { -var res; - -if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } -} else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } -} else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } -} else if (common.isNegativeZero(object)) { - return '-0.0'; -} - -res = object.toString(10); - -// JS stringifier can build scientific format without dots: 5e-100, -// while YAML requres dot: 5.e-100. Fix it with simple hack - -return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { -return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { -kind: 'scalar', -resolve: resolveYamlFloat, -construct: constructYamlFloat, -predicate: isFloat, -represent: representYamlFloat, -defaultStyle: 'lowercase' -}); - -},{"../common":38,"../type":49}],53:[function(_dereq_,module,exports){ -'use strict'; - -var common = _dereq_('../common'); -var Type = _dereq_('../type'); - -function isHexCode(c) { -return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { -return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { -return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { -if (data === null) return false; - -var max = data.length, - index = 0, - hasDigits = false, - ch; - -if (!max) return false; - -ch = data[index]; - -// sign -if (ch === '-' || ch === '+') { - ch = data[++index]; -} - -if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; -} - -// base 10 (except 0) or base 60 - -// value should not start with `_`; -if (ch === '_') return false; - -for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; -} - -// Should have digits and should not end with `_` -if (!hasDigits || ch === '_') return false; - -// if !base60 - done; -if (ch !== ':') return true; - -// base60 almost not used, no needs to optimize -return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} - -function constructYamlInteger(data) { -var value = data, sign = 1, ch, base, digits = []; - -if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); -} - -ch = value[0]; - -if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; -} - -if (value === '0') return 0; - -if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); -} - -if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); - - value = 0; - base = 1; - - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - - return sign * value; - -} - -return sign * parseInt(value, 10); -} - -function isInteger(object) { -return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:int', { -kind: 'scalar', -resolve: resolveYamlInteger, -construct: constructYamlInteger, -predicate: isInteger, -represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } -}, -defaultStyle: 'decimal', -styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] -} -}); - -},{"../common":38,"../type":49}],54:[function(_dereq_,module,exports){ -'use strict'; - -var esprima; - -// Browserified version does not have esprima -// -// 1. For node.js just _dereq_ module as deps -// 2. For browser try to _dereq_ mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { -// workaround to exclude package from browserify list. -var _require = _dereq_; -esprima = _require('esprima'); -} catch (_) { -/*global window */ -if (typeof window !== 'undefined') esprima = window.esprima; -} - -var Type = _dereq_('../../type'); - -function resolveJavascriptFunction(data) { -if (data === null) return false; - -try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; - } - - return true; -} catch (err) { - return false; -} -} - -function constructJavascriptFunction(data) { -/*jslint evil:true*/ - -var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - -if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); -} - -ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); -}); - -body = ast.body[0].expression.body.range; - -// Esprima's ranges include the first '{' and the last '}' characters on -// function expressions. So cut them out. -/*eslint-disable no-new-func*/ -return new Function(params, source.slice(body[0] + 1, body[1] - 1)); -} - -function representJavascriptFunction(object /*, style*/) { -return object.toString(); -} - -function isFunction(object) { -return Object.prototype.toString.call(object) === '[object Function]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/function', { -kind: 'scalar', -resolve: resolveJavascriptFunction, -construct: constructJavascriptFunction, -predicate: isFunction, -represent: representJavascriptFunction -}); - -},{"../../type":49}],55:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../../type'); - -function resolveJavascriptRegExp(data) { -if (data === null) return false; -if (data.length === 0) return false; - -var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - -// if regexp starts with '/' it can have modifiers and must be properly closed -// `/foo/gim` - modifiers tail can be maximum 3 chars -if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; -} - -return true; -} - -function constructJavascriptRegExp(data) { -var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - -// `/foo/gim` - tail can be maximum 4 chars -if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); -} - -return new RegExp(regexp, modifiers); -} - -function representJavascriptRegExp(object /*, style*/) { -var result = '/' + object.source + '/'; - -if (object.global) result += 'g'; -if (object.multiline) result += 'm'; -if (object.ignoreCase) result += 'i'; - -return result; -} - -function isRegExp(object) { -return Object.prototype.toString.call(object) === '[object RegExp]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/regexp', { -kind: 'scalar', -resolve: resolveJavascriptRegExp, -construct: constructJavascriptRegExp, -predicate: isRegExp, -represent: representJavascriptRegExp -}); - -},{"../../type":49}],56:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../../type'); - -function resolveJavascriptUndefined() { -return true; -} - -function constructJavascriptUndefined() { -/*eslint-disable no-undefined*/ -return undefined; -} - -function representJavascriptUndefined() { -return ''; -} - -function isUndefined(object) { -return typeof object === 'undefined'; -} - -module.exports = new Type('tag:yaml.org,2002:js/undefined', { -kind: 'scalar', -resolve: resolveJavascriptUndefined, -construct: constructJavascriptUndefined, -predicate: isUndefined, -represent: representJavascriptUndefined -}); - -},{"../../type":49}],57:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -module.exports = new Type('tag:yaml.org,2002:map', { -kind: 'mapping', -construct: function (data) { return data !== null ? data : {}; } -}); - -},{"../type":49}],58:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -function resolveYamlMerge(data) { -return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { -kind: 'scalar', -resolve: resolveYamlMerge -}); - -},{"../type":49}],59:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -function resolveYamlNull(data) { -if (data === null) return true; - -var max = data.length; - -return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { -return null; -} - -function isNull(object) { -return object === null; -} - -module.exports = new Type('tag:yaml.org,2002:null', { -kind: 'scalar', -resolve: resolveYamlNull, -construct: constructYamlNull, -predicate: isNull, -represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } -}, -defaultStyle: 'lowercase' -}); - -},{"../type":49}],60:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { -if (data === null) return true; - -var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - -for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; -} - -return true; -} - -function constructYamlOmap(data) { -return data !== null ? data : []; -} - -module.exports = new Type('tag:yaml.org,2002:omap', { -kind: 'sequence', -resolve: resolveYamlOmap, -construct: constructYamlOmap -}); - -},{"../type":49}],61:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { -if (data === null) return true; - -var index, length, pair, keys, result, - object = data; - -result = new Array(object.length); - -for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; -} - -return true; -} - -function constructYamlPairs(data) { -if (data === null) return []; - -var index, length, pair, keys, result, - object = data; - -result = new Array(object.length); - -for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; -} - -return result; -} - -module.exports = new Type('tag:yaml.org,2002:pairs', { -kind: 'sequence', -resolve: resolveYamlPairs, -construct: constructYamlPairs -}); - -},{"../type":49}],62:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -module.exports = new Type('tag:yaml.org,2002:seq', { -kind: 'sequence', -construct: function (data) { return data !== null ? data : []; } -}); - -},{"../type":49}],63:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -function resolveYamlSet(data) { -if (data === null) return true; - -var key, object = data; - -for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } -} - -return true; -} - -function constructYamlSet(data) { -return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { -kind: 'mapping', -resolve: resolveYamlSet, -construct: constructYamlSet -}); - -},{"../type":49}],64:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -module.exports = new Type('tag:yaml.org,2002:str', { -kind: 'scalar', -construct: function (data) { return data !== null ? data : ''; } -}); - -},{"../type":49}],65:[function(_dereq_,module,exports){ -'use strict'; - -var Type = _dereq_('../type'); - -var YAML_DATE_REGEXP = new RegExp( -'^([0-9][0-9][0-9][0-9])' + // [1] year -'-([0-9][0-9])' + // [2] month -'-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( -'^([0-9][0-9][0-9][0-9])' + // [1] year -'-([0-9][0-9]?)' + // [2] month -'-([0-9][0-9]?)' + // [3] day -'(?:[Tt]|[ \\t]+)' + // ... -'([0-9][0-9]?)' + // [4] hour -':([0-9][0-9])' + // [5] minute -':([0-9][0-9])' + // [6] second -'(?:\\.([0-9]*))?' + // [7] fraction -'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour -'(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { -if (data === null) return false; -if (YAML_DATE_REGEXP.exec(data) !== null) return true; -if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; -return false; -} - -function constructYamlTimestamp(data) { -var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - -match = YAML_DATE_REGEXP.exec(data); -if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - -if (match === null) throw new Error('Date resolve error'); - -// match: [1] year [2] month [3] day - -year = +(match[1]); -month = +(match[2]) - 1; // JS month starts with 0 -day = +(match[3]); - -if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); -} - -// match: [4] hour [5] minute [6] second [7] fraction - -hour = +(match[4]); -minute = +(match[5]); -second = +(match[6]); - -if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; -} - -// match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - -if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; -} - -date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - -if (delta) date.setTime(date.getTime() - delta); - -return date; -} - -function representYamlTimestamp(object /*, style*/) { -return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { -kind: 'scalar', -resolve: resolveYamlTimestamp, -construct: constructYamlTimestamp, -instanceOf: Date, -represent: representYamlTimestamp -}); - -},{"../type":49}],66:[function(_dereq_,module,exports){ -/** -* Helpers. -*/ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** -* Parse or format the given `val`. -* -* Options: -* -* - `long` verbose formatting [false] -* -* @param {String|Number} val -* @param {Object} [options] -* @throws {Error} throw an error if val is not a non-empty string or a number -* @return {String|Number} -* @api public -*/ - -module.exports = function(val, options) { -options = options || {}; -var type = typeof val; -if (type === 'string' && val.length > 0) { - return parse(val); -} else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); -} -throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) -); -}; - -/** -* Parse the given `str` and return milliseconds. -* -* @param {String} str -* @return {Number} -* @api private -*/ - -function parse(str) { -str = String(str); -if (str.length > 100) { - return; -} -var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str -); -if (!match) { - return; -} -var n = parseFloat(match[1]); -var type = (match[2] || 'ms').toLowerCase(); -switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; -} -} - -/** -* Short format for `ms`. -* -* @param {Number} ms -* @return {String} -* @api private -*/ - -function fmtShort(ms) { -if (ms >= d) { - return Math.round(ms / d) + 'd'; -} -if (ms >= h) { - return Math.round(ms / h) + 'h'; -} -if (ms >= m) { - return Math.round(ms / m) + 'm'; -} -if (ms >= s) { - return Math.round(ms / s) + 's'; -} -return ms + 'ms'; -} - -/** -* Long format for `ms`. -* -* @param {Number} ms -* @return {String} -* @api private -*/ - -function fmtLong(ms) { -return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** -* Pluralization helper. -*/ - -function plural(ms, n, name) { -if (ms < n) { - return; -} -if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; -} -return Math.ceil(ms / n) + ' ' + name + 's'; -} - -},{}],67:[function(_dereq_,module,exports){ -'use strict'; - -var format = _dereq_('format-util'); -var slice = Array.prototype.slice; -var protectedProperties = ['name', 'message', 'stack']; -var errorPrototypeProperties = [ -'name', 'message', 'description', 'number', 'code', 'fileName', 'lineNumber', 'columnNumber', -'sourceURL', 'line', 'column', 'stack' -]; - -module.exports = create(Error); -module.exports.error = create(Error); -module.exports.eval = create(EvalError); -module.exports.range = create(RangeError); -module.exports.reference = create(ReferenceError); -module.exports.syntax = create(SyntaxError); -module.exports.type = create(TypeError); -module.exports.uri = create(URIError); -module.exports.formatter = format; - -/** -* Creates a new {@link ono} function that creates the given Error class. -* -* @param {Class} Klass - The Error subclass to create -* @returns {ono} -*/ -function create (Klass) { -/** - * @param {Error} [err] - The original error, if any - * @param {object} [props] - An object whose properties will be added to the error object - * @param {string} [message] - The error message. May contain {@link util#format} placeholders - * @param {...*} [params] - Parameters that map to the `message` placeholders - * @returns {Error} - */ -return function onoFactory (err, props, message, params) { // eslint-disable-line no-unused-vars - var formatArgs = []; - var formattedMessage = ''; - - // Determine which arguments were actually specified - if (typeof err === 'string') { - formatArgs = slice.call(arguments); - err = props = undefined; - } - else if (typeof props === 'string') { - formatArgs = slice.call(arguments, 1); - props = undefined; - } - else if (typeof message === 'string') { - formatArgs = slice.call(arguments, 2); - } - - // If there are any format arguments, then format the error message - if (formatArgs.length > 0) { - formattedMessage = module.exports.formatter.apply(null, formatArgs); - } - - if (err && err.message) { - // The inner-error's message will be added to the new message - formattedMessage += (formattedMessage ? ' \n' : '') + err.message; - } - - // Create the new error - // NOTE: DON'T move this to a separate function! We don't want to pollute the stack trace - var newError = new Klass(formattedMessage); - - // Extend the new error with the additional properties - extendError(newError, err); // Copy properties of the original error - extendToJSON(newError); // Replace the original toJSON method - extend(newError, props); // Copy custom properties, possibly including a custom toJSON method - - return newError; -}; -} - -/** -* Extends the targetError with the properties of the source error. -* -* @param {Error} targetError - The error object to extend -* @param {?Error} sourceError - The source error object, if any -*/ -function extendError (targetError, sourceError) { -extendStack(targetError, sourceError); -extend(targetError, sourceError); -} - -/** -* JavaScript engines differ in how errors are serialized to JSON - especially when it comes -* to custom error properties and stack traces. So we add our own toJSON method that ALWAYS -* outputs every property of the error. -*/ -function extendToJSON (error) { -error.toJSON = errorToJSON; - -// Also add an inspect() method, for compatibility with Node.js' `util.inspect()` method -error.inspect = errorToString; -} - -/** -* Extends the target object with the properties of the source object. -* -* @param {object} target - The object to extend -* @param {?source} source - The object whose properties are copied -*/ -function extend (target, source) { -if (source && typeof source === 'object') { - var keys = Object.keys(source); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - - // Don't copy "protected" properties, since they have special meaning/behavior - // and are set by the onoFactory function - if (protectedProperties.indexOf(key) >= 0) { - continue; - } - - try { - target[key] = source[key]; - } - catch (e) { - // This property is read-only, so it can't be copied - } - } -} -} - -/** -* Custom JSON serializer for Error objects. -* Returns all built-in error properties, as well as extended properties. -* -* @returns {object} -*/ -function errorToJSON () { -var json = {}; - -// Get all the properties of this error -var keys = Object.keys(this); - -// Also include properties from the Error prototype -keys = keys.concat(errorPrototypeProperties); - -for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = this[key]; - var type = typeof value; - if (type !== 'undefined' && type !== 'function') { - json[key] = value; - } -} - -return json; -} - -/** -* Serializes Error objects as human-readable JSON strings for debugging/logging purposes. -* -* @returns {string} -*/ -function errorToString () { -return JSON.stringify(this, null, 2).replace(/\\n/g, '\n'); -} - -/** -* Extend the error stack to include its cause -* -* @param {Error} targetError -* @param {Error} sourceError -*/ -function extendStack (targetError, sourceError) { -if (hasLazyStack(targetError)) { - if (sourceError) { - lazyJoinStacks(targetError, sourceError); - } - else { - lazyPopStack(targetError); - } -} -else { - if (sourceError) { - targetError.stack = joinStacks(targetError.stack, sourceError.stack); - } - else { - targetError.stack = popStack(targetError.stack); - } -} -} - -/** -* Appends the original {@link Error#stack} property to the new Error's stack. -* -* @param {string} newStack -* @param {string} originalStack -* @returns {string} -*/ -function joinStacks (newStack, originalStack) { -newStack = popStack(newStack); - -if (newStack && originalStack) { - return newStack + '\n\n' + originalStack; -} -else { - return newStack || originalStack; -} -} - -/** -* Removes Ono from the stack, so that the stack starts at the original error location -* -* @param {string} stack -* @returns {string} -*/ -function popStack (stack) { -if (stack) { - var lines = stack.split('\n'); - - if (lines.length < 2) { - // The stack only has one line, so there's nothing we can remove - return stack; - } - - // Find the `onoFactory` call in the stack, and remove it - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.indexOf('onoFactory') >= 0) { - lines.splice(i, 1); - return lines.join('\n'); - } - } - - // If we get here, then the stack doesn't contain a call to `onoFactory`. - // This may be due to minification or some optimization of the JS engine. - // So just return the stack as-is. - return stack; -} -} - -/** -* Does a one-time determination of whether this JavaScript engine -* supports lazy `Error.stack` properties. -*/ -var supportsLazyStack = (function () { -return !!( - // ES5 property descriptors must be supported - Object.getOwnPropertyDescriptor && Object.defineProperty && - - // Chrome on Android doesn't support lazy stacks :( - (typeof navigator === 'undefined' || !/Android/.test(navigator.userAgent)) -); -}()); - -/** -* Does this error have a lazy stack property? -* -* @param {Error} err -* @returns {boolean} -*/ -function hasLazyStack (err) { -if (!supportsLazyStack) { - return false; -} - -var descriptor = Object.getOwnPropertyDescriptor(err, 'stack'); -if (!descriptor) { - return false; -} -return typeof descriptor.get === 'function'; -} - -/** -* Calls {@link joinStacks} lazily, when the {@link Error#stack} property is accessed. -* -* @param {Error} targetError -* @param {Error} sourceError -*/ -function lazyJoinStacks (targetError, sourceError) { -var targetStack = Object.getOwnPropertyDescriptor(targetError, 'stack'); - -Object.defineProperty(targetError, 'stack', { - get: function () { - return joinStacks(targetStack.get.apply(targetError), sourceError.stack); - }, - enumerable: false, - configurable: true -}); -} - -/** -* Calls {@link popStack} lazily, when the {@link Error#stack} property is accessed. -* -* @param {Error} error -*/ -function lazyPopStack (error) { -var targetStack = Object.getOwnPropertyDescriptor(error, 'stack'); - -Object.defineProperty(error, 'stack', { - get: function () { - return popStack(targetStack.get.apply(error)); - }, - enumerable: false, - configurable: true -}); -} - -},{"format-util":30}],68:[function(_dereq_,module,exports){ -(function (process){ -'use strict'; - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { -module.exports = nextTick; -} else { -module.exports = process.nextTick; -} - -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); - }); -} -} - -}).call(this,_dereq_('_process')) - -},{"_process":69}],69:[function(_dereq_,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],70:[function(_dereq_,module,exports){ -(function (global){ -/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { - -/** Detect free variables */ -var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; -var freeModule = typeof module == 'object' && module && - !module.nodeType && module; -var freeGlobal = typeof global == 'object' && global; -if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal -) { - root = freeGlobal; -} - -/** - * The `punycode` object. - * @name punycode - * @type Object - */ -var punycode, - -/** Highest positive signed 32-bit float value */ -maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - -/** Bootstring parameters */ -base = 36, -tMin = 1, -tMax = 26, -skew = 38, -damp = 700, -initialBias = 72, -initialN = 128, // 0x80 -delimiter = '-', // '\x2D' - -/** Regular expressions */ -regexPunycode = /^xn--/, -regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars -regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - -/** Error messages */ -errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}, - -/** Convenience shortcuts */ -baseMinusTMin = base - tMin, -floor = Math.floor, -stringFromCharCode = String.fromCharCode, - -/** Temporary variable */ -key; - -/*--------------------------------------------------------------------------*/ - -/** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ -function error(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 length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; -} - -/** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ -function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; -} - -/** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ -function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} - -/** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ -function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); -} - -/** - * 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. - */ -function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; -} - -/** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ -function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); -} - -/** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ -function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); -} - -/** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ -function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // 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. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); -} - -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++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. - */ -function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); -} - -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); -} - -/*--------------------------------------------------------------------------*/ - -/** Define the public API */ -punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.4.1', - /** - * 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 -}; - -/** Expose `punycode` */ -// Some AMD build optimizers, like r.js, check for specific condition patterns -// like the following: -if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd -) { - define('punycode', function() { - return punycode; - }); -} else if (freeExports && freeModule) { - if (module.exports == freeExports) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { - // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } -} else { - // in Rhino or a web browser - root.punycode = punycode; -} - -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],71:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { -return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { -sep = sep || '&'; -eq = eq || '='; -var obj = {}; - -if (typeof qs !== 'string' || qs.length === 0) { - return obj; -} - -var regexp = /\+/g; -qs = qs.split(sep); - -var maxKeys = 1000; -if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; -} - -var len = qs.length; -// maxKeys <= 0 means that we should not limit keys count -if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; -} - -for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } -} - -return obj; -}; - -var isArray = Array.isArray || function (xs) { -return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],72:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { -switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; -} -}; - -module.exports = function(obj, sep, eq, name) { -sep = sep || '&'; -eq = eq || '='; -if (obj === null) { - obj = undefined; -} - -if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - -} - -if (!name) return ''; -return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -var isArray = Array.isArray || function (xs) { -return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -function map (xs, f) { -if (xs.map) return xs.map(f); -var res = []; -for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); -} -return res; -} - -var objectKeys = Object.keys || function (obj) { -var res = []; -for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); -} -return res; -}; - -},{}],73:[function(_dereq_,module,exports){ -'use strict'; - -exports.decode = exports.parse = _dereq_('./decode'); -exports.encode = exports.stringify = _dereq_('./encode'); - -},{"./decode":71,"./encode":72}],74:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// 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. - -'use strict'; - -/**/ - -var processNextTick = _dereq_('process-nextick-args'); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { -var keys = []; -for (var key in obj) { - keys.push(key); -}return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -var Readable = _dereq_('./_stream_readable'); -var Writable = _dereq_('./_stream_writable'); - -util.inherits(Duplex, Readable); - -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { -var method = keys[v]; -if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} - -function Duplex(options) { -if (!(this instanceof Duplex)) return new Duplex(options); - -Readable.call(this, options); -Writable.call(this, options); - -if (options && options.readable === false) this.readable = false; - -if (options && options.writable === false) this.writable = false; - -this.allowHalfOpen = true; -if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - -this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { -// if we allow half-open state, or if the writable side ended, -// then we're ok. -if (this.allowHalfOpen || this._writableState.ended) return; - -// no more data can be written. -// But allow more writes to happen in this tick. -processNextTick(onEndNT, this); -} - -function onEndNT(self) { -self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { -get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; -}, -set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; -} -}); - -Duplex.prototype._destroy = function (err, cb) { -this.push(null); -this.end(); - -processNextTick(cb, err); -}; - -function forEach(xs, f) { -for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); -} -} -},{"./_stream_readable":76,"./_stream_writable":78,"core-util-is":26,"inherits":33,"process-nextick-args":68}],75:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; - -module.exports = PassThrough; - -var Transform = _dereq_('./_stream_transform'); - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { -if (!(this instanceof PassThrough)) return new PassThrough(options); - -Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { -cb(null, chunk); -}; -},{"./_stream_transform":77,"core-util-is":26,"inherits":33}],76:[function(_dereq_,module,exports){ -(function (process,global){ -// 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. - -'use strict'; - -/**/ - -var processNextTick = _dereq_('process-nextick-args'); -/**/ - -module.exports = Readable; - -/**/ -var isArray = _dereq_('isarray'); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = _dereq_('events').EventEmitter; - -var EElistenerCount = function (emitter, type) { -return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = _dereq_('./internal/streams/stream'); -/**/ - -// TODO(bmeurer): Change this back to const once hole checks are -// properly optimized away early in Ignition+TurboFan. -/**/ -var Buffer = _dereq_('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { -return Buffer.from(chunk); -} -function _isUint8Array(obj) { -return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -/**/ -var debugUtil = _dereq_('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { -debug = debugUtil.debuglog('stream'); -} else { -debug = function () {}; -} -/**/ - -var BufferList = _dereq_('./internal/streams/BufferList'); -var destroyImpl = _dereq_('./internal/streams/destroy'); -var StringDecoder; - -util.inherits(Readable, Stream); - -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { -// Sadly this is not cacheable as some libraries bundle their own -// event emitter implementation with them. -if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); -} else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} -} - -function ReadableState(options, stream) { -Duplex = Duplex || _dereq_('./_stream_duplex'); - -options = options || {}; - -// object stream flag. Used to make read(n) ignore n and to -// make all the buffer merging and length checks go away -this.objectMode = !!options.objectMode; - -if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - -// the point at which it stops calling _read() to fill the buffer -// Note: 0 is a valid value, means "don't call _read preemptively ever" -var hwm = options.highWaterMark; -var defaultHwm = this.objectMode ? 16 : 16 * 1024; -this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - -// cast to ints. -this.highWaterMark = Math.floor(this.highWaterMark); - -// A linked list is used to store data chunks instead of an array because the -// linked list can remove elements from the beginning faster than -// array.shift() -this.buffer = new BufferList(); -this.length = 0; -this.pipes = null; -this.pipesCount = 0; -this.flowing = null; -this.ended = false; -this.endEmitted = false; -this.reading = false; - -// a flag to be able to tell if the event 'readable'/'data' is emitted -// immediately, or on a later tick. We set this to true at first, because -// any actions that shouldn't happen until "later" should generally also -// not happen before the first read call. -this.sync = true; - -// whenever we return null, then we set a flag to say -// that we're awaiting a 'readable' event emission. -this.needReadable = false; -this.emittedReadable = false; -this.readableListening = false; -this.resumeScheduled = false; - -// has it been destroyed -this.destroyed = false; - -// Crypto is kind of old and crusty. Historically, its default string -// encoding is 'binary' so we have to make this configurable. -// Everything else in the universe uses 'utf8', though. -this.defaultEncoding = options.defaultEncoding || 'utf8'; - -// the number of writers that are awaiting a drain event in .pipe()s -this.awaitDrain = 0; - -// if true, a maybeReadMore has been scheduled -this.readingMore = false; - -this.decoder = null; -this.encoding = null; -if (options.encoding) { - if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; -} -} - -function Readable(options) { -Duplex = Duplex || _dereq_('./_stream_duplex'); - -if (!(this instanceof Readable)) return new Readable(options); - -this._readableState = new ReadableState(options, this); - -// legacy -this.readable = true; - -if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; -} - -Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { -get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; -}, -set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; -} -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { -this.push(null); -cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { -var state = this._readableState; -var skipChunkCheck; - -if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } -} else { - skipChunkCheck = true; -} - -return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { -return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { -var state = stream._readableState; -if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); -} else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } -} - -return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { -if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); -} else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); -} -maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { -var er; -if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); -} -return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { -return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { -return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { -if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder; -this._readableState.decoder = new StringDecoder(enc); -this._readableState.encoding = enc; -return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { -if (n >= MAX_HWM) { - n = MAX_HWM; -} else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; -} -return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { -if (n <= 0 || state.length === 0 && state.ended) return 0; -if (state.objectMode) return 1; -if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; -} -// If we're asking for more than the current hwm, then raise the hwm. -if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); -if (n <= state.length) return n; -// Don't have enough -if (!state.ended) { - state.needReadable = true; - return 0; -} -return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { -debug('read', n); -n = parseInt(n, 10); -var state = this._readableState; -var nOrig = n; - -if (n !== 0) state.emittedReadable = false; - -// if we're doing read(0) to trigger a readable event, but we -// already have a bunch of data in the buffer, then just trigger -// the 'readable' event and move on. -if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; -} - -n = howMuchToRead(n, state); - -// if we've ended, and we're now clear, then finish it up. -if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; -} - -// All the actual chunk generation logic needs to be -// *below* the call to _read. The reason is that in certain -// synthetic stream cases, such as passthrough streams, _read -// may be a completely synchronous operation which may change -// the state of the read buffer, providing enough data when -// before there was *not* enough. -// -// So, the steps are: -// 1. Figure out what the state of things will be after we do -// a read from the buffer. -// -// 2. If that resulting state will trigger a _read, then call _read. -// Note that this may be asynchronous, or synchronous. Yes, it is -// deeply ugly to write APIs this way, but that still doesn't mean -// that the Readable class should behave improperly, as streams are -// designed to be sync/async agnostic. -// Take note if the _read call is sync or async (ie, if the read call -// has returned yet), so that we know whether or not it's safe to emit -// 'readable' etc. -// -// 3. Actually pull the requested chunks out of the buffer and return. - -// if we need a readable event, then we need to do some reading. -var doRead = state.needReadable; -debug('need readable', doRead); - -// if we currently have less than the highWaterMark, then also read some -if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); -} - -// however, if we've ended, then there's no point, and if we're already -// reading, then it's unnecessary. -if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); -} else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); -} - -var ret; -if (n > 0) ret = fromList(n, state);else ret = null; - -if (ret === null) { - state.needReadable = true; - n = 0; -} else { - state.length -= n; -} - -if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); -} - -if (ret !== null) this.emit('data', ret); - -return ret; -}; - -function onEofChunk(stream, state) { -if (state.ended) return; -if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } -} -state.ended = true; - -// emit 'readable' now to make sure it gets picked up. -emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { -var state = stream._readableState; -state.needReadable = false; -if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); -} -} - -function emitReadable_(stream) { -debug('emit readable'); -stream.emit('readable'); -flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { -if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); -} -} - -function maybeReadMore_(stream, state) { -var len = state.length; -while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; -} -state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { -this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { -var src = this; -var state = this._readableState; - -switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; -} -state.pipesCount += 1; -debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - -var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - -var endFn = doEnd ? onend : unpipe; -if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - -dest.on('unpipe', onunpipe); -function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } -} - -function onend() { - debug('onend'); - dest.end(); -} - -// when the dest drains, it reduces the awaitDrain counter -// on the source. This would be more elegant with a .once() -// handler in flow(), but adding and removing repeatedly is -// too slow. -var ondrain = pipeOnDrain(src); -dest.on('drain', ondrain); - -var cleanedUp = false; -function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); -} - -// If the user pushes more data while we're writing to dest then we'll end up -// in ondata again. However, we only want to increase awaitDrain once because -// dest will only emit one 'drain' event for the multiple writes. -// => Introduce a guard on increasing awaitDrain. -var increasedAwaitDrain = false; -src.on('data', ondata); -function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } -} - -// if the dest has an error, then stop piping into it. -// however, don't suppress the throwing behavior for this. -function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); -} - -// Make sure our error handler is attached before userland ones. -prependListener(dest, 'error', onerror); - -// Both close and finish should trigger unpipe, but only once. -function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); -} -dest.once('close', onclose); -function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); -} -dest.once('finish', onfinish); - -function unpipe() { - debug('unpipe'); - src.unpipe(dest); -} - -// tell the dest that it's being piped to -dest.emit('pipe', src); - -// start the flow if it hasn't been started already. -if (!state.flowing) { - debug('pipe resume'); - src.resume(); -} - -return dest; -}; - -function pipeOnDrain(src) { -return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } -}; -} - -Readable.prototype.unpipe = function (dest) { -var state = this._readableState; -var unpipeInfo = { hasUnpiped: false }; - -// if we're not piping anywhere, then do nothing. -if (state.pipesCount === 0) return this; - -// just one destination. most common case. -if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; -} - -// slow case. multiple pipe destinations. - -if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; -} - -// try to find the right one. -var index = indexOf(state.pipes, dest); -if (index === -1) return this; - -state.pipes.splice(index, 1); -state.pipesCount -= 1; -if (state.pipesCount === 1) state.pipes = state.pipes[0]; - -dest.emit('unpipe', this, unpipeInfo); - -return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { -var res = Stream.prototype.on.call(this, ev, fn); - -if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); -} else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } -} - -return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { -debug('readable nexttick read 0'); -self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { -var state = this._readableState; -if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); -} -return this; -}; - -function resume(stream, state) { -if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); -} -} - -function resume_(stream, state) { -if (!state.reading) { - debug('resume read 0'); - stream.read(0); -} - -state.resumeScheduled = false; -state.awaitDrain = 0; -stream.emit('resume'); -flow(stream); -if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { -debug('call pause flowing=%j', this._readableState.flowing); -if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); -} -return this; -}; - -function flow(stream) { -var state = stream._readableState; -debug('flow', state.flowing); -while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { -var state = this._readableState; -var paused = false; - -var self = this; -stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.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 = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } -}); - -// proxy all the other methods. -// important when wrapping filters and duplexes. -for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } -} - -// proxy certain important events. -for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); -} - -// when we try to consume some more bytes, simply unpause the -// underlying stream. -self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } -}; - -return self; -}; - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { -// nothing buffered -if (state.length === 0) return null; - -var ret; -if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); -} else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); -} - -return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { -var ret; -if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); -} else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); -} else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); -} -return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { -var p = list.head; -var c = 1; -var ret = p.data; -n -= ret.length; -while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; -} -list.length -= c; -return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { -var ret = Buffer.allocUnsafe(n); -var p = list.head; -var c = 1; -p.data.copy(ret); -n -= p.data.length; -while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; -} -list.length -= c; -return ret; -} - -function endReadable(stream) { -var state = stream._readableState; - -// If we get here before consuming all the bytes, then that is a -// bug in node. Should never happen. -if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - -if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); -} -} - -function endReadableNT(state, stream) { -// Check that we didn't get one last unshift. -if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); -} -} - -function forEach(xs, f) { -for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); -} -} - -function indexOf(xs, x) { -for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; -} -return -1; -} -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./_stream_duplex":74,"./internal/streams/BufferList":79,"./internal/streams/destroy":80,"./internal/streams/stream":81,"_process":69,"core-util-is":26,"events":29,"inherits":33,"isarray":35,"process-nextick-args":68,"safe-buffer":83,"string_decoder/":88,"util":22}],77:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// 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. - -'use strict'; - -module.exports = Transform; - -var Duplex = _dereq_('./_stream_duplex'); - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -util.inherits(Transform, Duplex); - -function TransformState(stream) { -this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); -}; - -this.needTransform = false; -this.transforming = false; -this.writecb = null; -this.writechunk = null; -this.writeencoding = null; -} - -function afterTransform(stream, er, data) { -var ts = stream._transformState; -ts.transforming = false; - -var cb = ts.writecb; - -if (!cb) { - return stream.emit('error', new Error('write callback called multiple times')); -} - -ts.writechunk = null; -ts.writecb = null; - -if (data !== null && data !== undefined) stream.push(data); - -cb(er); - -var rs = stream._readableState; -rs.reading = false; -if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); -} -} - -function Transform(options) { -if (!(this instanceof Transform)) return new Transform(options); - -Duplex.call(this, options); - -this._transformState = new TransformState(this); - -var stream = this; - -// start out asking for a readable event once data is transformed. -this._readableState.needReadable = true; - -// we have implemented the _read method, and done the other things -// that Readable wants before the first _read call, so unset the -// sync guard flag. -this._readableState.sync = false; - -if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; -} - -// When the writable side finishes, then flush out anything remaining. -this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); -}); -} - -Transform.prototype.push = function (chunk, encoding) { -this._transformState.needTransform = false; -return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { -throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { -var ts = this._transformState; -ts.writecb = cb; -ts.writechunk = chunk; -ts.writeencoding = encoding; -if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); -} -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { -var ts = this._transformState; - -if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); -} else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; -} -}; - -Transform.prototype._destroy = function (err, cb) { -var _this = this; - -Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this.emit('close'); -}); -}; - -function done(stream, er, data) { -if (er) return stream.emit('error', er); - -if (data !== null && data !== undefined) stream.push(data); - -// if there's nothing in the write buffer, then that means -// that nothing more will ever be provided -var ws = stream._writableState; -var ts = stream._transformState; - -if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - -if (ts.transforming) throw new Error('Calling transform done when still transforming'); - -return stream.push(null); -} -},{"./_stream_duplex":74,"core-util-is":26,"inherits":33}],78:[function(_dereq_,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - -'use strict'; - -/**/ - -var processNextTick = _dereq_('process-nextick-args'); -/**/ - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { -this.chunk = chunk; -this.encoding = encoding; -this.callback = cb; -this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { -var _this = this; - -this.next = null; -this.entry = null; -this.finish = function () { - onCorkedFinish(_this, state); -}; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = _dereq_('core-util-is'); -util.inherits = _dereq_('inherits'); -/**/ - -/**/ -var internalUtil = { -deprecate: _dereq_('util-deprecate') -}; -/**/ - -/**/ -var Stream = _dereq_('./internal/streams/stream'); -/**/ - -/**/ -var Buffer = _dereq_('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { -return Buffer.from(chunk); -} -function _isUint8Array(obj) { -return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - -var destroyImpl = _dereq_('./internal/streams/destroy'); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { -Duplex = Duplex || _dereq_('./_stream_duplex'); - -options = options || {}; - -// object stream flag to indicate whether or not this stream -// contains buffers or objects. -this.objectMode = !!options.objectMode; - -if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - -// the point at which write() starts returning false -// Note: 0 is a valid value, means that we always return false if -// the entire buffer is not flushed immediately on write() -var hwm = options.highWaterMark; -var defaultHwm = this.objectMode ? 16 : 16 * 1024; -this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - -// cast to ints. -this.highWaterMark = Math.floor(this.highWaterMark); - -// if _final has been called -this.finalCalled = false; - -// drain event flag. -this.needDrain = false; -// at the start of calling end() -this.ending = false; -// when end() has been called, and returned -this.ended = false; -// when 'finish' is emitted -this.finished = false; - -// has it been destroyed -this.destroyed = false; - -// should we decode strings into buffers before passing to _write? -// this is here so that some node-core streams can optimize string -// handling at a lower level. -var noDecode = options.decodeStrings === false; -this.decodeStrings = !noDecode; - -// Crypto is kind of old and crusty. Historically, its default string -// encoding is 'binary' so we have to make this configurable. -// Everything else in the universe uses 'utf8', though. -this.defaultEncoding = options.defaultEncoding || 'utf8'; - -// not an actual buffer we keep track of, but a measurement -// of how much we're waiting to get pushed to some underlying -// socket or file. -this.length = 0; - -// a flag to see when we're in the middle of a write. -this.writing = false; - -// when true all writes will be buffered until .uncork() call -this.corked = 0; - -// a flag to be able to tell if the onwrite cb is called immediately, -// or on a later tick. We set this to true at first, because any -// actions that shouldn't happen until "later" should generally also -// not happen before the first write call. -this.sync = true; - -// a flag to know if we're processing previously buffered items, which -// may call the _write() callback in the same tick, so that we don't -// end up in an overlapped onwrite situation. -this.bufferProcessing = false; - -// the callback that's passed to _write(chunk,cb) -this.onwrite = function (er) { - onwrite(stream, er); -}; - -// the callback that the user supplies to write(chunk,encoding,cb) -this.writecb = null; - -// the amount that is being written when _write is called. -this.writelen = 0; - -this.bufferedRequest = null; -this.lastBufferedRequest = null; - -// number of pending user-supplied write callbacks -// this must be 0 before 'finish' can be emitted -this.pendingcb = 0; - -// emit prefinish if the only thing we're waiting for is _write cbs -// This is relevant for synchronous Transform streams -this.prefinished = false; - -// True if the error was already emitted and should not be thrown again -this.errorEmitted = false; - -// count buffered requests -this.bufferedRequestCount = 0; - -// allocate the first CorkedRequest, there is always -// one allocated and free to use, and we maintain at most two -this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { -var current = this.bufferedRequest; -var out = []; -while (current) { - out.push(current); - current = current.next; -} -return out; -}; - -(function () { -try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); -} catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { -realHasInstance = Function.prototype[Symbol.hasInstance]; -Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - - return object && object._writableState instanceof WritableState; - } -}); -} else { -realHasInstance = function (object) { - return object instanceof this; -}; -} - -function Writable(options) { -Duplex = Duplex || _dereq_('./_stream_duplex'); - -// Writable ctor is applied to Duplexes, too. -// `realHasInstance` is necessary because using plain `instanceof` -// would return false, as no `_writableState` property is attached. - -// Trying to use the custom `instanceof` for Writable here will also break the -// Node.js LazyTransform implementation, which has a non-trivial getter for -// `_writableState` that would lead to infinite recursion. -if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); -} - -this._writableState = new WritableState(options, this); - -// legacy. -this.writable = true; - -if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - - if (typeof options.final === 'function') this._final = options.final; -} - -Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { -this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { -var er = new Error('write after end'); -// TODO: defer error events consistently everywhere, not just the cb -stream.emit('error', er); -processNextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { -var valid = true; -var er = false; - -if (chunk === null) { - er = new TypeError('May not write null values to stream'); -} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); -} -if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; -} -return valid; -} - -Writable.prototype.write = function (chunk, encoding, cb) { -var state = this._writableState; -var ret = false; -var isBuf = _isUint8Array(chunk) && !state.objectMode; - -if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); -} - -if (typeof encoding === 'function') { - cb = encoding; - encoding = null; -} - -if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - -if (typeof cb !== 'function') cb = nop; - -if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); -} - -return ret; -}; - -Writable.prototype.cork = function () { -var state = this._writableState; - -state.corked++; -}; - -Writable.prototype.uncork = function () { -var state = this._writableState; - -if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); -} -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { -// node::ParseEncoding() requires lower case. -if (typeof encoding === 'string') encoding = encoding.toLowerCase(); -if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); -this._writableState.defaultEncoding = encoding; -return this; -}; - -function decodeChunk(state, chunk, encoding) { -if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); -} -return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { -if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } -} -var len = state.objectMode ? 1 : chunk.length; - -state.length += len; - -var ret = state.length < state.highWaterMark; -// we must ensure that previous needDrain will not be reset to false. -if (!ret) state.needDrain = true; - -if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; -} else { - doWrite(stream, state, false, len, chunk, encoding, cb); -} - -return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { -state.writelen = len; -state.writecb = cb; -state.writing = true; -state.sync = true; -if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); -state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { ---state.pendingcb; - -if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - processNextTick(cb, er); - // this can emit finish, and it will always happen - // after error - processNextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); -} -} - -function onwriteStateUpdate(state) { -state.writing = false; -state.writecb = null; -state.length -= state.writelen; -state.writelen = 0; -} - -function onwrite(stream, er) { -var state = stream._writableState; -var sync = state.sync; -var cb = state.writecb; - -onwriteStateUpdate(state); - -if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } -} -} - -function afterWrite(stream, state, finished, cb) { -if (!finished) onwriteDrain(stream, state); -state.pendingcb--; -cb(); -finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { -if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); -} -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { -state.bufferProcessing = true; -var entry = state.bufferedRequest; - -if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } -} else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; -} - -state.bufferedRequestCount = 0; -state.bufferedRequest = entry; -state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { -cb(new Error('_write() is not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { -var state = this._writableState; - -if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; -} else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; -} - -if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - -// .end() fully uncorks -if (state.corked) { - state.corked = 1; - this.uncork(); -} - -// ignore unnecessary end() calls. -if (!state.ending && !state.finished) endWritable(this, state, cb); -}; - -function needFinish(state) { -return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { -stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); -}); -} -function prefinish(stream, state) { -if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - processNextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } -} -} - -function finishMaybe(stream, state) { -var need = needFinish(state); -if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } -} -return need; -} - -function endWritable(stream, state, cb) { -state.ending = true; -finishMaybe(stream, state); -if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); -} -state.ended = true; -stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { -var entry = corkReq.entry; -corkReq.entry = null; -while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; -} -if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; -} else { - state.corkedRequestsFree = corkReq; -} -} - -Object.defineProperty(Writable.prototype, 'destroyed', { -get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; -}, -set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; -} -}); - -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { -this.end(); -cb(err); -}; -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./_stream_duplex":74,"./internal/streams/destroy":80,"./internal/streams/stream":81,"_process":69,"core-util-is":26,"inherits":33,"process-nextick-args":68,"safe-buffer":83,"util-deprecate":92}],79:[function(_dereq_,module,exports){ -'use strict'; - -/**/ - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = _dereq_('safe-buffer').Buffer; -/**/ - -function copyBuffer(src, target, offset) { -src.copy(target, offset); -} - -module.exports = function () { -function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; -} - -BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; -}; - -BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; - -BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; -}; - -BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; -}; - -BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; -}; - -BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; -}; - -return BufferList; -}(); -},{"safe-buffer":83}],80:[function(_dereq_,module,exports){ -'use strict'; - -/**/ - -var processNextTick = _dereq_('process-nextick-args'); -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { -var _this = this; - -var readableDestroyed = this._readableState && this._readableState.destroyed; -var writableDestroyed = this._writableState && this._writableState.destroyed; - -if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - processNextTick(emitErrorNT, this, err); - } - 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; -} - -// if this is a duplex stream mark the writable part as destroyed as well -if (this._writableState) { - this._writableState.destroyed = true; -} - -this._destroy(err || null, function (err) { - if (!cb && err) { - processNextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } -}); -} - -function undestroy() { -if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; -} - -if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; -} -} - -function emitErrorNT(self, err) { -self.emit('error', err); -} - -module.exports = { -destroy: destroy, -undestroy: undestroy -}; -},{"process-nextick-args":68}],81:[function(_dereq_,module,exports){ -module.exports = _dereq_('events').EventEmitter; - -},{"events":29}],82:[function(_dereq_,module,exports){ -exports = module.exports = _dereq_('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = _dereq_('./lib/_stream_writable.js'); -exports.Duplex = _dereq_('./lib/_stream_duplex.js'); -exports.Transform = _dereq_('./lib/_stream_transform.js'); -exports.PassThrough = _dereq_('./lib/_stream_passthrough.js'); - -},{"./lib/_stream_duplex.js":74,"./lib/_stream_passthrough.js":75,"./lib/_stream_readable.js":76,"./lib/_stream_transform.js":77,"./lib/_stream_writable.js":78}],83:[function(_dereq_,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var buffer = _dereq_('buffer') -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 _dereq_('buffer') -copyProps(buffer, exports) -exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { -return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { -if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') -} -return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { -if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') -} -var buf = Buffer(size) -if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } -} else { - buf.fill(0) -} -return buf -} - -SafeBuffer.allocUnsafe = function (size) { -if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') -} -return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { -if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') -} -return buffer.SlowBuffer(size) -} - -},{"buffer":23}],84:[function(_dereq_,module,exports){ -(function (global){ -var ClientRequest = _dereq_('./lib/request') -var extend = _dereq_('xtend') -var statusCodes = _dereq_('builtin-status-codes') -var url = _dereq_('url') - -var http = exports - -http.request = function (opts, cb) { -if (typeof opts === 'string') - opts = url.parse(opts) -else - opts = extend(opts) - -// Normally, the page is loaded from http or https, so not specifying a protocol -// will result in a (valid) protocol-relative url. However, this won't work if -// the protocol is something else, like 'file:' -var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' - -var protocol = opts.protocol || defaultProtocol -var host = opts.hostname || opts.host -var port = opts.port -var path = opts.path || '/' - -// Necessary for IPv6 addresses -if (host && host.indexOf(':') !== -1) - host = '[' + host + ']' - -// This may be a relative url. The browser should always be able to interpret it correctly. -opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path -opts.method = (opts.method || 'GET').toUpperCase() -opts.headers = opts.headers || {} - -// Also valid opts.auth, opts.mode - -var req = new ClientRequest(opts) -if (cb) - req.on('response', cb) -return req -} - -http.get = function get (opts, cb) { -var req = http.request(opts, cb) -req.end() -return req -} - -http.Agent = function () {} -http.Agent.defaultMaxSockets = 4 - -http.STATUS_CODES = statusCodes - -http.METHODS = [ -'CHECKOUT', -'CONNECT', -'COPY', -'DELETE', -'GET', -'HEAD', -'LOCK', -'M-SEARCH', -'MERGE', -'MKACTIVITY', -'MKCOL', -'MOVE', -'NOTIFY', -'OPTIONS', -'PATCH', -'POST', -'PROPFIND', -'PROPPATCH', -'PURGE', -'PUT', -'REPORT', -'SEARCH', -'SUBSCRIBE', -'TRACE', -'UNLOCK', -'UNSUBSCRIBE' -] -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./lib/request":86,"builtin-status-codes":24,"url":90,"xtend":93}],85:[function(_dereq_,module,exports){ -(function (global){ -exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) - -exports.blobConstructor = false -try { -new Blob([new ArrayBuffer(1)]) -exports.blobConstructor = true -} catch (e) {} - -// The xhr request to example.com may violate some restrictive CSP configurations, -// so if we're running in a browser that supports `fetch`, avoid calling getXHR() -// and assume support for certain features below. -var xhr -function getXHR () { -// Cache the xhr value -if (xhr !== undefined) return xhr - -if (global.XMLHttpRequest) { - xhr = new global.XMLHttpRequest() - // If XDomainRequest is available (ie only, where xhr might not work - // cross domain), use the page location. Otherwise use example.com - // Note: this doesn't actually make an http request. - try { - xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') - } catch(e) { - xhr = null - } -} else { - // Service workers don't have XHR - xhr = null -} -return xhr -} - -function checkTypeSupport (type) { -var xhr = getXHR() -if (!xhr) return false -try { - xhr.responseType = type - return xhr.responseType === type -} catch (e) {} -return false -} - -// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. -// Safari 7.1 appears to have fixed this bug. -var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' -var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) - -// If fetch is supported, then arraybuffer will be supported too. Skip calling -// checkTypeSupport(), since that calls getXHR(). -exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) - -// These next two tests unavoidably show warnings in Chrome. Since fetch will always -// be used if it's available, just return false for these to avoid the warnings. -exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') -exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && -checkTypeSupport('moz-chunked-arraybuffer') - -// If fetch is supported, then overrideMimeType will be supported too. Skip calling -// getXHR(). -exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) - -exports.vbArray = isFunction(global.VBArray) - -function isFunction (value) { -return typeof value === 'function' -} - -xhr = null // Help gc - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],86:[function(_dereq_,module,exports){ -(function (process,global,Buffer){ -var capability = _dereq_('./capability') -var inherits = _dereq_('inherits') -var response = _dereq_('./response') -var stream = _dereq_('readable-stream') -var toArrayBuffer = _dereq_('to-arraybuffer') - -var IncomingMessage = response.IncomingMessage -var rStates = response.readyStates - -function decideMode (preferBinary, useFetch) { -if (capability.fetch && useFetch) { - return 'fetch' -} else if (capability.mozchunkedarraybuffer) { - return 'moz-chunked-arraybuffer' -} else if (capability.msstream) { - return 'ms-stream' -} else if (capability.arraybuffer && preferBinary) { - return 'arraybuffer' -} else if (capability.vbArray && preferBinary) { - return 'text:vbarray' -} else { - return 'text' -} -} - -var ClientRequest = module.exports = function (opts) { -var self = this -stream.Writable.call(self) - -self._opts = opts -self._body = [] -self._headers = {} -if (opts.auth) - self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) -Object.keys(opts.headers).forEach(function (name) { - self.setHeader(name, opts.headers[name]) -}) - -var preferBinary -var useFetch = true -if (opts.mode === 'disable-fetch' || 'timeout' in opts) { - // If the use of XHR should be preferred and includes preserving the 'content-type' header. - // Force XHR to be used since the Fetch API does not yet support timeouts. - useFetch = false - preferBinary = true -} else if (opts.mode === 'prefer-streaming') { - // If streaming is a high priority but binary compatibility and - // the accuracy of the 'content-type' header aren't - preferBinary = false -} else if (opts.mode === 'allow-wrong-content-type') { - // If streaming is more important than preserving the 'content-type' header - preferBinary = !capability.overrideMimeType -} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { - // Use binary if text streaming may corrupt data or the content-type header, or for speed - preferBinary = true -} else { - throw new Error('Invalid value for opts.mode') -} -self._mode = decideMode(preferBinary, useFetch) - -self.on('finish', function () { - self._onFinish() -}) -} - -inherits(ClientRequest, stream.Writable) - -ClientRequest.prototype.setHeader = function (name, value) { -var self = this -var lowerName = name.toLowerCase() -// This check is not necessary, but it prevents warnings from browsers about setting unsafe -// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but -// http-browserify did it, so I will too. -if (unsafeHeaders.indexOf(lowerName) !== -1) - return - -self._headers[lowerName] = { - name: name, - value: value -} -} - -ClientRequest.prototype.getHeader = function (name) { -var header = this._headers[name.toLowerCase()] -if (header) - return header.value -return null -} - -ClientRequest.prototype.removeHeader = function (name) { -var self = this -delete self._headers[name.toLowerCase()] -} - -ClientRequest.prototype._onFinish = function () { -var self = this - -if (self._destroyed) - return -var opts = self._opts - -var headersObj = self._headers -var body = null -if (opts.method !== 'GET' && opts.method !== 'HEAD') { - if (capability.blobConstructor) { - body = new global.Blob(self._body.map(function (buffer) { - return toArrayBuffer(buffer) - }), { - type: (headersObj['content-type'] || {}).value || '' - }) - } else { - // get utf8 string - body = Buffer.concat(self._body).toString() - } -} - -// create flattened list of headers -var headersList = [] -Object.keys(headersObj).forEach(function (keyName) { - var name = headersObj[keyName].name - var value = headersObj[keyName].value - if (Array.isArray(value)) { - value.forEach(function (v) { - headersList.push([name, v]) - }) - } else { - headersList.push([name, value]) - } -}) - -if (self._mode === 'fetch') { - global.fetch(self._opts.url, { - method: self._opts.method, - headers: headersList, - body: body || undefined, - mode: 'cors', - credentials: opts.withCredentials ? 'include' : 'same-origin' - }).then(function (response) { - self._fetchResponse = response - self._connect() - }, function (reason) { - self.emit('error', reason) - }) -} else { - var xhr = self._xhr = new global.XMLHttpRequest() - try { - xhr.open(self._opts.method, self._opts.url, true) - } catch (err) { - process.nextTick(function () { - self.emit('error', err) - }) - return - } - - // Can't set responseType on really old browsers - if ('responseType' in xhr) - xhr.responseType = self._mode.split(':')[0] - - if ('withCredentials' in xhr) - xhr.withCredentials = !!opts.withCredentials - - if (self._mode === 'text' && 'overrideMimeType' in xhr) - xhr.overrideMimeType('text/plain; charset=x-user-defined') - - if ('timeout' in opts) { - xhr.timeout = opts.timeout - xhr.ontimeout = function () { - self.emit('timeout') - } - } - - headersList.forEach(function (header) { - xhr.setRequestHeader(header[0], header[1]) - }) - - self._response = null - xhr.onreadystatechange = function () { - switch (xhr.readyState) { - case rStates.LOADING: - case rStates.DONE: - self._onXHRProgress() - break - } - } - // Necessary for streaming in Firefox, since xhr.response is ONLY defined - // in onprogress, not in onreadystatechange with xhr.readyState = 3 - if (self._mode === 'moz-chunked-arraybuffer') { - xhr.onprogress = function () { - self._onXHRProgress() - } - } - - xhr.onerror = function () { - if (self._destroyed) - return - self.emit('error', new Error('XHR error')) - } - - try { - xhr.send(body) - } catch (err) { - process.nextTick(function () { - self.emit('error', err) - }) - return - } -} -} - -/** -* Checks if xhr.status is readable and non-zero, indicating no error. -* Even though the spec says it should be available in readyState 3, -* accessing it throws an exception in IE8 -*/ -function statusValid (xhr) { -try { - var status = xhr.status - return (status !== null && status !== 0) -} catch (e) { - return false -} -} - -ClientRequest.prototype._onXHRProgress = function () { -var self = this - -if (!statusValid(self._xhr) || self._destroyed) - return - -if (!self._response) - self._connect() - -self._response._onXHRProgress() -} - -ClientRequest.prototype._connect = function () { -var self = this - -if (self._destroyed) - return - -self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) -self._response.on('error', function(err) { - self.emit('error', err) -}) - -self.emit('response', self._response) -} - -ClientRequest.prototype._write = function (chunk, encoding, cb) { -var self = this - -self._body.push(chunk) -cb() -} - -ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { -var self = this -self._destroyed = true -if (self._response) - self._response._destroyed = true -if (self._xhr) - self._xhr.abort() -// Currently, there isn't a way to truly abort a fetch. -// If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 -} - -ClientRequest.prototype.end = function (data, encoding, cb) { -var self = this -if (typeof data === 'function') { - cb = data - data = undefined -} - -stream.Writable.prototype.end.call(self, data, encoding, cb) -} - -ClientRequest.prototype.flushHeaders = function () {} -ClientRequest.prototype.setTimeout = function () {} -ClientRequest.prototype.setNoDelay = function () {} -ClientRequest.prototype.setSocketKeepAlive = function () {} - -// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method -var unsafeHeaders = [ -'accept-charset', -'accept-encoding', -'access-control-request-headers', -'access-control-request-method', -'connection', -'content-length', -'cookie', -'cookie2', -'date', -'dnt', -'expect', -'host', -'keep-alive', -'origin', -'referer', -'te', -'trailer', -'transfer-encoding', -'upgrade', -'user-agent', -'via' -] - -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer) - -},{"./capability":85,"./response":87,"_process":69,"buffer":23,"inherits":33,"readable-stream":82,"to-arraybuffer":89}],87:[function(_dereq_,module,exports){ -(function (process,global,Buffer){ -var capability = _dereq_('./capability') -var inherits = _dereq_('inherits') -var stream = _dereq_('readable-stream') - -var rStates = exports.readyStates = { -UNSENT: 0, -OPENED: 1, -HEADERS_RECEIVED: 2, -LOADING: 3, -DONE: 4 -} - -var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { -var self = this -stream.Readable.call(self) - -self._mode = mode -self.headers = {} -self.rawHeaders = [] -self.trailers = {} -self.rawTrailers = [] - -// Fake the 'close' event, but only once 'end' fires -self.on('end', function () { - // The nextTick is necessary to prevent the 'request' module from causing an infinite loop - process.nextTick(function () { - self.emit('close') - }) -}) - -if (mode === 'fetch') { - self._fetchResponse = response - - self.url = response.url - self.statusCode = response.status - self.statusMessage = response.statusText - - response.headers.forEach(function(header, key){ - self.headers[key.toLowerCase()] = header - self.rawHeaders.push(key, header) - }) - - - // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed - var reader = response.body.getReader() - function read () { - reader.read().then(function (result) { - if (self._destroyed) - return - if (result.done) { - self.push(null) - return - } - self.push(new Buffer(result.value)) - read() - }).catch(function(err) { - self.emit('error', err) - }) - } - read() - -} else { - self._xhr = xhr - self._pos = 0 - - self.url = xhr.responseURL - self.statusCode = xhr.status - self.statusMessage = xhr.statusText - var headers = xhr.getAllResponseHeaders().split(/\r?\n/) - headers.forEach(function (header) { - var matches = header.match(/^([^:]+):\s*(.*)/) - if (matches) { - var key = matches[1].toLowerCase() - if (key === 'set-cookie') { - if (self.headers[key] === undefined) { - self.headers[key] = [] - } - self.headers[key].push(matches[2]) - } else if (self.headers[key] !== undefined) { - self.headers[key] += ', ' + matches[2] - } else { - self.headers[key] = matches[2] - } - self.rawHeaders.push(matches[1], matches[2]) - } - }) - - self._charset = 'x-user-defined' - if (!capability.overrideMimeType) { - var mimeType = self.rawHeaders['mime-type'] - if (mimeType) { - var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) - if (charsetMatch) { - self._charset = charsetMatch[1].toLowerCase() - } - } - if (!self._charset) - self._charset = 'utf-8' // best guess - } -} -} - -inherits(IncomingMessage, stream.Readable) - -IncomingMessage.prototype._read = function () {} - -IncomingMessage.prototype._onXHRProgress = function () { -var self = this - -var xhr = self._xhr - -var response = null -switch (self._mode) { - case 'text:vbarray': // For IE9 - if (xhr.readyState !== rStates.DONE) - break - try { - // This fails in IE8 - response = new global.VBArray(xhr.responseBody).toArray() - } catch (e) {} - if (response !== null) { - self.push(new Buffer(response)) - break - } - // Falls through in IE8 - case 'text': - try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 - response = xhr.responseText - } catch (e) { - self._mode = 'text:vbarray' - break - } - if (response.length > self._pos) { - var newData = response.substr(self._pos) - if (self._charset === 'x-user-defined') { - var buffer = new Buffer(newData.length) - for (var i = 0; i < newData.length; i++) - buffer[i] = newData.charCodeAt(i) & 0xff - - self.push(buffer) - } else { - self.push(newData, self._charset) - } - self._pos = response.length - } - break - case 'arraybuffer': - if (xhr.readyState !== rStates.DONE || !xhr.response) - break - response = xhr.response - self.push(new Buffer(new Uint8Array(response))) - break - case 'moz-chunked-arraybuffer': // take whole - response = xhr.response - if (xhr.readyState !== rStates.LOADING || !response) - break - self.push(new Buffer(new Uint8Array(response))) - break - case 'ms-stream': - response = xhr.response - if (xhr.readyState !== rStates.LOADING) - break - var reader = new global.MSStreamReader() - reader.onprogress = function () { - if (reader.result.byteLength > self._pos) { - self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) - self._pos = reader.result.byteLength - } - } - reader.onload = function () { - self.push(null) - } - // reader.onerror = ??? // TODO: this - reader.readAsArrayBuffer(response) - break -} - -// The ms-stream case handles end separately in reader.onload() -if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { - self.push(null) -} -} - -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer) - -},{"./capability":85,"_process":69,"buffer":23,"inherits":33,"readable-stream":82}],88:[function(_dereq_,module,exports){ -'use strict'; - -var Buffer = _dereq_('safe-buffer').Buffer; - -var isEncoding = Buffer.isEncoding || function (encoding) { -encoding = '' + encoding; -switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; -} -}; - -function _normalizeEncoding(enc) { -if (!enc) return 'utf8'; -var retried; -while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } -} -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { -var nenc = _normalizeEncoding(enc); -if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); -return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { -this.encoding = normalizeEncoding(encoding); -var nb; -switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; -} -this.lastNeed = 0; -this.lastTotal = 0; -this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { -if (buf.length === 0) return ''; -var r; -var i; -if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; -} else { - i = 0; -} -if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); -return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { -if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); -} -buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); -this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. -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 -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; -} -if (--j < i) return 0; -nb = utf8CheckByte(buf[j]); -if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; -} -if (--j < i) return 0; -nb = utf8CheckByte(buf[j]); -if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; -} -return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// UTF-8 replacement characters ('\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'.repeat(p); -} -if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'.repeat(p + 1); - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'.repeat(p + 2); - } - } -} -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { -var p = this.lastTotal - this.lastNeed; -var r = utf8CheckExtraBytes(this, buf, p); -if (r !== undefined) return r; -if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); -} -buf.copy(this.lastChar, p, 0, buf.length); -this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { -var total = utf8CheckIncomplete(this, buf, i); -if (!this.lastNeed) return buf.toString('utf8', i); -this.lastTotal = total; -var end = buf.length - (total - this.lastNeed); -buf.copy(this.lastChar, 0, end); -return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character for each buffered byte of a (partial) -// character needs to be added to the output. -function utf8End(buf) { -var r = buf && buf.length ? this.write(buf) : ''; -if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); -return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { -if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; -} -this.lastNeed = 1; -this.lastTotal = 2; -this.lastChar[0] = buf[buf.length - 1]; -return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { -var r = buf && buf.length ? this.write(buf) : ''; -if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); -} -return r; -} - -function base64Text(buf, i) { -var n = (buf.length - i) % 3; -if (n === 0) return buf.toString('base64', i); -this.lastNeed = 3 - n; -this.lastTotal = 3; -if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; -} else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; -} -return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { -var r = buf && buf.length ? this.write(buf) : ''; -if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); -return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { -return buf.toString(this.encoding); -} - -function simpleEnd(buf) { -return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":83}],89:[function(_dereq_,module,exports){ -var Buffer = _dereq_('buffer').Buffer - -module.exports = function (buf) { -// If the buffer is backed by a Uint8Array, a faster version will work -if (buf instanceof Uint8Array) { - // If the buffer isn't a subarray, return the underlying ArrayBuffer - if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { - return buf.buffer - } else if (typeof buf.buffer.slice === 'function') { - // Otherwise we need to get a proper copy - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) - } -} - -if (Buffer.isBuffer(buf)) { - // This is the slow version that will work with any Buffer - // implementation (even in old browsers) - var arrayCopy = new Uint8Array(buf.length) - var len = buf.length - for (var i = 0; i < len; i++) { - arrayCopy[i] = buf[i] - } - return arrayCopy.buffer -} else { - throw new Error('Argument must be a Buffer') -} -} - -},{"buffer":23}],90:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var punycode = _dereq_('punycode'); -var util = _dereq_('./util'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { -this.protocol = null; -this.slashes = null; -this.auth = null; -this.host = null; -this.port = null; -this.hostname = null; -this.hash = null; -this.search = null; -this.query = null; -this.pathname = null; -this.path = null; -this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = _dereq_('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { -if (url && util.isObject(url) && url instanceof Url) return url; - -var u = new Url; -u.parse(url, parseQueryString, slashesDenoteHost); -return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { -if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); -} - -// Copy chrome, IE, opera backslash-handling behavior. -// Back slashes before the query string get converted to forward slashes -// See: https://code.google.com/p/chromium/issues/detail?id=25916 -var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; -uSplit[0] = uSplit[0].replace(slashRegex, '/'); -url = uSplit.join(splitter); - -var rest = url; - -// trim before proceeding. -// This is to support parse stuff like " http://foo.com \n" -rest = rest.trim(); - -if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } -} - -var proto = protocolPattern.exec(rest); -if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); -} - -// figure out if it's got a host -// user@server is *always* interpreted as a hostname, and url -// resolution will treat //foo/bar as host=foo,path=bar because that's -// how the browser resolves relative URLs. -if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } -} - -if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } -} - -// now rest is set to the post-host stuff. -// chop off any delim chars. -if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } -} - - -// chop off from the tail first. -var hash = rest.indexOf('#'); -if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); -} -var qm = rest.indexOf('?'); -if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); -} else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; -} -if (rest) this.pathname = rest; -if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; -} - -//to support http.request -if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; -} - -// finally, reconstruct the href based on what has been validated. -this.href = this.format(); -return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { -// ensure it's an object, and not a string url. -// If it's an obj, this is a no-op. -// this way, you can call url_format() on strings -// to clean up potentially wonky urls. -if (util.isString(obj)) obj = urlParse(obj); -if (!(obj instanceof Url)) return Url.prototype.format.call(obj); -return obj.format(); -} - -Url.prototype.format = function() { -var auth = this.auth || ''; -if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; -} - -var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - -if (this.host) { - host = auth + this.host; -} else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } -} - -if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); -} - -var search = this.search || (query && ('?' + query)) || ''; - -if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - -// only the slashedProtocols get the //. Not mailto:, xmpp:, etc. -// unless they had them to begin with. -if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; -} else if (!host) { - host = ''; -} - -if (hash && hash.charAt(0) !== '#') hash = '#' + hash; -if (search && search.charAt(0) !== '?') search = '?' + search; - -pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); -}); -search = search.replace('#', '%23'); - -return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { -return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { -return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { -if (!source) return relative; -return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { -if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; -} - -var result = new Url(); -var tkeys = Object.keys(this); -for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; -} - -// hash is always overridden, no matter what. -// even href="" will remove it. -result.hash = relative.hash; - -// if the relative url is empty, then there's nothing left to do here. -if (relative.href === '') { - result.href = result.format(); - return result; -} - -// hrefs like //foo/bar always cut to the protocol. -if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; -} - -if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -} - -var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - -// if the url is a non-slashed url, then relative -// links like ../.. should be able -// to crawl up to the hostname, as well. This is strange. -// result.protocol has already been set by now. -// Later on, put the first path part into the host field. -if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); -} - -if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. -} else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; -} else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; -} - -if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; -} - -// if a url ENDs in . or .., then it must get a trailing slash. -// however, if it ends in anything else non-slashy, -// then it must NOT get a trailing slash. -var last = srcPath.slice(-1)[0]; -var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - -// strip single dots, resolve double dots to parent dir -// if the path tries to go above the root, `up` ends up > 0 -var up = 0; -for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } -} - -// if the path is allowed to go above the root, restore leading ..s -if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } -} - -if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); -} - -if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); -} - -var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - -// put the host back -if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } -} - -mustEndAbs = mustEndAbs || (result.host && srcPath.length); - -if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); -} - -if (!srcPath.length) { - result.pathname = null; - result.path = null; -} else { - result.pathname = srcPath.join('/'); -} - -//to support request.http -if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); -} -result.auth = relative.auth || result.auth; -result.slashes = result.slashes || relative.slashes; -result.href = result.format(); -return result; -}; - -Url.prototype.parseHost = function() { -var host = this.host; -var port = portPattern.exec(host); -if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); -} -if (host) this.hostname = host; -}; - -},{"./util":91,"punycode":70,"querystring":73}],91:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = { -isString: function(arg) { - return typeof(arg) === 'string'; -}, -isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; -}, -isNull: function(arg) { - return arg === null; -}, -isNullOrUndefined: function(arg) { - return arg == null; -} -}; - -},{}],92:[function(_dereq_,module,exports){ -(function (global){ - -/** -* Module exports. -*/ - -module.exports = deprecate; - -/** -* Mark that a method should not be used. -* Returns a modified function which warns once by default. -* -* If `localStorage.noDeprecation = true` is set, then it is a no-op. -* -* If `localStorage.throwDeprecation = true` is set, then deprecated functions -* will throw an Error when invoked. -* -* If `localStorage.traceDeprecation = true` is set, then deprecated functions -* will invoke `console.trace()` instead of `console.warn()`. -* -* @param {Function} fn - the function to deprecate -* @param {String} msg - the string to print to the console when `fn` is invoked -* @returns {Function} a new "deprecated" version of `fn` -* @api public -*/ - -function deprecate (fn, msg) { -if (config('noDeprecation')) { - return fn; -} - -var warned = false; -function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); -} - -return deprecated; -} - -/** -* Checks `localStorage` for boolean values for the given `name`. -* -* @param {String} name -* @returns {Boolean} -* @api private -*/ - -function config (name) { -// accessing global.localStorage can trigger a DOMException in sandboxed iframes -try { - if (!global.localStorage) return false; -} catch (_) { - return false; -} -var val = global.localStorage[name]; -if (null == val) return false; -return String(val).toLowerCase() === 'true'; -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],93:[function(_dereq_,module,exports){ -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - -},{}]},{},[3])(3) -}); -//# sourceMappingURL=ref-parser.js.map -}); - - var jsonSchemaRefParser$1 = /*#__PURE__*/Object.freeze({ - default: jsonSchemaRefParser - }); - - var require$$3 = ( jsonSchemaRefParser$1 && jsonSchemaRefParser ) || jsonSchemaRefParser$1; - - function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - - - var RandExp = _interopDefault$1(randexp); - var deref = _interopDefault$1(lib$1); - var jsonpath$1 = _interopDefault$1(jsonpath); - var $RefParser = _interopDefault$1(require$$3); - - function template(value, schema) { - if (Array.isArray(value)) { - return value.map(function (x) { return template(x, schema); }); - } - if (typeof value === 'string') { - value = value.replace(/#\{([\w.-]+)\}/g, function (_, $1) { return schema[$1]; }); - } - return value; - } - // dynamic proxy for custom generators - function proxy(gen) { - return function (value, schema, property, rootSchema) { - var fn = value; - var args = []; - // support for nested object, first-key is the generator - if (typeof value === 'object') { - fn = Object.keys(value)[0]; - // treat the given array as arguments, - if (Array.isArray(value[fn])) { - // if the generator is expecting arrays they should be nested, e.g. `[[1, 2, 3], true, ...]` - args = value[fn]; - } - else { - args.push(value[fn]); - } - } - // support for keypaths, e.g. "internet.email" - var props = fn.split('.'); - // retrieve a fresh dependency - var ctx = gen(); - while (props.length > 1) { - ctx = ctx[props.shift()]; - } - // retrieve last value from context object - value = typeof ctx === 'object' ? ctx[props[0]] : ctx; - // invoke dynamic generators - if (typeof value === 'function') { - value = value.apply(ctx, args.map(function (x) { return template(x, rootSchema); })); - } - // test for pending callbacks - if (Object.prototype.toString.call(value) === '[object Object]') { - for (var key in value) { - if (typeof value[key] === 'function') { - throw new Error('Cannot resolve value for "' + property + ': ' + fn + '", given: ' + value); - } - } - } - return value; - }; - } - /** - * Container is used to wrap external generators (faker, chance, casual, etc.) and its dependencies. - * - * - `jsf.extend('faker')` will enhance or define the given dependency. - * - `jsf.define('faker')` will provide the "faker" keyword support. - * - * RandExp is not longer considered an "extension". - */ - var Container = /** @class */ (function () { - function Container() { - // dynamic requires - handle all dependencies - // they will NOT be included on the bundle - this.registry = {}; - this.support = {}; - } - /** - * Override dependency given by name - * @param name - * @param callback - */ - Container.prototype.extend = function (name, callback) { - var _this = this; - this.registry[name] = callback(this.registry[name]); - // built-in proxy (can be overridden) - if (!this.support[name]) { - this.support[name] = proxy(function () { return _this.registry[name]; }); - } - }; - /** - * Set keyword support by name - * @param name - * @param callback - */ - Container.prototype.define = function (name, callback) { - this.support[name] = callback; - }; - /** - * Returns dependency given by name - * @param name - * @returns {Dependency} - */ - Container.prototype.get = function (name) { - if (typeof this.registry[name] === 'undefined') { - throw new ReferenceError('"' + name + '" dependency doesn\'t exist.'); - } - return this.registry[name]; - }; - /** - * Apply a custom keyword - * @param schema - */ - Container.prototype.wrap = function (schema) { - var keys = Object.keys(schema); - var length = keys.length; - var context = {}; - while (length--) { - var fn = keys[length].replace(/^x-/, ''); - var gen = this.support[fn]; - if (typeof gen === 'function') { - if (typeof schema[fn] === 'object' && schema[fn].hasOwnProperty('type')) { - continue; - } - Object.defineProperty(schema, 'generate', { - configurable: false, - enumerable: false, - writable: false, - value: function (rootSchema) { return gen.call(context, schema[keys[length]], schema, keys[length], rootSchema); }, - }); - break; - } - } - return schema; - }; - return Container; - }()); - - /** - * This class defines a registry for custom formats used within JSF. - */ - var Registry = /** @class */ (function () { - function Registry() { - // empty by default - this.data = {}; - } - /** - * Registers custom format - */ - Registry.prototype.register = function (name, callback) { - this.data[name] = callback; - }; - /** - * Register many formats at one shot - */ - Registry.prototype.registerMany = function (formats) { - for (var name in formats) { - this.data[name] = formats[name]; - } - }; - /** - * Returns element by registry key - */ - Registry.prototype.get = function (name) { - var format = this.data[name]; - return format; - }; - /** - * Returns the whole registry content - */ - Registry.prototype.list = function () { - return this.data; - }; - return Registry; - }()); - - // instantiate - var registry = new Registry(); - /** - * Custom format API - * - * @see https://github.com/json-schema-faker/json-schema-faker#custom-formats - * @param nameOrFormatMap - * @param callback - * @returns {any} - */ - function formatAPI(nameOrFormatMap, callback) { - if (typeof nameOrFormatMap === 'undefined') { - return registry.list(); - } - else if (typeof nameOrFormatMap === 'string') { - if (typeof callback === 'function') { - registry.register(nameOrFormatMap, callback); - } - else { - return registry.get(nameOrFormatMap); - } - } - else { - registry.registerMany(nameOrFormatMap); - } - } - - /** - * This class defines a registry for custom settings used within JSF. - */ - var OptionRegistry = /** @class */ (function (_super) { - tslib_es6.__extends(OptionRegistry, _super); - function OptionRegistry() { - var _this = _super.call(this) || this; - _this.data = _this.defaults; - return _this; - } - Object.defineProperty(OptionRegistry.prototype, "defaults", { - get: function () { - var data = {}; - data['defaultInvalidTypeProduct'] = null; - data['defaultRandExpMax'] = 10; - data['ignoreProperties'] = []; - data['ignoreMissingRefs'] = false; - data['failOnInvalidTypes'] = true; - data['failOnInvalidFormat'] = true; - data['alwaysFakeOptionals'] = false; - data['fixedProbabilities'] = true; - data['optionalsProbability'] = 0.0; - data['useDefaultValue'] = false; - data['useExamplesValue'] = false; - data['avoidExampleItemsLength'] = false; - data['requiredOnly'] = false; - data['minItems'] = 0; - data['maxItems'] = null; - data['maxLength'] = null; - data['resolveJsonPath'] = false; - data['reuseProperties'] = false; - data['fillProperties'] = true; - data['random'] = Math.random; - return data; - }, - enumerable: true, - configurable: true - }); - return OptionRegistry; - }(Registry)); - - // instantiate - var registry$1 = new OptionRegistry(); - /** - * Custom option API - * - * @param nameOrOptionMap - * @returns {any} - */ - function optionAPI(nameOrOptionMap) { - if (typeof nameOrOptionMap === 'string') { - return registry$1.get(nameOrOptionMap); - } - else { - return registry$1.registerMany(nameOrOptionMap); - } - } - optionAPI.getDefaults = function () { return registry$1.defaults; }; - - var ALL_TYPES = ['array', 'object', 'integer', 'number', 'string', 'boolean', 'null']; - var MOST_NEAR_DATETIME = 2524608000000; - var MIN_INTEGER = -100000000; - var MAX_INTEGER = 100000000; - var MIN_NUMBER = -100; - var MAX_NUMBER = 100; - var env = { - ALL_TYPES: ALL_TYPES, - MIN_NUMBER: MIN_NUMBER, - MAX_NUMBER: MAX_NUMBER, - MIN_INTEGER: MIN_INTEGER, - MAX_INTEGER: MAX_INTEGER, - MOST_NEAR_DATETIME: MOST_NEAR_DATETIME, - }; - - /// - function _randexp(value) { - // set maximum default, see #193 - RandExp.prototype.max = optionAPI('defaultRandExpMax'); - // same implementation as the original except using our random - RandExp.prototype.randInt = function (a, b) { - return a + Math.floor(optionAPI('random')() * (1 + b - a)); - }; - var re = new RandExp(value); - return re.gen(); - } - /** - * Returns random element of a collection - * - * @param collection - * @returns {T} - */ - function pick(collection) { - return collection[Math.floor(optionAPI('random')() * collection.length)]; - } - /** - * Returns shuffled collection of elements - * - * @param collection - * @returns {T[]} - */ - function shuffle(collection) { - var tmp, key, copy = collection.slice(), length = collection.length; - for (; length > 0;) { - key = Math.floor(optionAPI('random')() * length); - // swap - tmp = copy[--length]; - copy[length] = copy[key]; - copy[key] = tmp; - } - return copy; - } - /** - * Returns a random integer between min (inclusive) and max (inclusive) - * Using Math.round() will give you a non-uniform distribution! - * @see http://stackoverflow.com/a/1527820/769384 - */ - function getRandom(min, max) { - return optionAPI('random')() * (max - min) + min; - } - /** - * Generates random number according to parameters passed - * - * @param min - * @param max - * @param defMin - * @param defMax - * @param hasPrecision - * @returns {number} - */ - function number(min, max, defMin, defMax, hasPrecision) { - if (hasPrecision === void 0) { hasPrecision = false; } - defMin = typeof defMin === 'undefined' ? env.MIN_NUMBER : defMin; - defMax = typeof defMax === 'undefined' ? env.MAX_NUMBER : defMax; - min = typeof min === 'undefined' ? defMin : min; - max = typeof max === 'undefined' ? defMax : max; - if (max < min) { - max += min; - } - var result = getRandom(min, max); - if (!hasPrecision) { - return Math.round(result); - } - return result; - } - function by(type) { - switch (type) { - case 'seconds': - return number(0, 60) * 60; - case 'minutes': - return number(15, 50) * 612; - case 'hours': - return number(12, 72) * 36123; - case 'days': - return number(7, 30) * 86412345; - case 'weeks': - return number(4, 52) * 604812345; - case 'months': - return number(2, 13) * 2592012345; - case 'years': - return number(1, 20) * 31104012345; - } - } - function date(step) { - if (step) { - return by(step); - } - var now = new Date(); - var days = number(-1000, env.MOST_NEAR_DATETIME); - now.setTime(now.getTime() - days); - return now; - } - var random = { - pick: pick, - date: date, - randexp: _randexp, - shuffle: shuffle, - number: number, - }; - - function getSubAttribute(obj, dotSeparatedKey) { - var keyElements = dotSeparatedKey.split('.'); - while (keyElements.length) { - var prop = keyElements.shift(); - if (!obj[prop]) { - break; - } - obj = obj[prop]; - } - return obj; - } - /** - * Returns true/false whether the object parameter has its own properties defined - * - * @param obj - * @param properties - * @returns {boolean} - */ - function hasProperties(obj) { - var properties = []; - for (var _i = 1; _i < arguments.length; _i++) { - properties[_i - 1] = arguments[_i]; - } - return properties.filter(function (key) { - return typeof obj[key] !== 'undefined'; - }).length > 0; - } - /** - * Returns typecasted value. - * External generators (faker, chance, casual) may return data in non-expected formats, such as string, when you might expect an - * integer. This function is used to force the typecast. This is the base formatter for all result values. - * - * @param schema - * @param callback - * @returns {any} - */ - function typecast(schema, callback) { - var params = {}; - // normalize constraints - switch (schema.type) { - case 'integer': - case 'number': - if (typeof schema.minimum !== 'undefined') { - params.minimum = schema.minimum; - } - if (typeof schema.maximum !== 'undefined') { - params.maximum = schema.maximum; - } - if (schema.enum) { - var min = Math.max(params.minimum || 0, 0); - var max = Math.min(params.maximum || Infinity, Infinity); - min = handleExclusiveMinimum(schema, min); - max = handleExclusiveMaximum(schema, max); - // discard out-of-bounds enumerations - schema.enum = schema.enum.filter(function (x) { - if (x >= min && x <= max) { - return true; - } - return false; - }); - } - break; - case 'string': - if (typeof schema.minLength !== 'undefined') { - params.minLength = schema.minLength; - } - if (typeof schema.maxLength !== 'undefined') { - params.maxLength = schema.maxLength; - } - var _maxLength = optionAPI('maxLength'); - var _minLength = optionAPI('minLength'); - // Don't allow user to set max length above our maximum - if (_maxLength && params.maxLength > _maxLength) { - params.maxLength = _maxLength; - } - // Don't allow user to set min length above our maximum - if (_minLength && params.minLength < _minLength) { - params.minLength = _minLength; - } - break; - } - // execute generator - var value = callback(params); - // normalize output value - switch (schema.type) { - case 'number': - value = parseFloat(value); - break; - case 'integer': - value = parseInt(value, 10); - break; - case 'boolean': - value = !!value; - break; - case 'string': - value = String(value); - var min = Math.max(params.minLength || 0, 0); - var max = Math.min(params.maxLength || Infinity, Infinity); - while (value.length < min) { - value += ' ' + value; - } - if (value.length > max) { - value = value.substr(0, max); - } - break; - } - return value; - } - function merge(a, b) { - for (var key in b) { - if (typeof b[key] !== 'object' || b[key] === null) { - a[key] = b[key]; - } - else if (Array.isArray(b[key])) { - a[key] = a[key] || []; - // fix #292 - skip duplicated values from merge object (b) - b[key].forEach(function (value) { - if (a[key].indexOf(value) === -1) { - a[key].push(value); - } - }); - } - else if (typeof a[key] !== 'object' || a[key] === null || Array.isArray(a[key])) { - a[key] = merge({}, b[key]); - } - else { - a[key] = merge(a[key], b[key]); - } - } - return a; - } - function clean(obj, isArray, requiredProps) { - if (!obj || typeof obj !== 'object') { - return obj; - } - if (Array.isArray(obj)) { - obj = obj - .map(function (value) { return clean(value, true, requiredProps); }) - .filter(function (value) { return typeof value !== 'undefined'; }); - return obj; - } - Object.keys(obj).forEach(function (k) { - if (!requiredProps || requiredProps.indexOf(k) === -1) { - if (Array.isArray(obj[k]) && !obj[k].length) { - delete obj[k]; - } - } - else { - obj[k] = clean(obj[k]); - } - }); - if (!Object.keys(obj).length && isArray) { - return undefined; - } - return obj; - } - function short(schema) { - var s = JSON.stringify(schema); - var l = JSON.stringify(schema, null, 2); - return s.length > 400 ? l.substr(0, 400) + '...' : l; - } - function anyValue() { - return random.pick([ - false, - true, - null, - -1, - NaN, - Math.PI, - Infinity, - undefined, - [], - {}, - Math.random(), - Math.random().toString(36).substr(2), - ]); - } - function notValue(schema, parent) { - var copy = merge({}, parent); - if (typeof schema.minimum !== 'undefined') { - copy.maximum = schema.minimum; - copy.exclusiveMaximum = true; - } - if (typeof schema.maximum !== 'undefined') { - copy.minimum = schema.maximum > copy.maximum ? 0 : schema.maximum; - copy.exclusiveMinimum = true; - } - if (typeof schema.minLength !== 'undefined') { - copy.maxLength = schema.minLength; - } - if (typeof schema.maxLength !== 'undefined') { - copy.minLength = schema.maxLength > copy.maxLength ? 0 : schema.maxLength; - } - if (schema.type) { - copy.type = random.pick(env.ALL_TYPES.filter(function (x) { - // treat both types as _similar enough_ to be skipped equal - if (x === 'number' || x === 'integer') { - return schema.type !== 'number' && schema.type !== 'integer'; - } - return x !== schema.type; - })); - } - else if (schema.enum) { - do { - var value = anyValue(); - } while (schema.enum.indexOf(value) !== -1); - copy.enum = [value]; - } - if (schema.required && copy.properties) { - schema.required.forEach(function (prop) { - delete copy.properties[prop]; - }); - } - // TODO: explore more scenarios - return copy; - } - // FIXME: evaluate more constraints? - function validate(value, schemas) { - return !schemas.every(function (x) { - if (typeof x.minimum !== 'undefined' && value >= x.minimum) { - return true; - } - if (typeof x.maximum !== 'undefined' && value <= x.maximum) { - return true; - } - }); - } - function isKey(prop) { - return prop === 'enum' || prop === 'default' || prop === 'required' || prop === 'definitions'; - } - function omitProps(obj, props) { - var copy = {}; - Object.keys(obj).forEach(function (k) { - if (props.indexOf(k) === -1) { - if (Array.isArray(obj[k])) { - copy[k] = obj[k].slice(); - } - else { - copy[k] = typeof obj[k] === 'object' - ? merge({}, obj[k]) - : obj[k]; - } - } - }); - return copy; - } - var utils = { - getSubAttribute: getSubAttribute, - hasProperties: hasProperties, - omitProps: omitProps, - typecast: typecast, - merge: merge, - clean: clean, - short: short, - notValue: notValue, - anyValue: anyValue, - validate: validate, - isKey: isKey, - }; - - var ParseError = /** @class */ (function (_super) { - tslib_es6.__extends(ParseError, _super); - function ParseError(message, path) { - var _this = _super.call(this) || this; - _this.path = path; - if (Error.captureStackTrace) { - Error.captureStackTrace(_this, _this.constructor); - } - _this.name = 'ParseError'; - _this.message = message; - _this.path = path; - return _this; - } - return ParseError; - }(Error)); - - var inferredProperties = { - array: [ - 'additionalItems', - 'items', - 'maxItems', - 'minItems', - 'uniqueItems' - ], - integer: [ - 'exclusiveMaximum', - 'exclusiveMinimum', - 'maximum', - 'minimum', - 'multipleOf' - ], - object: [ - 'additionalProperties', - 'dependencies', - 'maxProperties', - 'minProperties', - 'patternProperties', - 'properties', - 'required' - ], - string: [ - 'maxLength', - 'minLength', - 'pattern' - ] - }; - inferredProperties.number = inferredProperties.integer; - var subschemaProperties = [ - 'additionalItems', - 'items', - 'additionalProperties', - 'dependencies', - 'patternProperties', - 'properties' - ]; - /** - * Iterates through all keys of `obj` and: - * - checks whether those keys match properties of a given inferred type - * - makes sure that `obj` is not a subschema; _Do not attempt to infer properties named as subschema containers. The - * reason for this is that any property name within those containers that matches one of the properties used for - * inferring missing type values causes the container itself to get processed which leads to invalid output. (Issue 62)_ - * - * @returns {boolean} - */ - function matchesType(obj, lastElementInPath, inferredTypeProperties) { - return Object.keys(obj).filter(function (prop) { - var isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1, inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1; - if (inferredPropertyFound && !isSubschema) { - return true; - } - }).length > 0; - } - /** - * Checks whether given `obj` type might be inferred. The mechanism iterates through all inferred types definitions, - * tries to match allowed properties with properties of given `obj`. Returns type name, if inferred, or null. - * - * @returns {string|null} - */ - function inferType(obj, schemaPath) { - for (var typeName in inferredProperties) { - var lastElementInPath = schemaPath[schemaPath.length - 1]; - if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) { - return typeName; - } - } - } - - /** - * Generates randomized boolean value. - * - * @returns {boolean} - */ - function booleanGenerator() { - return optionAPI('random')() > 0.5; - } - - var booleanType = booleanGenerator; - - /** - * Generates null value. - * - * @returns {null} - */ - function nullGenerator() { - return null; - } - - var nullType = nullGenerator; - - // TODO provide types - function unique(path, items, value, sample, resolve, traverseCallback) { - var tmp = [], seen = []; - function walk(obj) { - var json = JSON.stringify(obj); - if (seen.indexOf(json) === -1) { - seen.push(json); - tmp.push(obj); - } - } - items.forEach(walk); - // TODO: find a better solution? - var limit = 10; - while (tmp.length !== items.length) { - walk(traverseCallback(value.items || sample, path, resolve)); - if (!limit--) { - break; - } - } - return tmp; - } - // TODO provide types - var arrayType = function arrayType(value, path, resolve, traverseCallback) { - var items = []; - if (!(value.items || value.additionalItems)) { - if (utils.hasProperties(value, 'minItems', 'maxItems', 'uniqueItems')) { - throw new ParseError('missing items for ' + utils.short(value), path); - } - return items; - } - // see http://stackoverflow.com/a/38355228/769384 - // after type guards support subproperties (in TS 2.0) we can simplify below to (value.items instanceof Array) - // so that value.items.map becomes recognized for typescript compiler - var tmpItems = value.items; - if (tmpItems instanceof Array) { - return Array.prototype.concat.call(items, tmpItems.map(function (item, key) { - var itemSubpath = path.concat(['items', key + '']); - return traverseCallback(item, itemSubpath, resolve); - })); - } - var minItems = value.minItems; - var maxItems = value.maxItems; - if (optionAPI('minItems') && minItems === undefined) { - // fix boundaries - minItems = !maxItems - ? optionAPI('minItems') - : Math.min(optionAPI('minItems'), maxItems); - } - if (optionAPI('maxItems')) { - // Don't allow user to set max items above our maximum - if (maxItems && maxItems > optionAPI('maxItems')) { - maxItems = optionAPI('maxItems'); - } - // Don't allow user to set min items above our maximum - if (minItems && minItems > optionAPI('maxItems')) { - minItems = maxItems; - } - } - var optionalsProbability = optionAPI('alwaysFakeOptionals') === true ? 1.0 : optionAPI('optionalsProbability'); - var length = (maxItems != null && optionalsProbability) - ? Math.round(maxItems * optionalsProbability) - : random.number(minItems, maxItems, 1, 5), - // TODO below looks bad. Should additionalItems be copied as-is? - sample = typeof value.additionalItems === 'object' ? value.additionalItems : {}; - for (var current = items.length; current < length; current++) { - var itemSubpath = path.concat(['items', current + '']); - var element = traverseCallback(value.items || sample, itemSubpath, resolve); - items.push(element); - } - if (value.uniqueItems) { - return unique(path.concat(['items']), items, value, sample, resolve, traverseCallback); - } - return items; - }; - - var numberType = function numberType(value) { - var min = typeof value.minimum === 'undefined' ? env.MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? env.MAX_INTEGER : value.maximum, multipleOf = value.multipleOf; - if (multipleOf) { - max = Math.floor(max / multipleOf) * multipleOf; - min = Math.ceil(min / multipleOf) * multipleOf; - } - min = handleExclusiveMinimum(value, min); - max = handleExclusiveMaximum(value, max); - if (min > max) { - return NaN; - } - if (multipleOf) { - if (String(multipleOf).indexOf('.') === -1) { - var base = random.number(Math.floor(min / multipleOf), Math.floor(max / multipleOf)) * multipleOf; - while (base < min) { - base += value.multipleOf; - } - return base; - } - var boundary = (max - min) / multipleOf; - do { - var num = random.number(0, boundary) * multipleOf; - var fix = (num / multipleOf) % 1; - } while (fix !== 0); - return num; - } - return random.number(min, max, undefined, undefined, true); - }; - - // The `integer` type is just a wrapper for the `number` type. The `number` type - // returns floating point numbers, and `integer` type truncates the fraction - // part, leaving the result as an integer. - var integerType = function integerType(value) { - var generated = numberType(value); - // whether the generated number is positive or negative, need to use either - // floor (positive) or ceil (negative) function to get rid of the fraction - return generated > 0 ? Math.floor(generated) : Math.ceil(generated); - }; - - var LIPSUM_WORDS = ('Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore' - + ' et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea' - + ' commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla' - + ' pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est' - + ' laborum').split(' '); - /** - * Generates randomized array of single lorem ipsum words. - * - * @param length - * @returns {Array.} - */ - function wordsGenerator(length) { - var words = random.shuffle(LIPSUM_WORDS); - return words.slice(0, length); - } - - // fallback generator - var anyType = { type: ['string', 'number', 'integer', 'boolean'] }; - // TODO provide types - // Updated objectType definition to latest version (0.5.0-rcv.41) - var objectType = function objectType(value, path, resolve, traverseCallback) { - const props = {}; - - const properties = value.properties || {}; - const patternProperties = value.patternProperties || {}; - const requiredProperties = typeof value.required === 'boolean' ? [] : (value.required || []).slice(); - const allowsAdditional = value.additionalProperties !== false; - - const propertyKeys = Object.keys(properties); - const patternPropertyKeys = Object.keys(patternProperties); - const optionalProperties = propertyKeys.concat(patternPropertyKeys).reduce((_response, _key) => { - if (requiredProperties.indexOf(_key) === -1) _response.push(_key); - return _response; - }, []); - const allProperties = requiredProperties.concat(optionalProperties); - - const additionalProperties = allowsAdditional // eslint-disable-line - ? (value.additionalProperties === true ? anyType : value.additionalProperties) - : value.additionalProperties; - - if (!allowsAdditional - && propertyKeys.length === 0 - && patternPropertyKeys.length === 0 - && utils.hasProperties(value, 'minProperties', 'maxProperties', 'dependencies', 'required') - ) { - // just nothing - return null; - } - - if (optionAPI('requiredOnly') === true) { - requiredProperties.forEach(key => { - if (properties[key]) { - props[key] = properties[key]; - } - }); - - return traverseCallback(props, path.concat(['properties']), resolve, value); - } - - const optionalsProbability = optionAPI('alwaysFakeOptionals') === true ? 1.0 : optionAPI('optionalsProbability'); - const fixedProbabilities = optionAPI('alwaysFakeOptionals') || optionAPI('fixedProbabilities') || false; - const ignoreProperties = optionAPI('ignoreProperties') || []; - const reuseProps = optionAPI('reuseProperties'); - const fillProps = optionAPI('fillProperties'); - - const max = value.maxProperties || (allProperties.length + (allowsAdditional ? random.number(1, 5) : 0)); - - let min = Math.max(value.minProperties || 0, requiredProperties.length); - let neededExtras = Math.max(0, allProperties.length - min); - - if (optionalsProbability !== null) { - if (fixedProbabilities === true) { - neededExtras = Math.round((min - requiredProperties.length) + (optionalsProbability * (allProperties.length - min))); - } else { - neededExtras = random.number(min - requiredProperties.length, optionalsProbability * (allProperties.length - min)); - } - } - - const extraPropertiesRandomOrder = random.shuffle(optionalProperties).slice(0, neededExtras); - const extraProperties = optionalProperties.filter(_item => { - return extraPropertiesRandomOrder.indexOf(_item) !== -1; - }); - - // properties are read from right-to-left - const _limit = optionalsProbability !== null || requiredProperties.length === max ? max : random.number(0, max); - const _props = requiredProperties.concat(extraProperties).slice(0, max); - const _defns = []; - - if (value.dependencies) { - Object.keys(value.dependencies).forEach(prop => { - const _required = value.dependencies[prop]; - - if (_props.indexOf(prop) !== -1) { - if (Array.isArray(_required)) { - // property-dependencies - _required.forEach(sub => { - if (_props.indexOf(sub) === -1) { - _props.push(sub); - } - }); - } else { - _defns.push(_required); - } - } - }); - - // schema-dependencies - if (_defns.length) { - delete value.dependencies; - - return traverseCallback({ - allOf: _defns.concat(value), - }, path.concat(['properties']), resolve, value); - } - } - - const skipped = []; - const missing = []; - - _props.forEach(key => { - for (let i = 0; i < ignoreProperties.length; i += 1) { - if ((ignoreProperties[i] instanceof RegExp && ignoreProperties[i].test(key)) - || (typeof ignoreProperties[i] === 'string' && ignoreProperties[i] === key) - || (typeof ignoreProperties[i] === 'function' && ignoreProperties[i](properties[key], key))) { - skipped.push(key); - return; - } - } - - if (additionalProperties === false) { - if (requiredProperties.indexOf(key) !== -1) { - props[key] = properties[key]; - } - } - - if (properties[key]) { - props[key] = properties[key]; - } - - let found; - - // then try patternProperties - patternPropertyKeys.forEach(_key => { - if (key.match(new RegExp(_key))) { - found = true; - - if (props[key]) { - utils.merge(props[key], patternProperties[_key]); - } else { - props[random.randexp(key)] = patternProperties[_key]; - } - } - }); - - if (!found) { - // try patternProperties again, - const subschema = patternProperties[key] || additionalProperties; - - // FIXME: allow anyType as fallback when no subschema is given? - - if (subschema && additionalProperties !== false) { - // otherwise we can use additionalProperties? - props[patternProperties[key] ? random.randexp(key) : key] = properties[key] || subschema; - } else { - missing.push(key); - } - } - }); - - // discard already ignored props if they're not required to be filled... - let current = Object.keys(props).length + (fillProps ? 0 : skipped.length); - - // generate dynamic suffix for additional props... - const hash = suffix => random.randexp(`_?[_a-f\\d]{1,3}${suffix ? '\\$?' : ''}`); - - function get(from) { - let one; - - do { - if (!from.length) break; - one = from.shift(); - } while (props[one]); - - return one; - } - - let minProps = min; - if (allowsAdditional && !requiredProperties.length) { - minProps = Math.max(optionalsProbability === null || additionalProperties ? random.number(fillProps ? 1 : 0, max) : 0, min); - } - - while (fillProps) { - if (!(patternPropertyKeys.length || allowsAdditional)) { - break; - } - - if (current >= minProps) { - break; - } - - if (allowsAdditional) { - if (reuseProps && ((propertyKeys.length - current) > minProps)) { - let count = 0; - let key; - - do { - count += 1; - - // skip large objects - if (count > 1000) { - break; - } - - key = get(requiredProperties) || random.pick(propertyKeys); - } while (typeof props[key] !== 'undefined'); - - if (typeof props[key] === 'undefined') { - props[key] = properties[key]; - current += 1; - } - } else if (patternPropertyKeys.length && !additionalProperties) { - const prop = random.pick(patternPropertyKeys); - const word = random.randexp(prop); - - if (!props[word]) { - props[word] = patternProperties[prop]; - current += 1; - } - } else { - const word = get(requiredProperties) || (wordsGenerator(1) + hash()); - - if (!props[word]) { - props[word] = additionalProperties || anyType; - current += 1; - } - } - } - - for (let i = 0; current < min && i < patternPropertyKeys.length; i += 1) { - const _key = patternPropertyKeys[i]; - const word = random.randexp(_key); - - - if (!props[word]) { - props[word] = patternProperties[_key]; - current += 1; - } - } - } - - // fill up-to this value and no more! - if (requiredProperties.length === 0 && (!allowsAdditional || optionalsProbability === false)) { - const maximum = random.number(min, max); - - for (; current < maximum;) { - const word = get(propertyKeys); - - if (word) { - props[word] = properties[word]; - } - - current += 1; - } - } - - return traverseCallback(props, path.concat(['properties']), resolve, value); - }; - - /** - * Helper function used by thunkGenerator to produce some words for the final result. - * - * @returns {string} - */ - function produce() { - var length = random.number(1, 5); - return wordsGenerator(length).join(' '); - } - /** - * Generates randomized concatenated string based on words generator. - * - * @returns {string} - */ - function thunkGenerator(min, max) { - if (min === void 0) { min = 0; } - if (max === void 0) { max = 140; } - var min = Math.max(0, min), max = random.number(min, max), result = produce(); - // append until length is reached - while (result.length < min) { - result += produce(); - } - // cut if needed - if (result.length > max) { - result = result.substr(0, max); - } - return result; - } - - /** - * Generates randomized ipv4 address. - * - * @returns {string} - */ - function ipv4Generator() { - return [0, 0, 0, 0].map(function () { - return random.number(0, 255); - }).join('.'); - } - - /** - * Generates randomized date time ISO format string. - * - * @returns {string} - */ - function dateTimeGenerator() { - return random.date().toISOString(); - } - - /** - * Generates randomized date format string. - * - * @returns {string} - */ - function dateGenerator() { - return dateTimeGenerator().slice(0, 10); - } - - /** - * Generates randomized time format string. - * - * @returns {string} - */ - function timeGenerator() { - return dateTimeGenerator().slice(11); - } - - /** - * Added few formats from latest json-schema-faker. see below for source - * https://github.com/json-schema-faker/json-schema-faker/blob/master/src/lib/generators/coreFormat.js - * - */ - const FRAGMENT = '[a-zA-Z][a-zA-Z0-9+-.]*'; - const URI_PATTERN = `https?://{hostname}(?:${FRAGMENT})+`; - const PARAM_PATTERN = '(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?'; - - /** - * Predefined core formats - * @type {[key: string]: string} - */ - var regexps = { - email: '[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}', - hostname: '[a-zA-Z]{1,33}\\.[a-z]{2,4}', - ipv6: '[a-f\\d]{4}(:[a-f\\d]{4}){7}', - uri: URI_PATTERN, - slug: '[a-zA-Z\\d_-]+', - - // types from draft-0[67] (?) - 'uri-reference': `${URI_PATTERN}${PARAM_PATTERN}`, - 'uri-template': URI_PATTERN.replace('(?:', '(?:/\\{[a-z][:a-zA-Z0-9-]*\\}|'), - 'json-pointer': `(/(?:${FRAGMENT.replace(']*', '/]*')}|~[01]))+`, - - // some types from https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#data-types (?) - uuid: '^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$', - }; - - regexps.iri = regexps['uri-reference']; - regexps['iri-reference'] = regexps['uri-reference']; - - regexps['idn-email'] = regexps.email; - regexps['idn-hostname'] = regexps.hostname; - - /** - * Generates randomized string basing on a built-in regex format - * - * @param coreFormat - * @returns {string} - */ - function coreFormatGenerator(coreFormat) { - return random.randexp(regexps[coreFormat]).replace(/\{(\w+)\}/, function (match, key) { - return random.randexp(regexps[key]); - }); - } - - function generateFormat(value, invalid) { - var callback = formatAPI(value.format); - if (typeof callback === 'function') { - return callback(value); - } - switch (value.format) { - case 'date-time': - case 'datetime': - return dateTimeGenerator(); - case 'date': - return dateGenerator(); - case 'time': - return timeGenerator(); - case 'ipv4': - return ipv4Generator(); - case 'regex': - // TODO: discuss - return '.+?'; - case 'email': - case 'hostname': - case 'ipv6': - case 'uri': - case 'uri-reference': - case 'iri': - case 'iri-reference': - case 'idn-email': - case 'idn-hostname': - case 'json-pointer': - case 'slug': - case 'uri-template': - case 'uuid': - return coreFormatGenerator(value.format); - default: - if (typeof callback === 'undefined') { - if (optionAPI('failOnInvalidFormat')) { - throw new Error('unknown registry key ' + utils.short(value.format)); - } - else { - return invalid(); - } - } - throw new Error('unsupported format "' + value.format + '"'); - } - } - var stringType = function stringType(value) { - var output; - output = utils.typecast(value, function (opts) { - if (value.format) { - return generateFormat(value, function () { return thunkGenerator(opts.minLength, opts.maxLength); }); - } - if (value.pattern) { - return random.randexp(value.pattern); - } - return thunkGenerator(opts.minLength, opts.maxLength); - }); - return output; - }; - - var typeMap = { - boolean: booleanType, - null: nullType, - array: arrayType, - integer: integerType, - number: numberType, - object: objectType, - string: stringType - }; - - // TODO provide types - function traverse(schema, path, resolve, rootSchema) { - schema = resolve(schema); - if (!schema) { - return; - } - if (optionAPI('useExamplesValue') && 'example' in schema) { - var clonedSchema, - result; - - // avoid minItems and maxItems while checking for valid examples - if (optionAPI('avoidExampleItemsLength') && _.get(schema, 'type') === 'array') { - clonedSchema = _.clone(schema); - _.unset(clonedSchema, 'minItems'); - _.unset(clonedSchema, 'maxItems'); - - // avoid validation of values that are in pm variable format (i.e. '{{userId}}') - result = validateSchema(clonedSchema, schema.example, { ignoreUnresolvedVariables: true }); - } - else { - // avoid validation of values that are in pm variable format (i.e. '{{userId}}') - result = validateSchema(schema, schema.example, { ignoreUnresolvedVariables: true }); - } - - // Use example only if valid - if (result && result.length === 0) { - return schema.example; - } - } - // use default as faked value if found as keyword in schema - if (optionAPI('useDefaultValue') && 'default' in schema) { - // to not use default as faked value in case it is actual property of schema - if (!(_.has(schema.default, 'type') && _.includes(ALL_TYPES, schema.default.type))) { - return schema.default; - } - } - if (schema.not && typeof schema.not === 'object') { - schema = utils.notValue(schema.not, utils.omitProps(schema, ['not'])); - } - if (Array.isArray(schema.enum)) { - return utils.typecast(schema, function () { return random.pick(schema.enum); }); - } - // thunks can return sub-schemas - if (typeof schema.thunk === 'function') { - return traverse(schema.thunk(), path, resolve); - } - if (typeof schema.generate === 'function') { - return utils.typecast(schema, function () { return schema.generate(rootSchema); }); - } - // TODO remove the ugly overcome - var type = schema.type; - if (Array.isArray(type)) { - type = random.pick(type); - } - else if (typeof type === 'undefined') { - // Attempt to infer the type - type = inferType(schema, path) || type; - if (type) { - schema.type = type; - } - } - if (typeof type === 'string') { - if (!typeMap[type]) { - if (optionAPI('failOnInvalidTypes')) { - throw new ParseError('unknown primitive ' + utils.short(type), path.concat(['type'])); - } - else { - return optionAPI('defaultInvalidTypeProduct'); - } - } - else { - try { - var result = typeMap[type](schema, path, resolve, traverse); - var required = schema.items - ? schema.items.required - : schema.required; - return utils.clean(result, null, required); - } - catch (e) { - if (typeof e.path === 'undefined') { - throw new ParseError(e.message, path); - } - throw e; - } - } - } - var copy = {}; - if (Array.isArray(schema)) { - copy = []; - } - for (var prop in schema) { - if (typeof schema[prop] === 'object' && prop !== 'definitions') { - copy[prop] = traverse(schema[prop], path.concat([prop]), resolve, copy); - } - else { - copy[prop] = schema[prop]; - } - } - return copy; - } - - function pick$1(data) { - return Array.isArray(data) - ? random.pick(data) - : data; - } - function cycle(data, reverse) { - if (!Array.isArray(data)) { - return data; - } - var value = reverse - ? data.pop() - : data.shift(); - if (reverse) { - data.unshift(value); - } - else { - data.push(value); - } - return value; - } - function resolve(obj, data, values, property) { - if (!obj || typeof obj !== 'object') { - return obj; - } - if (!values) { - values = {}; - } - if (!data) { - data = obj; - } - if (Array.isArray(obj)) { - return obj.map(function (x) { return resolve(x, data, values, property); }); - } - if (obj.jsonPath) { - var params = typeof obj.jsonPath !== 'object' - ? { path: obj.jsonPath } - : obj.jsonPath; - params.group = obj.group || params.group || property; - params.cycle = obj.cycle || params.cycle || false; - params.reverse = obj.reverse || params.reverse || false; - params.count = obj.count || params.count || 1; - var key = params.group + "__" + params.path; - if (!values[key]) { - if (params.count > 1) { - values[key] = jsonpath$1.query(data, params.path, params.count); - } - else { - values[key] = jsonpath$1.value(data, params.path); - } - } - if (params.cycle || params.reverse) { - return cycle(values[key], params.reverse); - } - return pick$1(values[key]); - } - Object.keys(obj).forEach(function (k) { - obj[k] = resolve(obj[k], data, values, k); - }); - return obj; - } - // TODO provide types - function run(refs, schema, container) { - try { - var result = traverse(schema, [], function reduce(sub, maxReduceDepth) { - if (typeof maxReduceDepth === 'undefined') { - maxReduceDepth = random.number(1, 3); - } - if (!sub) { - return null; - } - if (typeof sub.generate === 'function') { - return sub; - } - // cleanup - if (sub.id && typeof sub.id === 'string') { - delete sub.id; - delete sub.$schema; - } - if (typeof sub.$ref === 'string') { - if (sub.$ref === '#') { - delete sub.$ref; - return sub; - } - if (sub.$ref.indexOf('#/') === -1) { - var ref = deref.util.findByRef(sub.$ref, refs); - if (!ref) { - throw new Error('Reference not found: ' + sub.$ref); - } - return ref; - } - // just remove the reference - delete sub.$ref; - return sub; - } - if (Array.isArray(sub.allOf)) { - var schemas = sub.allOf; - delete sub.allOf; - // this is the only case where all sub-schemas - // must be resolved before any merge - schemas.forEach(function (subSchema) { - var _sub = reduce(subSchema, maxReduceDepth + 1); - // call given thunks if present - utils.merge(sub, typeof _sub.thunk === 'function' - ? _sub.thunk() - : _sub); - }); - } - if (Array.isArray(sub.oneOf || sub.anyOf)) { - var mix = sub.oneOf || sub.anyOf; - // test every value from the enum against each-oneOf - // schema, only values that validate once are kept - if (sub.enum && sub.oneOf) { - sub.enum = sub.enum.filter(function (x) { return utils.validate(x, mix); }); - } - delete sub.anyOf; - delete sub.oneOf; - return { - thunk: function () { - var copy = utils.merge({}, sub); - utils.merge(copy, random.pick(mix)); - return copy; - }, - }; - } - for (var prop in sub) { - if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !utils.isKey(prop)) { - sub[prop] = reduce(sub[prop], maxReduceDepth); - } - } - return container.wrap(sub); - }); - if (optionAPI('resolveJsonPath')) { - return resolve(result); - } - return result; - } - catch (e) { - if (e.path) { - throw new Error(e.message + ' in ' + '/' + e.path.join('/')); - } - else { - throw e; - } - } - } - - var container = new Container(); - function getRefs(refs) { - var $refs = {}; - if (Array.isArray(refs)) { - refs.map(deref.util.normalizeSchema).forEach(function (schema) { - $refs[schema.id] = schema; - }); - } - else { - $refs = refs || {}; - } - return $refs; - } - function walk(obj, cb) { - var keys = Object.keys(obj); - var retval; - for (var i = 0; i < keys.length; i += 1) { - retval = cb(obj[keys[i]], keys[i], obj); - if (!retval && obj[keys[i]] && !Array.isArray(obj[keys[i]]) && typeof obj[keys[i]] === 'object') { - retval = walk(obj[keys[i]], cb); - } - if (typeof retval !== 'undefined') { - return retval; - } - } - } - var jsf = function (schema, refs) { - var ignore = optionAPI('ignoreMissingRefs'); - var $ = deref(function (id, refs) { - // FIXME: allow custom callback? - if (ignore) { - return {}; - } - }); - var $refs = getRefs(refs); - return run($refs, $(schema, $refs, true), container); - }; - jsf.resolve = function (schema, refs, cwd) { - if (typeof refs === 'string') { - cwd = refs; - refs = {}; - } - // normalize basedir (browser aware) - cwd = cwd || (typeof process !== 'undefined' ? process.cwd() : ''); - cwd = cwd.replace(/\/+$/, '') + '/'; - var $refs = getRefs(refs); - // identical setup as json-schema-sequelizer - var fixedRefs = { - order: 300, - canRead: true, - read: function (file, callback) { - var id = cwd !== '/' - ? file.url.replace(cwd, '') - : file.url; - try { - callback(null, deref.util.findByRef(id, $refs)); - } - catch (e) { - var result = walk(schema, function (v, k, sub) { - if (k === 'id' && v === id) { - return sub; - } - }); - if (!result) { - return callback(e); - } - callback(null, result); - } - }, - }; - return $RefParser - .dereference(cwd, schema, { - resolve: { fixedRefs: fixedRefs }, - dereference: { - circular: 'ignore', - }, - }).then(function (sub) { return run($refs, sub, container); }); - }; - jsf.format = formatAPI; - jsf.option = optionAPI; - jsf.random = random; - // built-in support - container.define('pattern', random.randexp); - // skip default generators - container.define('jsonPath', function (value, schema) { - delete schema.type; - return schema; - }); - // safe auto-increment values - container.define('autoIncrement', function (value, schema) { - if (!this.offset) { - var min = schema.minimum || 1; - var max = min + env.MAX_NUMBER; - var offset = value.initialOffset || schema.initialOffset; - this.offset = offset || random.number(min, max); - } - if (value === true) { - return this.offset++; - } - return schema; - }); - // safe-and-sequential dates - container.define('sequentialDate', function (value, schema) { - if (!this.now) { - this.now = random.date(); - } - if (value) { - schema = this.now.toISOString(); - value = value === true - ? 'days' - : value; - if (['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'].indexOf(value) === -1) { - throw new Error("Unsupported increment by " + utils.short(value)); - } - this.now.setTime(this.now.getTime() + random.date(value)); - } - return schema; - }); - // returns itself for chaining - jsf.extend = function (name, cb) { - container.extend(name, cb); - return jsf; - }; - jsf.define = function (name, cb) { - container.define(name, cb); - return jsf; - }; - jsf.locate = function (name) { - return container.get(name); - }; - var VERSION="0.5.0-rc15"; - jsf.version = VERSION; - - var lib$2 = jsf; - - return lib$2; - -}))); diff --git a/lib/30XUtils/schemaUtils30X.js b/lib/30XUtils/schemaUtils30X.js index fd2c41a99..c915ee51e 100644 --- a/lib/30XUtils/schemaUtils30X.js +++ b/lib/30XUtils/schemaUtils30X.js @@ -40,16 +40,6 @@ module.exports = { return currentType === typeToValidate; }, - /** - * This method is to make this module matches with schemaUtilsXXX interface content - * It only returns the provided schema - * @param {object} schema a provided schema - * @returns {object} it returns the same schema - */ - fixExamplesByVersion(schema) { - return schema; - }, - /** * Check if request body type is binary type * @param {string} bodyType the bodyType provided in a request body content diff --git a/lib/31XUtils/schemaUtils31X.js b/lib/31XUtils/schemaUtils31X.js index dd3a3f00d..873d5d0b2 100644 --- a/lib/31XUtils/schemaUtils31X.js +++ b/lib/31XUtils/schemaUtils31X.js @@ -90,49 +90,6 @@ module.exports = { return { foundType, foundExample }; }, - /** - * Takes the first element from 'examples' property in a schema and adds a new 'example' property. - * This method is used before faking the schema. (Schema faker uses the example property to fakle the schema) - * @param {object} schema a provided schema - * @returns {object} it returns the schema with a new example property - */ - fixExamplesByVersion(schema) { - // This method could be removed when schema faker gets upgraded - const hasExamplesInRoot = _.has(schema, 'examples'), - hasChildItems = _.has(schema, 'type') && - _.has(schema, 'items'), - hasProperties = _.has(schema, 'properties'), - typeIsAnArray = _.has(schema, 'type') && - Array.isArray(schema.type); - - if (hasExamplesInRoot && typeIsAnArray) { - let typeAndExample = this.findTypeByExample(schema.examples, schema.type), - foundType = typeAndExample.foundType, - foundExample = typeAndExample.foundExample; - schema.type = foundType ? foundType : schema.type[0]; - schema.example = foundExample ? foundExample : schema.examples[0]; - } - - if (hasExamplesInRoot && !typeIsAnArray) { - schema.example = schema.examples[0]; - } - - if (!hasExamplesInRoot && typeIsAnArray) { - schema.type = schema.type[0]; - } - - if (!hasExamplesInRoot && hasChildItems) { - schema.items = this.fixExamplesByVersion(schema.items); - } - else if (hasProperties) { - const schemaProperties = Object.keys(schema.properties); - schemaProperties.forEach((property) => { - schema.properties[property] = this.fixExamplesByVersion(schema.properties[property]); - }); - } - return schema; - }, - /** * Check if request body type is binary type. * Open api 3.1 does not need that a binary content has a schema within. It comes as an empty object diff --git a/lib/schemaUtils.js b/lib/schemaUtils.js index 57eee6ee0..becfc319b 100644 --- a/lib/schemaUtils.js +++ b/lib/schemaUtils.js @@ -9,7 +9,8 @@ const { formatDataPath, checkIsCorrectType, isKnownType } = require('./common/sc { getConcreteSchemaUtils, isSwagger, validateSupportedVersion } = require('./common/versionUtils.js'), async = require('async'), sdk = require('postman-collection'), - schemaFaker = require('../assets/json-schema-faker.js'), + // schemaFaker = require('../assets/json-schema-faker.js'), + schemaFaker = require('../assets/json-schema-faker-bundle.js'), deref = require('./deref.js'), _ = require('lodash'), xmlFaker = require('./xmlSchemaFaker.js'), @@ -112,7 +113,9 @@ schemaFaker.option({ maxItems: 20, // limit on maximum number of items faked for (type: arrray) useDefaultValue: true, ignoreMissingRefs: true, - avoidExampleItemsLength: true // option to avoid validating type array schema example's minItems and maxItems props. + avoidExampleItemsLength: true, // option to avoid validating type array schema example's minItems and maxItems props. + validationOptions: { ignoreUnresolvedVariables: true }, // validation ignoring Postman variables + pickFirstFromExamples: true // option to pick first example from examples array }); /** @@ -144,13 +147,9 @@ function safeSchemaFaker(oldSchema, resolveTo, resolveFor, parameterSourceOption var prop, key, resolvedSchema, fakedSchema, schemaResolutionCache = _.get(schemaCache, 'schemaResolutionCache', {}), schemaFakerCache = _.get(schemaCache, 'schemaFakerCache', {}); - let concreteUtils = components && components.hasOwnProperty('concreteUtils') ? - components.concreteUtils : - DEFAULT_SCHEMA_UTILS; resolvedSchema = deref.resolveRefs(oldSchema, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, 0, {}, stackLimit); - resolvedSchema = concreteUtils.fixExamplesByVersion(resolvedSchema); key = JSON.stringify(resolvedSchema); if (resolveTo === 'schema') { @@ -197,7 +196,7 @@ function safeSchemaFaker(oldSchema, resolveTo, resolveFor, parameterSourceOption return fakedSchema; } // for JSON, the indentCharacter will be applied in the JSON.stringify step later on - fakedSchema = schemaFaker(resolvedSchema); + fakedSchema = schemaFaker.generate(resolvedSchema, undefined, validateSchema); schemaFakerCache[key] = fakedSchema; return fakedSchema; } diff --git a/test/unit/30Xsupport/schemaUtils30X.test.js b/test/unit/30Xsupport/schemaUtils30X.test.js index a710f23a8..18ee3ac06 100644 --- a/test/unit/30Xsupport/schemaUtils30X.test.js +++ b/test/unit/30Xsupport/schemaUtils30X.test.js @@ -62,32 +62,6 @@ describe('compareTypes method', function() { }); }); -describe('fixExamplesByVersion method', function() { - it('Should return the same schema than the provided', function() { - const providedSchema = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - type: 'integer' - }, - name: { - type: 'string', - example: 'this is my fisrt example name in pet' - }, - tag: { - type: 'string' - } - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(providedSchema)); - }); -}); - describe('isBinaryContentType method', function() { it('Should be true if content type is binary type without schema', function() { const bodyType = 'application/octet-stream', diff --git a/test/unit/31Xsupport/schemaUtils31X.test.js b/test/unit/31Xsupport/schemaUtils31X.test.js index 16b326ad0..adc83f18a 100644 --- a/test/unit/31Xsupport/schemaUtils31X.test.js +++ b/test/unit/31Xsupport/schemaUtils31X.test.js @@ -153,479 +153,6 @@ describe('compareTypes method', function() { }); }); -describe('fixExamplesByVersion method', function() { - it('Should fix when user provides a primary schema root with examples', function() { - const providedSchema = { - type: 'string', - examples: [ - 'This is an example' - ] - }, - expectedSchemaAfterFix = { - type: 'string', - examples: [ - 'This is an example' - ], - example: 'This is an example' - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should fix when user provides a primary schema root with examples, ' + - 'and type is provided as array', function() { - const providedSchema = { - type: [ - 'string' - ], - examples: [ - 'This is an example' - ] - }, - expectedSchemaAfterFix = { - type: 'string', - examples: [ - 'This is an example' - ], - example: 'This is an example' - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with items', function() { - const providedSchema = { - type: 'array', - items: { - type: 'string', - examples: [ - 'This is my example' - ] - } - }, - expectedSchemaAfterFix = { - type: 'array', - items: { - type: 'string', - examples: [ - 'This is my example' - ], - example: 'This is my example' - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with items, and items type is provided as array', function() { - const providedSchema = { - type: 'array', - items: { - type: ['string'], - examples: [ - 'This is my example' - ] - } - }, - expectedSchemaAfterFix = { - type: 'array', - items: { - type: 'string', - examples: [ - 'This is my example' - ], - example: 'This is my example' - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with properties with examples ', function() { - const providedSchema = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - type: 'integer', - examples: [ - 11111 - ] - }, - name: { - type: 'string', - examples: [ - 'this is my fisrt example name in pet' - ] - }, - tag: { - type: 'string' - } - } - }, - expectedSchemaAfterFix = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - type: 'integer', - examples: [ - 11111 - ], - example: 11111 - }, - name: { - type: 'string', - examples: [ - 'this is my fisrt example name in pet' - ], - example: 'this is my fisrt example name in pet' - }, - tag: { - type: 'string' - } - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with properties with examples ' + - 'and type is provided as an array', function() { - const providedSchema = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - type: ['integer'], - examples: [ - 11111 - ] - }, - name: { - type: ['string'], - examples: [ - 'this is my fisrt example name in pet' - ] - }, - tag: { - type: ['string'] - } - } - }, - expectedSchemaAfterFix = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - type: 'integer', - examples: [ - 11111 - ], - example: 11111 - }, - name: { - type: 'string', - examples: [ - 'this is my fisrt example name in pet' - ], - example: 'this is my fisrt example name in pet' - }, - tag: { - type: 'string' - } - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with properties ' + - 'and properties has inner properties with examples', function() { - const providedSchema = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - 'required': [ - 'responseId', - 'responseName' - ], - 'properties': { - 'responseId': { - 'type': 'integer', - 'format': 'int64', - 'examples': [234] - }, - 'responseName': { - 'type': 'string', - 'examples': ['200 OK Response'] - } - } - }, - name: { - 'required': [ - 'responseId', - 'responseName' - ], - 'properties': { - 'responseId': { - 'type': 'integer', - 'format': 'int64', - 'examples': [111222333] - }, - 'responseName': { - 'type': 'string', - 'examples': ['Name 200 OK Response'] - } - } - } - } - }, - expectedSchemaAfterFix = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - 'required': [ - 'responseId', - 'responseName' - ], - 'properties': { - 'responseId': { - 'type': 'integer', - 'format': 'int64', - 'examples': [234], - 'example': 234 - }, - 'responseName': { - 'type': 'string', - 'examples': ['200 OK Response'], - 'example': '200 OK Response' - } - } - }, - name: { - 'required': [ - 'responseId', - 'responseName' - ], - 'properties': { - 'responseId': { - 'type': 'integer', - 'format': 'int64', - 'examples': [111222333], - 'example': 111222333 - }, - 'responseName': { - 'type': 'string', - 'examples': ['Name 200 OK Response'], - 'example': 'Name 200 OK Response' - } - } - } - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should resolve when user provides an schema with properties ' + - 'and properties has inner properties with examples and all types are arrays', function() { - const providedSchema = { - required: [ - 'id', - 'name' - ], - type: ['object'], - properties: { - id: { - required: [ - 'responseId', - 'responseName' - ], - properties: { - responseId: { - type: ['integer'], - format: 'int64', - examples: [ - 234 - ] - }, - responseName: { - type: ['string'], - examples: [ - '200 OK Response' - ] - } - } - }, - name: { - required: [ - 'responseId', - 'responseName' - ], - properties: { - responseId: { - type: ['integer'], - format: 'int64', - examples: [ - 5678 - ] - }, - responseName: { - type: ['string'], - examples: [ - 'Another name 200 OK Response' - ] - } - } - } - } - }, - expectedSchemaAfterFix = { - required: [ - 'id', - 'name' - ], - type: 'object', - properties: { - id: { - required: [ - 'responseId', - 'responseName' - ], - properties: { - responseId: { - type: 'integer', - format: 'int64', - examples: [ - 234 - ], - example: 234 - }, - responseName: { - type: 'string', - examples: [ - '200 OK Response' - ], - example: '200 OK Response' - } - } - }, - name: { - required: [ - 'responseId', - 'responseName' - ], - properties: { - responseId: { - type: 'integer', - format: 'int64', - examples: [ - 5678 - ], - example: 5678 - }, - responseName: { - type: 'string', - examples: [ - 'Another name 200 OK Response' - ], - example: 'Another name 200 OK Response' - } - } - } - } - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should return example 123 when the types is an array with string and integer', function() { - const providedSchema = { - required: [ - 'id' - ], - type: ['string', 'integer'], - examples: [123, 1234] - }, - expectedSchemaAfterFix = { - required: [ - 'id' - ], - type: 'integer', - examples: [123, 1234], - example: 123 - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should return example "Not an Integer" and type integer when type and example dont match', function() { - const providedSchema = { - required: [ - 'id' - ], - type: ['integer'], - examples: ['Not an Integer'] - }, - expectedSchemaAfterFix = { - required: [ - 'id' - ], - type: 'integer', - examples: ['Not an Integer'], - example: 'Not an Integer' - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - - it('Should return example "test" and type string when first example did not match any type', function() { - const providedSchema = { - required: [ - 'id' - ], - type: ['string', 'integer'], - examples: [true, 'test'] - }, - expectedSchemaAfterFix = { - required: [ - 'id' - ], - type: 'string', - examples: [true, 'test'], - example: 'test' - }, - fixedSchemaWithExample = concreteUtils.fixExamplesByVersion(providedSchema); - expect(JSON.stringify(fixedSchemaWithExample)).to.be.equal(JSON.stringify(expectedSchemaAfterFix)); - }); - -}); - describe('isBinaryContentType method', function() { it('Should be true if content type is binary type without schema', function() { const bodyType = 'application/octet-stream', diff --git a/test/unit/faker.test.js b/test/unit/faker.test.js index a52027b95..46b70ceb8 100644 --- a/test/unit/faker.test.js +++ b/test/unit/faker.test.js @@ -1,13 +1,13 @@ const _ = require('lodash'), expect = require('chai').expect, - schemaFaker = require('../../assets/json-schema-faker.js'); + { validateSchema } = require('../../lib/ajValidation/ajvValidation.js'), + schemaFaker = require('../../assets/json-schema-faker-bundle.js'); -// define options used similar while faking in schemaUtils.safeSchemFaker() schemaFaker.option({ requiredOnly: false, optionalsProbability: 1.0, minLength: 4, - maxLength: 4, + maxLength: 256, minItems: 1, maxItems: 20, useDefaultValue: true, @@ -36,7 +36,7 @@ describe('JSON SCHEMA FAKER TESTS', function () { }; it('Should use example with more than two elements for type array schema in faking. GitHub#9344', function () { - var fakedData = schemaFaker(schema); + var fakedData = schemaFaker.generate(schema); schemaFaker.option({ avoidExampleItemsLength: true }); expect(fakedData).to.deep.equal(schema.example); @@ -54,7 +54,7 @@ describe('JSON SCHEMA FAKER TESTS', function () { } }; - var fakedData = schemaFaker(schema); + var fakedData = schemaFaker.generate(schema, undefined, validateSchema); expect(fakedData).to.deep.equal({ default: 'This is actual property and not JSON schema defined "default" keyword' }); @@ -71,8 +71,9 @@ describe('JSON SCHEMA FAKER TESTS', function () { } } }; - - var fakedData = schemaFaker(schema); + schemaFaker.option('validationOptions', { ignoreUnresolvedVariables: true }); + schemaFaker.option('useExamplesValue', true); + var fakedData = schemaFaker.generate(schema, undefined, validateSchema); expect(fakedData).to.deep.equal({ id: '{{orderId}}' }); @@ -92,7 +93,7 @@ describe('JSON SCHEMA FAKER TESTS', function () { } }; - var fakedData = schemaFaker(schema); + var fakedData = schemaFaker.generate(schema); expect(fakedData).to.be.an('object'); expect(fakedData).to.be.not.empty; _.forEach(fakedData, (value) => {