Skip to content

Instantly share code, notes, and snippets.

@alfredwesterveld
Last active April 28, 2017 11:46
Show Gist options
  • Save alfredwesterveld/5aeae6f88dbf33d067110564a5aad849 to your computer and use it in GitHub Desktop.
Save alfredwesterveld/5aeae6f88dbf33d067110564a5aad849 to your computer and use it in GitHub Desktop.
requirebin sketch
var PNG = require('pngjs').PNG
, pixelmatch = require('pixelmatch')
, fabric = require('fabric').fabric;
var c1 = new fabric.Canvas('c1')
, c2 = new fabric.Canvas('c2');
var ctx1 = c1.getContext()
, ctx2 = c2.getContext()
, ctx3 = document.getElementById('c3').getContext('2d');
var pixelsElm = document.getElementById('pixels');
c1.add(new fabric.IText('hi', {
left: 20,
top: 20
}));
c2.add(new fabric.IText('hoi', {
left: 20,
top: 20
}));
document.getElementById('compare').addEventListener('click', function () {
var img1 = ctx1.getImageData(0, 0, 100, 100);
var img2 = ctx2.getImageData(0, 0, 100, 100);
var diff = ctx3.createImageData(100, 100);
var res = pixelmatch(img1.data, img2.data, diff.data, 100, 100);
ctx3.putImageData(diff, 0, 0);
pixelsElm.innerHTML = res;
});
setTimeout(function(){require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;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{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};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)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){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}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}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}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}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;if(a.prototype!==b.prototype)return false;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;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};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}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,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/":44}],2:[function(require,module,exports){},{}],3:[function(require,module,exports){"use strict";var TYPED_OK=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Int32Array!=="undefined";exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source){continue}if(typeof source!=="object"){throw new TypeError(source+"must be non-object")}for(var p in source){if(source.hasOwnProperty(p)){obj[p]=source[p]}}}return obj};exports.shrinkBuf=function(buf,size){if(buf.length===size){return buf}if(buf.subarray){return buf.subarray(0,size)}buf.length=size;return buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){var i,l,len,pos,chunk,result;len=0;for(i=0,l=chunks.length;i<l;i++){len+=chunks[i].length}result=new Uint8Array(len);pos=0;for(i=0,l=chunks.length;i<l;i++){chunk=chunks[i];result.set(chunk,pos);pos+=chunk.length}return result}};var fnUntyped={arraySet:function(dest,src,src_offs,len,dest_offs){for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){return[].concat.apply([],chunks)}};exports.setTyped=function(on){if(on){exports.Buf8=Uint8Array;exports.Buf16=Uint16Array;exports.Buf32=Int32Array;exports.assign(exports,fnTyped)}else{exports.Buf8=Array;exports.Buf16=Array;exports.Buf32=Array;exports.assign(exports,fnUntyped)}};exports.setTyped(TYPED_OK)},{}],4:[function(require,module,exports){"use strict";function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module.exports=adler32},{}],5:[function(require,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],6:[function(require,module,exports){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i<end;i++){crc=crc>>>8^t[(crc^buf[i])&255]}return crc^-1}module.exports=crc32},{}],7:[function(require,module,exports){"use strict";var utils=require("../utils/common");var trees=require("./trees");var adler32=require("./adler32");var crc32=require("./crc32");var msg=require("./messages");var Z_NO_FLUSH=0;var Z_PARTIAL_FLUSH=1;var Z_FULL_FLUSH=3;var Z_FINISH=4;var Z_BLOCK=5;var Z_OK=0;var Z_STREAM_END=1;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_BUF_ERROR=-5;var Z_DEFAULT_COMPRESSION=-1;var Z_FILTERED=1;var Z_HUFFMAN_ONLY=2;var Z_RLE=3;var Z_FIXED=4;var Z_DEFAULT_STRATEGY=0;var Z_UNKNOWN=2;var Z_DEFLATED=8;var MAX_MEM_LEVEL=9;var MAX_WBITS=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;function err(strm,errorCode){strm.msg=msg[errorCode];return errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}function flush_pending(strm){var s=strm.state;var len=s.pending;if(len>strm.avail_out){len=strm.avail_out}if(len===0){return}utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out);strm.next_out+=len;s.pending_out+=len;strm.total_out+=len;strm.avail_out-=len;s.pending-=len;if(s.pending===0){s.pending_out=0}}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last);s.block_start=s.strstart;flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255;s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size){len=size}if(len===0){return 0}strm.avail_in-=len;utils.arraySet(buf,strm.input,strm.next_in,len,start);if(strm.state.wrap===1){strm.adler=adler32(strm.adler,buf,len,start)}else if(strm.state.wrap===2){strm.adler=crc32(strm.adler,buf,len,start)}strm.next_in+=len;strm.total_in+=len;return len}function longest_match(s,cur_match){var chain_length=s.max_chain_length;var scan=s.strstart;var match;var len;var best_len=s.prev_length;var nice_match=s.nice_match;var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0;var _win=s.window;var wmask=s.w_mask;var prev=s.prev;var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match){chain_length>>=2}if(nice_match>s.lookahead){nice_match=s.lookahead}do{match=cur_match;if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue}scan+=2;match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len}return s.lookahead}function fill_window(s){var _w_size=s.w_size;var p,n,m,more,str;do{more=s.window_size-s.lookahead-s.strstart;if(s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0);s.match_start-=_w_size;s.strstart-=_w_size;s.block_start-=_w_size;n=s.hash_size;p=n;do{m=s.head[--p];s.head[p]=m>=_w_size?m-_w_size:0}while(--n);n=_w_size;p=n;do{m=s.prev[--p];s.prev[p]=m>=_w_size?m-_w_size:0}while(--n);more+=_w_size}if(s.strm.avail_in===0){break}n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more);s.lookahead+=n;if(s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert;s.ins_h=s.window[str];s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;while(s.insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;s.insert--;if(s.lookahead+s.insert<MIN_MATCH){break}}}}while(s.lookahead<MIN_LOOKAHEAD&&s.strm.avail_in!==0)}function deflate_stored(s,flush){var max_block_size=65535;if(max_block_size>s.pending_buf_size-5){max_block_size=s.pending_buf_size-5}for(;;){if(s.lookahead<=1){fill_window(s);if(s.lookahead===0&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.strstart+=s.lookahead;s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){s.lookahead=s.strstart-max_start;s.strstart=max_start;flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.strstart>s.block_start){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head;var bflush;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}if(hash_head!==0&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head)}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;if(s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do{s.strstart++;s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}while(--s.match_length!==0);s.strstart++}else{s.strstart+=s.match_length;s.match_length=0;s.ins_h=s.window[s.strstart];s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_slow(s,flush){var hash_head;var bflush;var max_insert;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}s.prev_length=s.match_length;s.prev_match=s.match_start;s.match_length=MIN_MATCH-1;if(hash_head!==0&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);if(s.match_length<=5&&(s.strategy===Z_FILTERED||s.match_length===MIN_MATCH&&s.strstart-s.match_start>4096)){s.match_length=MIN_MATCH-1}}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH;bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH);s.lookahead-=s.prev_length-1;s.prev_length-=2;do{if(++s.strstart<=max_insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}}while(--s.prev_length!==0);s.match_available=0;s.match_length=MIN_MATCH-1;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}else if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);if(bflush){flush_block_only(s,false)}s.strstart++;s.lookahead--;if(s.strm.avail_out===0){return BS_NEED_MORE}}else{s.match_available=1;s.strstart++;s.lookahead--}}if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);s.match_available=0}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_rle(s,flush){var bflush;var prev;var scan,strend;var _win=s.window;for(;;){if(s.lookahead<=MAX_MATCH){fill_window(s);if(s.lookahead<=MAX_MATCH&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.match_length=0;if(s.lookahead>=MIN_MATCH&&s.strstart>0){scan=s.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=MAX_MATCH-(strend-scan);if(s.match_length>s.lookahead){s.match_length=s.lookahead}}}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;s.strstart+=s.match_length;s.match_length=0}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){fill_window(s);if(s.lookahead===0){if(flush===Z_NO_FLUSH){return BS_NEED_MORE}break}}s.match_length=0;bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table;configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size;zero(s.head);s.max_lazy_match=configuration_table[s.level].max_lazy;s.good_match=configuration_table[s.level].good_length;s.nice_match=configuration_table[s.level].nice_length;s.max_chain_length=configuration_table[s.level].max_chain;s.strstart=0;s.block_start=0;s.lookahead=0;s.insert=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;s.ins_h=0}function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2);this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2);this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new utils.Buf16(MAX_BITS+1);this.heap=new utils.Buf16(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new utils.Buf16(2*L_CODES+1);zero(this.depth);this.l_buf=0;this.lit_bufsize=0;this.last_lit=0;this.d_buf=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state){return err(strm,Z_STREAM_ERROR)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;s=strm.state;s.pending=0;s.pending_out=0;if(s.wrap<0){s.wrap=-s.wrap}s.status=s.wrap?INIT_STATE:BUSY_STATE;strm.adler=s.wrap===2?0:1;s.last_flush=Z_NO_FLUSH;trees._tr_init(s);return Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK){lm_init(strm.state)}return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR}if(strm.state.wrap!==2){return Z_STREAM_ERROR}strm.state.gzhead=head;return Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm){return Z_STREAM_ERROR}var wrap=1;if(level===Z_DEFAULT_COMPRESSION){level=6}if(windowBits<0){wrap=0;windowBits=-windowBits}else if(windowBits>15){wrap=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED){return err(strm,Z_STREAM_ERROR)}if(windowBits===8){windowBits=9}var s=new DeflateState;strm.state=s;s.strm=strm;s.wrap=wrap;s.gzhead=null;s.w_bits=windowBits;s.w_size=1<<s.w_bits;s.w_mask=s.w_size-1;s.hash_bits=memLevel+7;s.hash_size=1<<s.hash_bits;s.hash_mask=s.hash_size-1;s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH);s.window=new utils.Buf8(s.w_size*2);s.head=new utils.Buf16(s.hash_size);s.prev=new utils.Buf16(s.w_size);s.lit_bufsize=1<<memLevel+6;s.pending_buf_size=s.lit_bufsize*4;s.pending_buf=new utils.Buf8(s.pending_buf_size);s.d_buf=1*s.lit_bufsize;s.l_buf=(1+2)*s.lit_bufsize;s.level=level;s.strategy=strategy;s.method=method;return deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,Z_DEFLATED,MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY)}function deflate(strm,flush){var old_flush,s;var beg,val;if(!strm||!strm.state||flush>Z_BLOCK||flush<0){return strm?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR}s=strm.state;if(!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH){return err(strm,strm.avail_out===0?Z_BUF_ERROR:Z_STREAM_ERROR)}s.strm=strm;old_flush=s.last_flush;s.last_flush=flush;if(s.status===INIT_STATE){if(s.wrap===2){strm.adler=0;put_byte(s,31);put_byte(s,139);put_byte(s,8);if(!s.gzhead){put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,OS_CODE);s.status=BUSY_STATE}else{put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(!s.gzhead.extra?0:4)+(!s.gzhead.name?0:8)+(!s.gzhead.comment?0:16));put_byte(s,s.gzhead.time&255);put_byte(s,s.gzhead.time>>8&255);put_byte(s,s.gzhead.time>>16&255);put_byte(s,s.gzhead.time>>24&255);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,s.gzhead.os&255);if(s.gzhead.extra&&s.gzhead.extra.length){put_byte(s,s.gzhead.extra.length&255);put_byte(s,s.gzhead.extra.length>>8&255)}if(s.gzhead.hcrc){strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)}s.gzindex=0;s.status=EXTRA_STATE}}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8;var level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2){level_flags=0}else if(s.level<6){level_flags=1}else if(s.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s.strstart!==0){header|=PRESET_DICT}header+=31-header%31;s.status=BUSY_STATE;putShortMSB(s,header);if(s.strstart!==0){putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}strm.adler=1}}if(s.status===EXTRA_STATE){if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){break}}put_byte(s,s.gzhead.extra[s.gzindex]&255);s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(s.gzindex===s.gzhead.extra.length){s.gzindex=0;s.status=NAME_STATE}}else{s.status=NAME_STATE}}if(s.status===NAME_STATE){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.name.length){val=s.gzhead.name.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.gzindex=0;s.status=COMMENT_STATE}}else{s.status=COMMENT_STATE}}if(s.status===COMMENT_STATE){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.comment.length){val=s.gzhead.comment.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.status=HCRC_STATE}}else{s.status=HCRC_STATE}}if(s.status===HCRC_STATE){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size){flush_pending(strm)}if(s.pending+2<=s.pending_buf_size){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);strm.adler=0;s.status=BUSY_STATE}}else{s.status=BUSY_STATE}}if(s.pending!==0){flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH){return err(strm,Z_BUF_ERROR)}if(s.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR)}if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY?deflate_huff(s,flush):s.strategy===Z_RLE?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s.last_flush=-1}return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH){trees._tr_align(s)}else if(flush!==Z_BLOCK){trees._tr_stored_block(s,0,0,false);if(flush===Z_FULL_FLUSH){zero(s.head);if(s.lookahead===0){s.strstart=0;s.block_start=0;s.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}}if(flush!==Z_FINISH){return Z_OK}if(s.wrap<=0){return Z_STREAM_END}if(s.wrap===2){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);put_byte(s,strm.adler>>16&255);put_byte(s,strm.adler>>24&255);put_byte(s,strm.total_in&255);put_byte(s,strm.total_in>>8&255);put_byte(s,strm.total_in>>16&255);put_byte(s,strm.total_in>>24&255)}else{putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}flush_pending(strm);if(s.wrap>0){s.wrap=-s.wrap}return s.pending!==0?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state){return Z_STREAM_ERROR}status=strm.state.status;if(status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE){return err(strm,Z_STREAM_ERROR)}strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var s;var str,n;var wrap;var avail;var next;var input;var tmpDict;if(!strm||!strm.state){return Z_STREAM_ERROR}s=strm.state;wrap=s.wrap;if(wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead){return Z_STREAM_ERROR}if(wrap===1){strm.adler=adler32(strm.adler,dictionary,dictLength,0)}s.wrap=0;if(dictLength>=s.w_size){if(wrap===0){zero(s.head);s.strstart=0;s.block_start=0;s.insert=0}tmpDict=new utils.Buf8(s.w_size);utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0);dictionary=tmpDict;dictLength=s.w_size}avail=strm.avail_in;next=strm.next_in;input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary;fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart;n=s.lookahead-(MIN_MATCH-1);do{s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++}while(--n);s.strstart=str;s.lookahead=MIN_MATCH-1;fill_window(s)}s.strstart+=s.lookahead;s.block_start=s.strstart;s.insert=s.lookahead;s.lookahead=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;strm.next_in=next;strm.input=input;strm.avail_in=avail;s.wrap=wrap;return Z_OK}exports.deflateInit=deflateInit;exports.deflateInit2=deflateInit2;exports.deflateReset=deflateReset;exports.deflateResetKeep=deflateResetKeep;exports.deflateSetHeader=deflateSetHeader;exports.deflate=deflate;exports.deflateEnd=deflateEnd;exports.deflateSetDictionary=deflateSetDictionary;exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":3,"./adler32":4,"./crc32":6,"./messages":11,"./trees":12}],8:[function(require,module,exports){"use strict";var BAD=30;var TYPE=12;module.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=lcode[hold&lmask];dolen:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits<op){hold+=input[_in++]<<bits;bits+=8}len+=hold&(1<<op)-1;hold>>>=op;bits-=op}if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=dcode[hold&dmask];dodist:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bits<op){hold+=input[_in++]<<bits;bits+=8;if(bits<op){hold+=input[_in++]<<bits;bits+=8}}dist+=hold&(1<<op)-1;if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output;
}}else if(wnext<op){from+=wsize+wnext-op;op-=wnext;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=0;if(wnext<len){op=wnext;len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}}else{from+=wnext-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}while(len>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<<op)-1)];continue dodist}else{strm.msg="invalid distance code";state.mode=BAD;break top}break}}else if((op&64)===0){here=lcode[(here&65535)+(hold&(1<<op)-1)];continue dolen}else if(op&32){state.mode=TYPE;break top}else{strm.msg="invalid literal/length code";state.mode=BAD;break top}break}}while(_in<last&&_out<end);len=bits>>3;_in-=len;bits-=len<<3;hold&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold;state.bits=bits;return}},{}],9:[function(require,module,exports){"use strict";var utils=require("../utils/common");var adler32=require("./adler32");var crc32=require("./crc32");var inflate_fast=require("./inffast");var inflate_table=require("./inftrees");var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0;state.window=new utils.Buf8(state.wsize)}if(copy>=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave<state.wsize){state.whave+=dist}}}return 0}function inflate(strm,flush){var state;var input,output;var next;var put;var have,left;var hold;var bits;var _in,_out;var copy;var from;var from_source;var here=0;var here_bits,here_op,here_val;var last_bits,last_op,last_val;var len;var ret;var hbuf=new utils.Buf8(4);var opts;var n;var order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!strm||!strm.state||!strm.output||!strm.input&&strm.avail_in!==0){return Z_STREAM_ERROR}state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO}put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break}while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.wrap&2&&hold===35615){state.check=0;hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<<len;strm.adler=state.check=1;state.mode=hold&512?DICTID:TYPE;hold=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.flags=hold;if((state.flags&255)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}if(state.flags&57344){strm.msg="unknown header flags set";state.mode=BAD;break}if(state.head){state.head.text=hold>>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.time=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.xflags=hold&255;state.head.os=hold>>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length=hold;if(state.head){state.head.extra_len=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.name=null}state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&4096){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.comment+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.comment=null}state.mode=HCRC;case HCRC:if(state.flags&512){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.check&65535)){strm.msg="header crc mismatch";state.mode=BAD;break}hold=0;bits=0}if(state.head){state.head.hcrc=state.flags>>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}strm.adler=state.check=zswap32(hold);hold=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;return Z_NEED_DICT}strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush===Z_BLOCK||flush===Z_TREES){break inf_leave}case TYPEDO:if(state.last){hold>>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.last=hold&1;hold>>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((hold&65535)!==(hold>>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.nlen=(hold&31)+257;hold>>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.lens[order[state.have++]]=hold&7;hold>>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_val<16){hold>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_op&&(here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<<state.distbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.offset+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<<bits;bits+=8}_out-=left;strm.total_out+=_out;state.total+=_out;if(_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)}_out=left;if((state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break}hold=0;bits=0}state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.total&4294967295)){strm.msg="incorrect length check";state.mode=BAD;break}hold=0;bits=0}state.mode=DONE;case DONE:ret=Z_STREAM_END;break inf_leave;case BAD:ret=Z_DATA_ERROR;break inf_leave;case MEM:return Z_MEM_ERROR;case SYNC:default:return Z_STREAM_ERROR}}strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;if(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush!==Z_FINISH)){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out)){state.mode=MEM;return Z_MEM_ERROR}}_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&&_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)}strm.data_type=state.bits+(state.last?64:0)+(state.mode===TYPE?128:0)+(state.mode===LEN_||state.mode===COPY_?256:0);if((_in===0&&_out===0||flush===Z_FINISH)&&ret===Z_OK){ret=Z_BUF_ERROR}return ret}function inflateEnd(strm){if(!strm||!strm.state){return Z_STREAM_ERROR}var state=strm.state;if(state.window){state.window=null}strm.state=null;return Z_OK}function inflateGetHeader(strm,head){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR}state.head=head;head.done=false;return Z_OK}function inflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var state;var dictid;var ret;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR}if(state.mode===DICT){dictid=1;dictid=adler32(dictid,dictionary,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR}}ret=updatewindow(strm,dictionary,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR}state.havedict=1;return Z_OK}exports.inflateReset=inflateReset;exports.inflateReset2=inflateReset2;exports.inflateResetKeep=inflateResetKeep;exports.inflateInit=inflateInit;exports.inflateInit2=inflateInit2;exports.inflate=inflate;exports.inflateEnd=inflateEnd;exports.inflateGetHeader=inflateGetHeader;exports.inflateSetDictionary=inflateSetDictionary;exports.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":3,"./adler32":4,"./crc32":6,"./inffast":8,"./inftrees":10}],10:[function(require,module,exports){"use strict";var utils=require("../utils/common");var MAXBITS=15;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var CODES=0;var LENS=1;var DISTS=2;var lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0];var lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78];var dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0];var dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var bits=opts.bits;var len=0;var sym=0;var min=0,max=0;var root=0;var curr=0;var drop=0;var left=0;var used=0;var huff=0;var incr;var fill;var low;var mask;var next;var base=null;var base_index=0;var end;var count=new utils.Buf16(MAXBITS+1);var offs=new utils.Buf16(MAXBITS+1);var extra=null;var extra_index=0;var here_bits,here_op,here_val;for(len=0;len<=MAXBITS;len++){count[len]=0}for(sym=0;sym<codes;sym++){count[lens[lens_index+sym]]++}root=bits;for(max=MAXBITS;max>=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min<max;min++){if(count[min]!==0){break}}if(root<min){root=min}left=1;for(len=1;len<=MAXBITS;len++){left<<=1;left-=count[len];if(left<0){return-1}}if(left>0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;len<MAXBITS;len++){offs[len+1]=offs[len]+count[len]}for(sym=0;sym<codes;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym}}if(type===CODES){base=extra=work;end=19}else if(type===LENS){base=lbase;base_index-=257;extra=lext;extra_index-=257;end=256}else{base=dbase;extra=dext;end=-1}huff=0;sym=0;len=min;next=table_index;curr=root;drop=0;low=-1;used=1<<root;mask=used-1;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}var i=0;for(;;){i++;here_bits=len-drop;if(work[sym]<end){here_op=0;here_val=work[sym]}else if(work[sym]>end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<<len-drop;fill=1<<curr;min=fill;do{fill-=incr;table[next+(huff>>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<<len-1;while(huff&incr){incr>>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<<curr;while(curr+drop<max){left-=count[curr+drop];if(left<=0){break}curr++;left<<=1}used+=1<<curr;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},{"../utils/common":3}],11:[function(require,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],12:[function(require,module,exports){"use strict";var utils=require("../utils/common");var Z_FIXED=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN=2;function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH=3;var MAX_MATCH=258;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];var extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];var extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];var bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length}var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc}function d_code(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255;s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length){s.bi_buf|=value<<s.bi_valid&65535;put_short(s,s.bi_buf);s.bi_buf=value>>Buf_size-s.bi_valid;s.bi_valid+=length-Buf_size}else{s.bi_buf|=value<<s.bi_valid&65535;s.bi_valid+=length}}function send_code(s,c,tree){send_bits(s,tree[c*2],tree[c*2+1])}function bi_reverse(code,len){var res=0;do{res|=code&1;code>>>=1;res<<=1}while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16){put_short(s,s.bi_buf);s.bi_buf=0;s.bi_valid=0}else if(s.bi_valid>=8){s.pending_buf[s.pending++]=s.bi_buf&255;s.bi_buf>>=8;s.bi_valid-=8}}function gen_bitlen(s,desc){var tree=desc.dyn_tree;var max_code=desc.max_code;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var extra=desc.stat_desc.extra_bits;var base=desc.stat_desc.extra_base;var max_length=desc.stat_desc.max_length;var h;var n,m;var bits;var xbits;var f;var overflow=0;for(bits=0;bits<=MAX_BITS;bits++){s.bl_count[bits]=0}tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;h<HEAP_SIZE;h++){n=s.heap[h];bits=tree[tree[n*2+1]*2+1]+1;if(bits>max_length){bits=max_length;overflow++}tree[n*2+1]=bits;if(n>max_code){continue}s.bl_count[bits]++;xbits=0;if(n>=base){xbits=extra[n-base]}f=tree[n*2];s.opt_len+=f*(bits+xbits);if(has_stree){s.static_len+=f*(stree[n*2+1]+xbits)}}if(overflow===0){return}do{bits=max_length-1;while(s.bl_count[bits]===0){bits--}s.bl_count[bits]--;s.bl_count[bits+1]+=2;s.bl_count[max_length]--;overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){m=s.heap[--h];if(m>max_code){continue}if(tree[m*2+1]!==bits){s.opt_len+=(bits-tree[m*2+1])*tree[m*2];tree[m*2+1]=bits}n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1);var code=0;var bits;var n;for(bits=1;bits<=MAX_BITS;bits++){next_code[bits]=code=code+bl_count[bits-1]<<1}for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0){continue}tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n;var bits;var length;var code;var dist;var bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code<LENGTH_CODES-1;code++){base_length[code]=length;for(n=0;n<1<<extra_lbits[code];n++){_length_code[length++]=code}}_length_code[length-1]=code;dist=0;for(code=0;code<16;code++){base_dist[code]=dist;for(n=0;n<1<<extra_dbits[code];n++){_dist_code[dist++]=code}}dist>>=7;for(;code<D_CODES;code++){base_dist[code]=dist<<7;for(n=0;n<1<<extra_dbits[code]-7;n++){_dist_code[256+dist++]=code}}for(bits=0;bits<=MAX_BITS;bits++){bl_count[bits]=0}n=0;while(n<=143){static_ltree[n*2+1]=8;n++;bl_count[8]++}while(n<=255){static_ltree[n*2+1]=9;n++;bl_count[9]++}while(n<=279){static_ltree[n*2+1]=7;n++;bl_count[7]++}while(n<=287){static_ltree[n*2+1]=8;n++;bl_count[8]++}gen_codes(static_ltree,L_CODES+1,bl_count);for(n=0;n<D_CODES;n++){static_dtree[n*2+1]=5;static_dtree[n*2]=bi_reverse(n,5)}static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS+1,L_CODES,MAX_BITS);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES,MAX_BITS);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES,MAX_BL_BITS)}function init_block(s){var n;for(n=0;n<L_CODES;n++){s.dyn_ltree[n*2]=0}for(n=0;n<D_CODES;n++){s.dyn_dtree[n*2]=0}for(n=0;n<BL_CODES;n++){s.bl_tree[n*2]=0}s.dyn_ltree[END_BLOCK*2]=1;s.opt_len=s.static_len=0;s.last_lit=s.matches=0}function bi_windup(s){if(s.bi_valid>8){put_short(s,s.bi_buf)}else if(s.bi_valid>0){s.pending_buf[s.pending++]=s.bi_buf}s.bi_buf=0;s.bi_valid=0}function copy_block(s,buf,len,header){bi_windup(s);if(header){put_short(s,len);put_short(s,~len)}utils.arraySet(s.pending_buf,s.window,buf,len,s.pending);s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2;var _m2=m*2;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]}function pqdownheap(s,tree,k){var v=s.heap[k];var j=k<<1;while(j<=s.heap_len){if(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)){j++}if(smaller(tree,v,s.heap[j],s.depth)){break}s.heap[k]=s.heap[j];k=j;j<<=1}s.heap[k]=v}function compress_block(s,ltree,dtree){var dist;var lc;var lx=0;var code;var extra;if(s.last_lit!==0){do{dist=s.pending_buf[s.d_buf+lx*2]<<8|s.pending_buf[s.d_buf+lx*2+1];lc=s.pending_buf[s.l_buf+lx];lx++;if(dist===0){send_code(s,lc,ltree)}else{code=_length_code[lc];send_code(s,code+LITERALS+1,ltree);extra=extra_lbits[code];if(extra!==0){lc-=base_length[code];send_bits(s,lc,extra)}dist--;code=d_code(dist);send_code(s,code,dtree);extra=extra_dbits[code];if(extra!==0){dist-=base_dist[code];send_bits(s,dist,extra)}}}while(lx<s.last_lit)}send_code(s,END_BLOCK,ltree)}function build_tree(s,desc){var tree=desc.dyn_tree;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var elems=desc.stat_desc.elems;var n,m;var max_code=-1;var node;s.heap_len=0;s.heap_max=HEAP_SIZE;for(n=0;n<elems;n++){if(tree[n*2]!==0){s.heap[++s.heap_len]=max_code=n;s.depth[n]=0}else{tree[n*2+1]=0}}while(s.heap_len<2){node=s.heap[++s.heap_len]=max_code<2?++max_code:0;tree[node*2]=1;s.depth[node]=0;s.opt_len--;if(has_stree){s.static_len-=stree[node*2+1]}}desc.max_code=max_code;for(n=s.heap_len>>1;n>=1;n--){pqdownheap(s,tree,n)}node=elems;do{n=s.heap[1];s.heap[1]=s.heap[s.heap_len--];pqdownheap(s,tree,1);m=s.heap[1];s.heap[--s.heap_max]=n;s.heap[--s.heap_max]=m;tree[node*2]=tree[n*2]+tree[m*2];s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1;tree[n*2+1]=tree[m*2+1]=node;s.heap[1]=node++;pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1];gen_bitlen(s,desc);gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){s.bl_tree[curlen*2]+=count}else if(curlen!==0){if(curlen!==prevlen){s.bl_tree[curlen*2]++}s.bl_tree[REP_3_6*2]++}else if(count<=10){s.bl_tree[REPZ_3_10*2]++}else{s.bl_tree[REPZ_11_138*2]++}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function send_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){do{send_code(s,curlen,s.bl_tree)}while(--count!==0)}else if(curlen!==0){if(curlen!==prevlen){send_code(s,curlen,s.bl_tree);count--}send_code(s,REP_3_6,s.bl_tree);send_bits(s,count-3,2)}else if(count<=10){
send_code(s,REPZ_3_10,s.bl_tree);send_bits(s,count-3,3)}else{send_code(s,REPZ_11_138,s.bl_tree);send_bits(s,count-11,7)}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function build_bl_tree(s){var max_blindex;scan_tree(s,s.dyn_ltree,s.l_desc.max_code);scan_tree(s,s.dyn_dtree,s.d_desc.max_code);build_tree(s,s.bl_desc);for(max_blindex=BL_CODES-1;max_blindex>=3;max_blindex--){if(s.bl_tree[bl_order[max_blindex]*2+1]!==0){break}}s.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5);send_bits(s,dcodes-1,5);send_bits(s,blcodes-4,4);for(rank=0;rank<blcodes;rank++){send_bits(s,s.bl_tree[bl_order[rank]*2+1],3)}send_tree(s,s.dyn_ltree,lcodes-1);send_tree(s,s.dyn_dtree,dcodes-1)}function detect_data_type(s){var black_mask=4093624447;var n;for(n=0;n<=31;n++,black_mask>>>=1){if(black_mask&1&&s.dyn_ltree[n*2]!==0){return Z_BINARY}}if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0){return Z_TEXT}for(n=32;n<LITERALS;n++){if(s.dyn_ltree[n*2]!==0){return Z_TEXT}}return Z_BINARY}var static_init_done=false;function _tr_init(s){if(!static_init_done){tr_static_init();static_init_done=true}s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc);s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc);s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc);s.bi_buf=0;s.bi_valid=0;init_block(s)}function _tr_stored_block(s,buf,stored_len,last){send_bits(s,(STORED_BLOCK<<1)+(last?1:0),3);copy_block(s,buf,stored_len,true)}function _tr_align(s){send_bits(s,STATIC_TREES<<1,3);send_code(s,END_BLOCK,static_ltree);bi_flush(s)}function _tr_flush_block(s,buf,stored_len,last){var opt_lenb,static_lenb;var max_blindex=0;if(s.level>0){if(s.strm.data_type===Z_UNKNOWN){s.strm.data_type=detect_data_type(s)}build_tree(s,s.l_desc);build_tree(s,s.d_desc);max_blindex=build_bl_tree(s);opt_lenb=s.opt_len+3+7>>>3;static_lenb=s.static_len+3+7>>>3;if(static_lenb<=opt_lenb){opt_lenb=static_lenb}}else{opt_lenb=static_lenb=stored_len+5}if(stored_len+4<=opt_lenb&&buf!==-1){_tr_stored_block(s,buf,stored_len,last)}else if(s.strategy===Z_FIXED||static_lenb===opt_lenb){send_bits(s,(STATIC_TREES<<1)+(last?1:0),3);compress_block(s,static_ltree,static_dtree)}else{send_bits(s,(DYN_TREES<<1)+(last?1:0),3);send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1);compress_block(s,s.dyn_ltree,s.dyn_dtree)}init_block(s);if(last){bi_windup(s)}}function _tr_tally(s,dist,lc){s.pending_buf[s.d_buf+s.last_lit*2]=dist>>>8&255;s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&255;s.pending_buf[s.l_buf+s.last_lit]=lc&255;s.last_lit++;if(dist===0){s.dyn_ltree[lc*2]++}else{s.matches++;dist--;s.dyn_ltree[(_length_code[lc]+LITERALS+1)*2]++;s.dyn_dtree[d_code(dist)*2]++}return s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init;exports._tr_stored_block=_tr_stored_block;exports._tr_flush_block=_tr_flush_block;exports._tr_tally=_tr_tally;exports._tr_align=_tr_align},{"../utils/common":3}],13:[function(require,module,exports){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module.exports=ZStream},{}],14:[function(require,module,exports){(function(process,Buffer){var msg=require("pako/lib/zlib/messages");var zstream=require("pako/lib/zlib/zstream");var zlib_deflate=require("pako/lib/zlib/deflate.js");var zlib_inflate=require("pako/lib/zlib/inflate.js");var constants=require("pako/lib/zlib/constants");for(var key in constants){exports[key]=constants[key]}exports.NONE=0;exports.DEFLATE=1;exports.INFLATE=2;exports.GZIP=3;exports.GUNZIP=4;exports.DEFLATERAW=5;exports.INFLATERAW=6;exports.UNZIP=7;function Zlib(mode){if(mode<exports.DEFLATE||mode>exports.UNZIP)throw new TypeError("Bad argument");this.mode=mode;this.init_done=false;this.write_in_progress=false;this.pending_close=false;this.windowBits=0;this.level=0;this.memLevel=0;this.strategy=0;this.dictionary=null}Zlib.prototype.init=function(windowBits,level,memLevel,strategy,dictionary){this.windowBits=windowBits;this.level=level;this.memLevel=memLevel;this.strategy=strategy;if(this.mode===exports.GZIP||this.mode===exports.GUNZIP)this.windowBits+=16;if(this.mode===exports.UNZIP)this.windowBits+=32;if(this.mode===exports.DEFLATERAW||this.mode===exports.INFLATERAW)this.windowBits=-this.windowBits;this.strm=new zstream;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:var status=zlib_deflate.deflateInit2(this.strm,this.level,exports.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:case exports.UNZIP:var status=zlib_inflate.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(status!==exports.Z_OK){this._error(status);return}this.write_in_progress=false;this.init_done=true};Zlib.prototype.params=function(){throw new Error("deflateParams Not supported")};Zlib.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===exports.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")};Zlib.prototype.write=function(flush,input,in_off,in_len,out,out_off,out_len){this._writeCheck();this.write_in_progress=true;var self=this;process.nextTick(function(){self.write_in_progress=false;var res=self._write(flush,input,in_off,in_len,out,out_off,out_len);self.callback(res[0],res[1]);if(self.pending_close)self.close()});return this};function bufferSet(data,offset){for(var i=0;i<data.length;i++){this[offset+i]=data[i]}}Zlib.prototype.writeSync=function(flush,input,in_off,in_len,out,out_off,out_len){this._writeCheck();return this._write(flush,input,in_off,in_len,out,out_off,out_len)};Zlib.prototype._write=function(flush,input,in_off,in_len,out,out_off,out_len){this.write_in_progress=true;if(flush!==exports.Z_NO_FLUSH&&flush!==exports.Z_PARTIAL_FLUSH&&flush!==exports.Z_SYNC_FLUSH&&flush!==exports.Z_FULL_FLUSH&&flush!==exports.Z_FINISH&&flush!==exports.Z_BLOCK){throw new Error("Invalid flush value")}if(input==null){input=new Buffer(0);in_len=0;in_off=0}if(out._set)out.set=out._set;else out.set=bufferSet;var strm=this.strm;strm.avail_in=in_len;strm.input=input;strm.next_in=in_off;strm.avail_out=out_len;strm.output=out;strm.next_out=out_off;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:var status=zlib_deflate.deflate(strm,flush);break;case exports.UNZIP:case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:var status=zlib_inflate.inflate(strm,flush);break;default:throw new Error("Unknown mode "+this.mode)}if(status!==exports.Z_STREAM_END&&status!==exports.Z_OK){this._error(status)}this.write_in_progress=false;return[strm.avail_in,strm.avail_out]};Zlib.prototype.close=function(){if(this.write_in_progress){this.pending_close=true;return}this.pending_close=false;if(this.mode===exports.DEFLATE||this.mode===exports.GZIP||this.mode===exports.DEFLATERAW){zlib_deflate.deflateEnd(this.strm)}else{zlib_inflate.inflateEnd(this.strm)}this.mode=exports.NONE};Zlib.prototype.reset=function(){switch(this.mode){case exports.DEFLATE:case exports.DEFLATERAW:var status=zlib_deflate.deflateReset(this.strm);break;case exports.INFLATE:case exports.INFLATERAW:var status=zlib_inflate.inflateReset(this.strm);break}if(status!==exports.Z_OK){this._error(status)}};Zlib.prototype._error=function(status){this.onerror(msg[status]+": "+this.strm.msg,status);this.write_in_progress=false;if(this.pending_close)this.close()};exports.Zlib=Zlib}).call(this,require("_process"),require("buffer").Buffer)},{_process:23,buffer:16,"pako/lib/zlib/constants":5,"pako/lib/zlib/deflate.js":7,"pako/lib/zlib/inflate.js":9,"pako/lib/zlib/messages":11,"pako/lib/zlib/zstream":13}],15:[function(require,module,exports){(function(process,Buffer){var Transform=require("_stream_transform");var binding=require("./binding");var util=require("util");var assert=require("assert").ok;binding.Z_MIN_WINDOWBITS=8;binding.Z_MAX_WINDOWBITS=15;binding.Z_DEFAULT_WINDOWBITS=15;binding.Z_MIN_CHUNK=64;binding.Z_MAX_CHUNK=Infinity;binding.Z_DEFAULT_CHUNK=16*1024;binding.Z_MIN_MEMLEVEL=1;binding.Z_MAX_MEMLEVEL=9;binding.Z_DEFAULT_MEMLEVEL=8;binding.Z_MIN_LEVEL=-1;binding.Z_MAX_LEVEL=9;binding.Z_DEFAULT_LEVEL=binding.Z_DEFAULT_COMPRESSION;Object.keys(binding).forEach(function(k){if(k.match(/^Z/))exports[k]=binding[k]});exports.codes={Z_OK:binding.Z_OK,Z_STREAM_END:binding.Z_STREAM_END,Z_NEED_DICT:binding.Z_NEED_DICT,Z_ERRNO:binding.Z_ERRNO,Z_STREAM_ERROR:binding.Z_STREAM_ERROR,Z_DATA_ERROR:binding.Z_DATA_ERROR,Z_MEM_ERROR:binding.Z_MEM_ERROR,Z_BUF_ERROR:binding.Z_BUF_ERROR,Z_VERSION_ERROR:binding.Z_VERSION_ERROR};Object.keys(exports.codes).forEach(function(k){exports.codes[exports.codes[k]]=k});exports.Deflate=Deflate;exports.Inflate=Inflate;exports.Gzip=Gzip;exports.Gunzip=Gunzip;exports.DeflateRaw=DeflateRaw;exports.InflateRaw=InflateRaw;exports.Unzip=Unzip;exports.createDeflate=function(o){return new Deflate(o)};exports.createInflate=function(o){return new Inflate(o)};exports.createDeflateRaw=function(o){return new DeflateRaw(o)};exports.createInflateRaw=function(o){return new InflateRaw(o)};exports.createGzip=function(o){return new Gzip(o)};exports.createGunzip=function(o){return new Gunzip(o)};exports.createUnzip=function(o){return new Unzip(o)};exports.deflate=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Deflate(opts),buffer,callback)};exports.deflateSync=function(buffer,opts){return zlibBufferSync(new Deflate(opts),buffer)};exports.gzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Gzip(opts),buffer,callback)};exports.gzipSync=function(buffer,opts){return zlibBufferSync(new Gzip(opts),buffer)};exports.deflateRaw=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new DeflateRaw(opts),buffer,callback)};exports.deflateRawSync=function(buffer,opts){return zlibBufferSync(new DeflateRaw(opts),buffer)};exports.unzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Unzip(opts),buffer,callback)};exports.unzipSync=function(buffer,opts){return zlibBufferSync(new Unzip(opts),buffer)};exports.inflate=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Inflate(opts),buffer,callback)};exports.inflateSync=function(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)};exports.gunzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Gunzip(opts),buffer,callback)};exports.gunzipSync=function(buffer,opts){return zlibBufferSync(new Gunzip(opts),buffer)};exports.inflateRaw=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new InflateRaw(opts),buffer,callback)};exports.inflateRawSync=function(buffer,opts){return zlibBufferSync(new InflateRaw(opts),buffer)};function zlibBuffer(engine,buffer,callback){var buffers=[];var nread=0;engine.on("error",onError);engine.on("end",onEnd);engine.end(buffer);flow();function flow(){var chunk;while(null!==(chunk=engine.read())){buffers.push(chunk);nread+=chunk.length}engine.once("readable",flow)}function onError(err){engine.removeListener("end",onEnd);engine.removeListener("readable",flow);callback(err)}function onEnd(){var buf=Buffer.concat(buffers,nread);buffers=[];callback(null,buf);engine.close()}}function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=new Buffer(buffer);if(!Buffer.isBuffer(buffer))throw new TypeError("Not a string or buffer");var flushFlag=binding.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function Deflate(opts){if(!(this instanceof Deflate))return new Deflate(opts);Zlib.call(this,opts,binding.DEFLATE)}function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);Zlib.call(this,opts,binding.INFLATE)}function Gzip(opts){if(!(this instanceof Gzip))return new Gzip(opts);Zlib.call(this,opts,binding.GZIP)}function Gunzip(opts){if(!(this instanceof Gunzip))return new Gunzip(opts);Zlib.call(this,opts,binding.GUNZIP)}function DeflateRaw(opts){if(!(this instanceof DeflateRaw))return new DeflateRaw(opts);Zlib.call(this,opts,binding.DEFLATERAW)}function InflateRaw(opts){if(!(this instanceof InflateRaw))return new InflateRaw(opts);Zlib.call(this,opts,binding.INFLATERAW)}function Unzip(opts){if(!(this instanceof Unzip))return new Unzip(opts);Zlib.call(this,opts,binding.UNZIP)}function Zlib(opts,mode){this._opts=opts=opts||{};this._chunkSize=opts.chunkSize||exports.Z_DEFAULT_CHUNK;Transform.call(this,opts);if(opts.flush){if(opts.flush!==binding.Z_NO_FLUSH&&opts.flush!==binding.Z_PARTIAL_FLUSH&&opts.flush!==binding.Z_SYNC_FLUSH&&opts.flush!==binding.Z_FULL_FLUSH&&opts.flush!==binding.Z_FINISH&&opts.flush!==binding.Z_BLOCK){throw new Error("Invalid flush flag: "+opts.flush)}}this._flushFlag=opts.flush||binding.Z_NO_FLUSH;if(opts.chunkSize){if(opts.chunkSize<exports.Z_MIN_CHUNK||opts.chunkSize>exports.Z_MAX_CHUNK){throw new Error("Invalid chunk size: "+opts.chunkSize)}}if(opts.windowBits){if(opts.windowBits<exports.Z_MIN_WINDOWBITS||opts.windowBits>exports.Z_MAX_WINDOWBITS){throw new Error("Invalid windowBits: "+opts.windowBits)}}if(opts.level){if(opts.level<exports.Z_MIN_LEVEL||opts.level>exports.Z_MAX_LEVEL){throw new Error("Invalid compression level: "+opts.level)}}if(opts.memLevel){if(opts.memLevel<exports.Z_MIN_MEMLEVEL||opts.memLevel>exports.Z_MAX_MEMLEVEL){throw new Error("Invalid memLevel: "+opts.memLevel)}}if(opts.strategy){if(opts.strategy!=exports.Z_FILTERED&&opts.strategy!=exports.Z_HUFFMAN_ONLY&&opts.strategy!=exports.Z_RLE&&opts.strategy!=exports.Z_FIXED&&opts.strategy!=exports.Z_DEFAULT_STRATEGY){throw new Error("Invalid strategy: "+opts.strategy)}}if(opts.dictionary){if(!Buffer.isBuffer(opts.dictionary)){throw new Error("Invalid dictionary: it should be a Buffer instance")}}this._binding=new binding.Zlib(mode);var self=this;this._hadError=false;this._binding.onerror=function(message,errno){self._binding=null;self._hadError=true;var error=new Error(message);error.errno=errno;error.code=exports.codes[errno];self.emit("error",error)};var level=exports.Z_DEFAULT_COMPRESSION;if(typeof opts.level==="number")level=opts.level;var strategy=exports.Z_DEFAULT_STRATEGY;if(typeof opts.strategy==="number")strategy=opts.strategy;this._binding.init(opts.windowBits||exports.Z_DEFAULT_WINDOWBITS,level,opts.memLevel||exports.Z_DEFAULT_MEMLEVEL,strategy,opts.dictionary);this._buffer=new Buffer(this._chunkSize);this._offset=0;this._closed=false;this._level=level;this._strategy=strategy;this.once("end",this.close)}util.inherits(Zlib,Transform);Zlib.prototype.params=function(level,strategy,callback){if(level<exports.Z_MIN_LEVEL||level>exports.Z_MAX_LEVEL){throw new RangeError("Invalid compression level: "+level)}if(strategy!=exports.Z_FILTERED&&strategy!=exports.Z_HUFFMAN_ONLY&&strategy!=exports.Z_RLE&&strategy!=exports.Z_FIXED&&strategy!=exports.Z_DEFAULT_STRATEGY){throw new TypeError("Invalid strategy: "+strategy)}if(this._level!==level||this._strategy!==strategy){var self=this;this.flush(binding.Z_SYNC_FLUSH,function(){self._binding.params(level,strategy);if(!self._hadError){self._level=level;self._strategy=strategy;if(callback)callback()}})}else{process.nextTick(callback)}};Zlib.prototype.reset=function(){return this._binding.reset()};Zlib.prototype._flush=function(callback){this._transform(new Buffer(0),"",callback)};Zlib.prototype.flush=function(kind,callback){var ws=this._writableState;if(typeof kind==="function"||kind===void 0&&!callback){callback=kind;kind=binding.Z_FULL_FLUSH}if(ws.ended){if(callback)process.nextTick(callback)}else if(ws.ending){if(callback)this.once("end",callback)}else if(ws.needDrain){var self=this;this.once("drain",function(){self.flush(callback)})}else{this._flushFlag=kind;this.write(new Buffer(0),"",callback)}};Zlib.prototype.close=function(callback){if(callback)process.nextTick(callback);if(this._closed)return;this._closed=true;this._binding.close();var self=this;process.nextTick(function(){self.emit("close")})};Zlib.prototype._transform=function(chunk,encoding,cb){var flushFlag;var ws=this._writableState;var ending=ws.ending||ws.ended;var last=ending&&(!chunk||ws.length===chunk.length);if(!chunk===null&&!Buffer.isBuffer(chunk))return cb(new Error("invalid input"));if(last)flushFlag=binding.Z_FINISH;else{flushFlag=this._flushFlag;if(chunk.length>=ws.length){this._flushFlag=this._opts.flush||binding.Z_NO_FLUSH}}var self=this;this._processChunk(chunk,flushFlag,cb)};Zlib.prototype._processChunk=function(chunk,flushFlag,cb){var availInBefore=chunk&&chunk.length;var availOutBefore=this._chunkSize-this._offset;var inOff=0;var self=this;var async=typeof cb==="function";if(!async){var buffers=[];var nread=0;var error;this.on("error",function(er){error=er});do{var res=this._binding.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore)}while(!this._hadError&&callback(res[0],res[1]));if(this._hadError){throw error}var buf=Buffer.concat(buffers,nread);this.close();return buf}var req=this._binding.write(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);req.buffer=chunk;req.callback=callback;function callback(availInAfter,availOutAfter){if(self._hadError)return;var have=availOutBefore-availOutAfter;assert(have>=0,"have should not go down");if(have>0){var out=self._buffer.slice(self._offset,self._offset+have);self._offset+=have;if(async){self.push(out)}else{buffers.push(out);nread+=out.length}}if(availOutAfter===0||self._offset>=self._chunkSize){availOutBefore=self._chunkSize;self._offset=0;self._buffer=new Buffer(self._chunkSize)}if(availOutAfter===0){inOff+=availInBefore-availInAfter;availInBefore=availInAfter;if(!async)return true;var newReq=self._binding.write(flushFlag,chunk,inOff,availInBefore,self._buffer,self._offset,self._chunkSize);newReq.callback=callback;newReq.buffer=chunk;return}if(!async)return false;cb()}};util.inherits(Deflate,Zlib);util.inherits(Inflate,Zlib);util.inherits(Gzip,Zlib);util.inherits(Gunzip,Zlib);util.inherits(DeflateRaw,Zlib);util.inherits(InflateRaw,Zlib);util.inherits(Unzip,Zlib)}).call(this,require("_process"),require("buffer").Buffer)},{"./binding":14,_process:23,_stream_transform:38,assert:1,buffer:16,util:44}],16:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()<length){throw new RangeError("Invalid typed array length")}if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(length);that.__proto__=Buffer.prototype}else{if(that===null){that=new Buffer(length)}that.length=length}return that}function Buffer(arg,encodingOrOffset,length){if(!Buffer.TYPED_ARRAY_SUPPORT&&!(this instanceof Buffer)){return new Buffer(arg,encodingOrOffset,length)}if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(this,arg)}return from(this,arg,encodingOrOffset,length)}Buffer.poolSize=8192;Buffer._augment=function(arr){arr.__proto__=Buffer.prototype;return arr};function from(that,value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){return fromArrayBuffer(that,value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(that,value,encodingOrOffset)}return fromObject(that,value)}Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)};if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true})}}function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(that,size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(that,size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill)}return createBuffer(that,size)}Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)};function allocUnsafe(that,size){assertSize(size);that=createBuffer(that,size<0?0:checked(size)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<size;++i){that[i]=0}}return that}Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)};function fromString(that,string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;that=createBuffer(that,length);var actual=that.write(string,encoding);if(actual!==length){that=that.slice(0,actual)}return that}function fromArrayLike(that,array){var length=array.length<0?0:checked(array.length)|0;that=createBuffer(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromArrayBuffer(that,array,byteOffset,length){array.byteLength;if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError("'offset' is out of bounds")}if(array.byteLength<byteOffset+(length||0)){throw new RangeError("'length' is out of bounds")}if(byteOffset===undefined&&length===undefined){array=new Uint8Array(array)}else if(length===undefined){array=new Uint8Array(array,byteOffset)}else{array=new Uint8Array(array,byteOffset,length)}if(Buffer.TYPED_ARRAY_SUPPORT){that=array;that.__proto__=Buffer.prototype}else{that=fromArrayLike(that,array)}return that}function fromObject(that,obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;that=createBuffer(that,len);if(that.length===0){return that}obj.copy(that,0,0,len);return that}if(obj){if(typeof ArrayBuffer!=="undefined"&&obj.buffer instanceof ArrayBuffer||"length"in obj){if(typeof obj.length!=="number"||isnan(obj.length)){return createBuffer(that,0)}return fromArrayLike(that,obj)}if(obj.type==="Buffer"&&isArray(obj.data)){return fromArrayLike(that,obj.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(typeof ArrayBuffer!=="undefined"&&typeof ArrayBuffer.isView==="function"&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){string=""+string}var len=string.length;if(len===0)return 0;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;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}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}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};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};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}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}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length);
}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}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":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>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}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]&127)}return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;++i){newBuf[i]=this[i+start]}}return newBuf};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*=256)){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*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(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*=256)){val+=this[offset+i]*mul}mul*=128;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*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}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&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;++i){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;++i){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}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&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}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)};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;if(end===start)return 0;if(target.length===0||this.length===0)return 0;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");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){for(i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){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};Buffer.prototype.fill=function fill(val,start,end,encoding){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}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString());var len=bytes.length;for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":17,ieee754:18,isarray:19}],17:[function(require,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")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i<l;i+=4,j+=3){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&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}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&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}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;var output="";var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],18:[function(require,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&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],19:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],20:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;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(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{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){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;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={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];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.error("(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"){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};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;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}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){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}},{}],21:[function(require,module,exports){if(typeof Object.create==="function"){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{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],22:[function(require,module,exports){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)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],23:[function(require,module,exports){var process=module.exports={};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){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){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)}};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="";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}},{}],24:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":25}],25:[function(require,module,exports){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args");var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_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)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;processNextTick(onEndNT,this)}function onEndNT(self){self.end()}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}},{"./_stream_readable":27,"./_stream_writable":29,"core-util-is":32,inherits:21,"process-nextick-args":34}],26:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("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":28,"core-util-is":32,inherits:21}],27:[function(require,module,exports){(function(process){"use strict";module.exports=Readable;var processNextTick=require("process-nextick-args");var isArray=require("isarray");var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");var util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util");var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=require("./internal/streams/BufferList");var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{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||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;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;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{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)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc;return this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}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(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(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}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(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false;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(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}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;emitReadable(stream)}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)}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)break;else len=state.length}state.readingMore=false}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:cleanup;if(state.endEmitted)processNextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){debug("onunpipe");if(readable===src){cleanup()}}function onend(){debug("onend");dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=false;function cleanup(){debug("cleanup");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",cleanup);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}var increasedAwaitDrain=false;src.on("data",ondata);function ondata(chunk){debug("ondata");increasedAwaitDrain=false;var ret=dest.write(chunk);if(false===ret&&!increasedAwaitDrain){if((state.pipesCount===1&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);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)}dest.emit("pipe",src);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;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){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)}return this}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);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"){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,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}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){}}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);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()}});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)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;var ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){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{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(n<list.head.data.length){ret=list.head.data.slice(0,n);list.head.data=list.head.data.slice(n)}else if(n===list.head.data.length){ret=list.shift()}else{ret=hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list)}return ret}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}function copyFromBuffer(n,list){var ret=bufferShim.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(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){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,require("_process"))},{"./_stream_duplex":25,"./internal/streams/BufferList":30,_process:23,buffer:16,"buffer-shims":31,"core-util-is":32,events:20,inherits:21,isarray:33,"process-nextick-args":34,"string_decoder/":41,util:2}],28:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("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("no writecb in Transform class"));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;this._readableState.needReadable=true;this._readableState.sync=false;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}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)};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)}};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{ts.needTransform=true}};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!==null&&data!==undefined)stream.push(data);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":25,"core-util-is":32,inherits:21}],29:[function(require,module,exports){(function(process){"use strict";module.exports=Writable;var processNextTick=require("process-nextick-args");var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var 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.")})}catch(_){}})();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||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}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(!Buffer.isBuffer(chunk)&&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;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,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){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=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb);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)processNextTick(cb,er);else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}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{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)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount;var buffer=new Array(l);var holder=state.corkedRequestsFree;holder.entry=entry;var count=0;while(entry){buffer[count]=entry;entry=entry.next;count+=1}doWrite(stream,state,true,state.length,buffer,"",holder.finish);state.pendingcb++;state.lastBufferedRequest=null;if(holder.next){state.corkedRequestsFree=holder.next;holder.next=null}else{state.corkedRequestsFree=new CorkedRequest(state)}}else{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(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);if(state.corked){state.corked=1;this.uncork()}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 prefinish(stream,state){if(!state.prefinished){state.prefinished=true;stream.emit("prefinish")}}function finishMaybe(stream,state){var need=needFinish(state);if(need){if(state.pendingcb===0){prefinish(stream,state);state.finished=true;stream.emit("finish")}else{prefinish(stream,state)}}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 CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(err){var entry=_this.entry;_this.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=_this}else{state.corkedRequestsFree=_this}}}}).call(this,require("_process"))},{"./_stream_duplex":25,_process:23,buffer:16,"buffer-shims":31,"core-util-is":32,events:20,inherits:21,"process-nextick-args":34,"util-deprecate":35}],30:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");module.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(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(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){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(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(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(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:16,"buffer-shims":31}],31:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++i<size){buf[i]=fillBuf[i%flen]}}else{buf.fill(_fill)}return buf};exports.allocUnsafe=function allocUnsafe(size){if(typeof Buffer.allocUnsafe==="function"){return Buffer.allocUnsafe(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:16}],32:[function(require,module,exports){(function(Buffer){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"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":22}],33:[function(require,module,exports){arguments[4][19][0].apply(exports,arguments)},{dup:19}],34:[function(require,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,require("_process"))},{_process:23}],35:[function(require,module,exports){(function(global){module.exports=deprecate;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}function config(name){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:{})},{}],36:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":26}],37:[function(require,module,exports){(function(process){var Stream=function(){try{return require("st"+"ream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=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");if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module.exports=Stream}}).call(this,require("_process"))},{"./lib/_stream_duplex.js":25,"./lib/_stream_passthrough.js":26,"./lib/_stream_readable.js":27,"./lib/_stream_transform.js":28,"./lib/_stream_writable.js":29,_process:23}],38:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":28}],39:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":29}],40:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:20,inherits:21,"readable-stream/duplex.js":24,"readable-stream/passthrough.js":36,"readable-stream/readable.js":37,"readable-stream/transform.js":38,"readable-stream/writable.js":39}],41:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(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 assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:16}],42:[function(require,module,exports){arguments[4][21][0].apply(exports,arguments)},{dup:21}],43:[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"}},{}],44:[function(require,module,exports){(function(process,global){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};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}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;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]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+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){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}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=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}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");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]}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"||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"];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(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){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 global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":43,_process:23,inherits:42}],45:[function(require,module,exports){(function(Buffer){"use strict";var interlaceUtils=require("./interlace");var pixelBppMap={1:{0:0,1:0,2:0,3:255},2:{0:0,1:0,2:0,3:1},3:{0:0,1:1,2:2,3:255},4:{0:0,1:1,2:2,3:3}};function bitRetriever(data,depth){var leftOver=[];var i=0;function split(){if(i===data.length){throw new Error("Ran out of data")}var byte=data[i];i++;var byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1;switch(depth){default:throw new Error("unrecognised depth");case 16:byte2=data[i];i++;leftOver.push((byte<<8)+byte2);break;case 4:byte2=byte&15;byte1=byte>>4;leftOver.push(byte1,byte2);break;case 2:byte4=byte&3;byte3=byte>>2&3;byte2=byte>>4&3;byte1=byte>>6&3;leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=byte&1;byte7=byte>>1&1;byte6=byte>>2&1;byte5=byte>>3&1;byte4=byte>>4&1;byte3=byte>>5&1;byte2=byte>>6&1;byte1=byte>>7&1;leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8);break}}return{get:function(count){while(leftOver.length<count){split()}var returner=leftOver.slice(0,count);leftOver=leftOver.slice(count);return returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length){throw new Error("extra data found")}}}}function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){var imageWidth=image.width;var imageHeight=image.height;var imagePass=image.index;for(var y=0;y<imageHeight;y++){for(var x=0;x<imageWidth;x++){var pxPos=getPxPos(x,y,imagePass);for(var i=0;i<4;i++){var idx=pixelBppMap[bpp][i];if(idx===255){pxData[pxPos+i]=255}else{var dataPos=idx+rawPos;if(dataPos===data.length){throw new Error("Ran out of data")}pxData[pxPos+i]=data[dataPos]}}rawPos+=bpp}}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){var imageWidth=image.width;var imageHeight=image.height;var imagePass=image.index;for(var y=0;y<imageHeight;y++){for(var x=0;x<imageWidth;x++){var pixelData=bits.get(bpp);var pxPos=getPxPos(x,y,imagePass);for(var i=0;i<4;i++){var idx=pixelBppMap[bpp][i];pxData[pxPos+i]=idx!==255?pixelData[idx]:maxBit}}bits.resetAfterLine()}}exports.dataToBitMap=function(data,bitmapInfo){var width=bitmapInfo.width;var height=bitmapInfo.height;var depth=bitmapInfo.depth;var bpp=bitmapInfo.bpp;var interlace=bitmapInfo.interlace;if(depth!==8){var bits=bitRetriever(data,depth)}var pxData;if(depth<=8){pxData=new Buffer(width*height*4)}else{pxData=new Uint16Array(width*height*4)}var maxBit=Math.pow(2,depth)-1;var rawPos=0;var images;var getPxPos;if(interlace){images=interlaceUtils.getImagePasses(width,height);getPxPos=interlaceUtils.getInterlaceIterator(width,height)}else{var nonInterlacedPxPos=0;getPxPos=function(){var returner=nonInterlacedPxPos;nonInterlacedPxPos+=4;return returner};images=[{width:width,height:height}]}for(var imageIndex=0;imageIndex<images.length;imageIndex++){if(depth===8){rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos)}else{mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit)}}if(depth===8){if(rawPos!==data.length){throw new Error("extra data found")}}else{bits.end()}return pxData}}).call(this,require("buffer").Buffer)},{"./interlace":55,buffer:16}],46:[function(require,module,exports){(function(Buffer){"use strict";var constants=require("./constants");module.exports=function(data,width,height,options){var outHasAlpha=options.colorType===constants.COLORTYPE_COLOR_ALPHA;if(options.inputHasAlpha&&outHasAlpha){return data}if(!options.inputHasAlpha&&!outHasAlpha){return data}var outBpp=outHasAlpha?4:3;var outData=new Buffer(width*height*outBpp);var inBpp=options.inputHasAlpha?4:3;var inIndex=0;var outIndex=0;var bgColor=options.bgColor||{};if(bgColor.red===undefined){bgColor.red=255}if(bgColor.green===undefined){bgColor.green=255}if(bgColor.blue===undefined){bgColor.blue=255}for(var y=0;y<height;y++){for(var x=0;x<width;x++){var red=data[inIndex];var green=data[inIndex+1];var blue=data[inIndex+2];var alpha;if(options.inputHasAlpha){alpha=data[inIndex+3];if(!outHasAlpha){alpha/=255;red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),255);green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),255);blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),255)}}else{alpha=255}outData[outIndex]=red;outData[outIndex+1]=green;outData[outIndex+2]=blue;if(outHasAlpha){outData[outIndex+3]=alpha}inIndex+=inBpp;outIndex+=outBpp}}return outData}}).call(this,require("buffer").Buffer)},{"./constants":48,buffer:16}],47:[function(require,module,exports){(function(process,Buffer){"use strict";var util=require("util");var Stream=require("stream");var ChunkStream=module.exports=function(){Stream.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};util.inherits(ChunkStream,Stream);ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback});process.nextTick(function(){this._process();if(this._paused&&this._reads.length>0){this._paused=false;this.emit("drain")}}.bind(this))};ChunkStream.prototype.write=function(data,encoding){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}var dataBuffer;if(Buffer.isBuffer(data)){dataBuffer=data}else{dataBuffer=new Buffer(data,encoding||this._encoding)}this._buffers.push(dataBuffer);this._buffered+=dataBuffer.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};ChunkStream.prototype.end=function(data,encoding){if(data){this.write(data,encoding)}this.writable=false;if(!this._buffers){return}if(this._buffers.length===0){this._end()}else{this._buffers.push(null);this._process()}};ChunkStream.prototype.destroySoon=ChunkStream.prototype.end;ChunkStream.prototype._end=function(){if(this._reads.length>0){this.emit("error",new Error("There are some read requests waiting on finished stream"))}this.destroy()};ChunkStream.prototype.destroy=function(){if(!this._buffers){return}this.writable=false;this._reads=null;this._buffers=null;this.emit("close")};ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();var smallerBuf=this._buffers[0];if(smallerBuf.length>read.length){this._buffered-=read.length;this._buffers[0]=smallerBuf.slice(read.length);read.func.call(this,smallerBuf.slice(0,read.length))}else{this._buffered-=smallerBuf.length;this._buffers.shift();read.func.call(this,smallerBuf)}};ChunkStream.prototype._processRead=function(read){this._reads.shift();var pos=0;var count=0;var data=new Buffer(read.length);while(pos<read.length){var buf=this._buffers[count++];var len=Math.min(buf.length,read.length-pos);buf.copy(data,pos,0,len);pos+=len;if(len!==buf.length){this._buffers[--count]=buf.slice(len)}}if(count>0){this._buffers.splice(0,count)}this._buffered-=read.length;read.func.call(this,data)};ChunkStream.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){var read=this._reads[0];if(read.allowLess){this._processReadAllowingLess(read)}else if(this._buffered>=read.length){this._processRead(read)}else{break}}if(this._buffers&&this._buffers.length>0&&this._buffers[0]===null){this._end()}}catch(ex){this.emit("error",ex)}}}).call(this,require("_process"),require("buffer").Buffer)},{_process:23,buffer:16,stream:40,util:44}],48:[function(require,module,exports){"use strict";module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}},{}],49:[function(require,module,exports){"use strict";var crcTable=[];(function(){for(var i=0;i<256;i++){var currentCrc=i;for(var j=0;j<8;j++){if(currentCrc&1){currentCrc=3988292384^currentCrc>>>1}else{currentCrc=currentCrc>>>1}}crcTable[i]=currentCrc}})();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(data){for(var i=0;i<data.length;i++){this._crc=crcTable[(this._crc^data[i])&255]^this._crc>>>8}return true};CrcCalculator.prototype.crc32=function(){return this._crc^-1};CrcCalculator.crc32=function(buf){var crc=-1;for(var i=0;i<buf.length;i++){crc=crcTable[(crc^buf[i])&255]^crc>>>8}return crc^-1}},{}],50:[function(require,module,exports){(function(Buffer){"use strict";var paethPredictor=require("./paeth-predictor");function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){pxData.copy(rawData,rawPos,pxPos,pxPos+byteWidth)}function filterSumNone(pxData,pxPos,byteWidth){var sum=0;var length=pxPos+byteWidth;for(var i=pxPos;i<length;i++){sum+=Math.abs(pxData[i])}return sum}function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}}function filterSumSub(pxData,pxPos,byteWidth,bpp){var sum=0;for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum}function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(var x=0;x<byteWidth;x++){var up=pxPos>0?pxData[pxPos+x-byteWidth]:0;var val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}}function filterSumUp(pxData,pxPos,byteWidth){var sum=0;var length=pxPos+byteWidth;for(var x=pxPos;x<length;x++){var up=pxPos>0?pxData[x-byteWidth]:0;var val=pxData[x]-up;sum+=Math.abs(val)}return sum}function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var up=pxPos>0?pxData[pxPos+x-byteWidth]:0;var val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}}function filterSumAvg(pxData,pxPos,byteWidth,bpp){var sum=0;for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var up=pxPos>0?pxData[pxPos+x-byteWidth]:0;var val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum}function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var up=pxPos>0?pxData[pxPos+x-byteWidth]:0;var upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0;var val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}function filterSumPaeth(pxData,pxPos,byteWidth,bpp){var sum=0;for(var x=0;x<byteWidth;x++){var left=x>=bpp?pxData[pxPos+x-bpp]:0;var up=pxPos>0?pxData[pxPos+x-byteWidth]:0;var upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0;var val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth};var filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(pxData,width,height,options,bpp){var filterTypes;if(!("filterType"in options)||options.filterType===-1){filterTypes=[0,1,2,3,4]}else if(typeof options.filterType==="number"){filterTypes=[options.filterType]}else{throw new Error("unrecognised filter types")}var byteWidth=width*bpp;var rawPos=0;var pxPos=0;var rawData=new Buffer((byteWidth+1)*height);var sel=filterTypes[0];for(var y=0;y<height;y++){if(filterTypes.length>1){var min=Infinity;for(var i=0;i<filterTypes.length;i++){var sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);if(sum<min){sel=filterTypes[i];min=sum}}}rawData[rawPos]=sel;rawPos++;filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp);rawPos+=byteWidth;pxPos+=byteWidth}return rawData}}).call(this,require("buffer").Buffer)},{"./paeth-predictor":59,buffer:16}],51:[function(require,module,exports){(function(Buffer){"use strict";var util=require("util");var ChunkStream=require("./chunkstream");var Filter=require("./filter-parse");var FilterAsync=module.exports=function(bitmapInfo){ChunkStream.call(this);var buffers=[];var that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}});this._filter.start()};util.inherits(FilterAsync,ChunkStream)}).call(this,require("buffer").Buffer)},{"./chunkstream":47,"./filter-parse":53,buffer:16,util:44}],52:[function(require,module,exports){(function(Buffer){"use strict";var SyncReader=require("./sync-reader");var Filter=require("./filter-parse");exports.process=function(inBuffer,bitmapInfo){var outBuffers=[];var reader=new SyncReader(inBuffer);var filter=new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}});filter.start();reader.process();return Buffer.concat(outBuffers)}}).call(this,require("buffer").Buffer)},{"./filter-parse":53,"./sync-reader":64,buffer:16}],53:[function(require,module,exports){(function(Buffer){"use strict";var interlaceUtils=require("./interlace");var paethPredictor=require("./paeth-predictor");function getByteWidth(width,bpp,depth){var byteWidth=width*bpp;if(depth!==8){byteWidth=Math.ceil(byteWidth/(8/depth))}return byteWidth}var Filter=module.exports=function(bitmapInfo,dependencies){var width=bitmapInfo.width;var height=bitmapInfo.height;var interlace=bitmapInfo.interlace;
var bpp=bitmapInfo.bpp;var depth=bitmapInfo.depth;this.read=dependencies.read;this.write=dependencies.write;this.complete=dependencies.complete;this._imageIndex=0;this._images=[];if(interlace){var passes=interlaceUtils.getImagePasses(width,height);for(var i=0;i<passes.length;i++){this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}}else{this._images.push({byteWidth:getByteWidth(width,bpp,depth),height:height,lineIndex:0})}if(depth===8){this._xComparison=bpp}else if(depth===16){this._xComparison=bpp*2}else{this._xComparison=1}};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){var xComparison=this._xComparison;var xBiggerThan=xComparison-1;for(var x=0;x<byteWidth;x++){var rawByte=rawData[1+x];var f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}};Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){var lastLine=this._lastLine;for(var x=0;x<byteWidth;x++){var rawByte=rawData[1+x];var f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}};Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){var xComparison=this._xComparison;var xBiggerThan=xComparison-1;var lastLine=this._lastLine;for(var x=0;x<byteWidth;x++){var rawByte=rawData[1+x];var f3Up=lastLine?lastLine[x]:0;var f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;var f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}};Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){var xComparison=this._xComparison;var xBiggerThan=xComparison-1;var lastLine=this._lastLine;for(var x=0;x<byteWidth;x++){var rawByte=rawData[1+x];var f4Up=lastLine?lastLine[x]:0;var f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;var f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0;var f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}};Filter.prototype._reverseFilterLine=function(rawData){var filter=rawData[0];var unfilteredLine;var currentImage=this._images[this._imageIndex];var byteWidth=currentImage.byteWidth;if(filter===0){unfilteredLine=rawData.slice(1,byteWidth+1)}else{unfilteredLine=new Buffer(byteWidth);switch(filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw new Error("Unrecognised filter type - "+filter)}}this.write(unfilteredLine);currentImage.lineIndex++;if(currentImage.lineIndex>=currentImage.height){this._lastLine=null;this._imageIndex++;currentImage=this._images[this._imageIndex]}else{this._lastLine=unfilteredLine}if(currentImage){this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}).call(this,require("buffer").Buffer)},{"./interlace":55,"./paeth-predictor":59,buffer:16}],54:[function(require,module,exports){(function(Buffer){"use strict";function dePalette(indata,outdata,width,height,palette){var pxPos=0;for(var y=0;y<height;y++){for(var x=0;x<width;x++){var color=palette[indata[pxPos]];if(!color){throw new Error("index "+indata[pxPos]+" not in palette")}for(var i=0;i<4;i++){outdata[pxPos+i]=color[i]}pxPos+=4}}}function replaceTransparentColor(indata,outdata,width,height,transColor){var pxPos=0;for(var y=0;y<height;y++){for(var x=0;x<width;x++){var makeTrans=false;if(transColor.length===1){if(transColor[0]===indata[pxPos]){makeTrans=true}}else if(transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2]){makeTrans=true}if(makeTrans){for(var i=0;i<4;i++){outdata[pxPos+i]=0}}pxPos+=4}}}function scaleDepth(indata,outdata,width,height,depth){var maxOutSample=255;var maxInSample=Math.pow(2,depth)-1;var pxPos=0;for(var y=0;y<height;y++){for(var x=0;x<width;x++){for(var i=0;i<4;i++){outdata[pxPos+i]=Math.floor(indata[pxPos+i]*maxOutSample/maxInSample+.5)}pxPos+=4}}}module.exports=function(indata,imageData){var depth=imageData.depth;var width=imageData.width;var height=imageData.height;var colorType=imageData.colorType;var transColor=imageData.transColor;var palette=imageData.palette;var outdata=indata;if(colorType===3){dePalette(indata,outdata,width,height,palette)}else{if(transColor){replaceTransparentColor(indata,outdata,width,height,transColor)}if(depth!==8){if(depth===16){outdata=new Buffer(width*height*4)}scaleDepth(indata,outdata,width,height,depth)}}return outdata}}).call(this,require("buffer").Buffer)},{buffer:16}],55:[function(require,module,exports){"use strict";var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(width,height){var images=[];var xLeftOver=width%8;var yLeftOver=height%8;var xRepeats=(width-xLeftOver)/8;var yRepeats=(height-yLeftOver)/8;for(var i=0;i<imagePasses.length;i++){var pass=imagePasses[i];var passWidth=xRepeats*pass.x.length;var passHeight=yRepeats*pass.y.length;for(var j=0;j<pass.x.length;j++){if(pass.x[j]<xLeftOver){passWidth++}else{break}}for(j=0;j<pass.y.length;j++){if(pass.y[j]<yLeftOver){passHeight++}else{break}}if(passWidth>0&&passHeight>0){images.push({width:passWidth,height:passHeight,index:i})}}return images};exports.getInterlaceIterator=function(width){return function(x,y,pass){var outerXLeftOver=x%imagePasses[pass].x.length;var outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver];var outerYLeftOver=y%imagePasses[pass].y.length;var outerY=(y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver];return outerX*4+outerY*width*4}}},{}],56:[function(require,module,exports){(function(Buffer){"use strict";var util=require("util");var Stream=require("stream");var constants=require("./constants");var Packer=require("./packer");var PackerAsync=module.exports=function(opt){Stream.call(this);var options=opt||{};this._packer=new Packer(options);this._deflate=this._packer.createDeflate();this.readable=true};util.inherits(PackerAsync,Stream);PackerAsync.prototype.pack=function(data,width,height,gamma){this.emit("data",new Buffer(constants.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(width,height));if(gamma){this.emit("data",this._packer.packGAMA(gamma))}var filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(filteredData)}}).call(this,require("buffer").Buffer)},{"./constants":48,"./packer":58,buffer:16,stream:40,util:44}],57:[function(require,module,exports){(function(Buffer){"use strict";var hasSyncZlib=true;var zlib=require("zlib");var constants=require("./constants");var Packer=require("./packer");module.exports=function(metaData,opt){if(!hasSyncZlib){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}var options=opt||{};var packer=new Packer(options);var chunks=[];chunks.push(new Buffer(constants.PNG_SIGNATURE));chunks.push(packer.packIHDR(metaData.width,metaData.height));if(metaData.gamma){chunks.push(packer.packGAMA(metaData.gamma))}var filteredData=packer.filterData(metaData.data,metaData.width,metaData.height);var compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());filteredData=null;if(!compressedData||!compressedData.length){throw new Error("bad png - invalid compressed data response")}chunks.push(packer.packIDAT(compressedData));chunks.push(packer.packIEND());return Buffer.concat(chunks)}}).call(this,require("buffer").Buffer)},{"./constants":48,"./packer":58,buffer:16,zlib:15}],58:[function(require,module,exports){(function(Buffer){"use strict";var constants=require("./constants");var CrcStream=require("./crc");var bitPacker=require("./bitpacker");var filter=require("./filter-pack");var zlib=require("zlib");var Packer=module.exports=function(options){this._options=options;options.deflateChunkSize=options.deflateChunkSize||32*1024;options.deflateLevel=options.deflateLevel!=null?options.deflateLevel:9;options.deflateStrategy=options.deflateStrategy!=null?options.deflateStrategy:3;options.inputHasAlpha=options.inputHasAlpha!=null?options.inputHasAlpha:true;options.deflateFactory=options.deflateFactory||zlib.createDeflate;options.bitDepth=options.bitDepth||8;options.colorType=typeof options.colorType==="number"?options.colorType:constants.COLORTYPE_COLOR_ALPHA;if(options.colorType!==constants.COLORTYPE_COLOR&&options.colorType!==constants.COLORTYPE_COLOR_ALPHA){throw new Error("option color type:"+options.colorType+" is not supported at present")}if(options.bitDepth!==8){throw new Error("option bit depth:"+options.bitDepth+" is not supported at present")}};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Packer.prototype.filterData=function(data,width,height){var packedData=bitPacker(data,width,height,this._options);var bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];var filteredData=filter(packedData,width,height,this._options,bpp);return filteredData};Packer.prototype._packChunk=function(type,data){var len=data?data.length:0;var buf=new Buffer(len+12);buf.writeUInt32BE(len,0);buf.writeUInt32BE(type,4);if(data){data.copy(buf,8)}buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4);return buf};Packer.prototype.packGAMA=function(gamma){var buf=new Buffer(4);buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0);return this._packChunk(constants.TYPE_gAMA,buf)};Packer.prototype.packIHDR=function(width,height){var buf=new Buffer(13);buf.writeUInt32BE(width,0);buf.writeUInt32BE(height,4);buf[8]=this._options.bitDepth;buf[9]=this._options.colorType;buf[10]=0;buf[11]=0;buf[12]=0;return this._packChunk(constants.TYPE_IHDR,buf)};Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)};Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)}}).call(this,require("buffer").Buffer)},{"./bitpacker":46,"./constants":48,"./crc":49,"./filter-pack":50,buffer:16,zlib:15}],59:[function(require,module,exports){"use strict";module.exports=function paethPredictor(left,above,upLeft){var paeth=left+above-upLeft;var pLeft=Math.abs(paeth-left);var pAbove=Math.abs(paeth-above);var pUpLeft=Math.abs(paeth-upLeft);if(pLeft<=pAbove&&pLeft<=pUpLeft){return left}if(pAbove<=pUpLeft){return above}return upLeft}},{}],60:[function(require,module,exports){"use strict";var util=require("util");var zlib=require("zlib");var ChunkStream=require("./chunkstream");var FilterAsync=require("./filter-parse-async");var Parser=require("./parser");var bitmapper=require("./bitmapper");var formatNormaliser=require("./format-normaliser");var ParserAsync=module.exports=function(options){ChunkStream.call(this);this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this)});this._options=options;this.writable=true;this._parser.start()};util.inherits(ParserAsync,ChunkStream);ParserAsync.prototype._handleError=function(err){this.emit("error",err);this.writable=false;this.destroy();if(this._inflate&&this._inflate.destroy){this._inflate.destroy()}this.errord=true};ParserAsync.prototype._inflateData=function(data){if(!this._inflate){this._inflate=zlib.createInflate();this._inflate.on("error",this.emit.bind(this,"error"));this._filter.on("complete",this._complete.bind(this));this._inflate.pipe(this._filter)}this._inflate.write(data)};ParserAsync.prototype._handleMetaData=function(metaData){this.emit("metadata",metaData);this._bitmapInfo=Object.create(metaData);this._filter=new FilterAsync(this._bitmapInfo)};ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor};ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette};ParserAsync.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}this.destroySoon()};ParserAsync.prototype._complete=function(filteredData){if(this.errord){return}try{var bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);var normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo);bitmapData=null}catch(ex){this._handleError(ex);return}this.emit("parsed",normalisedBitmapData)}},{"./bitmapper":45,"./chunkstream":47,"./filter-parse-async":51,"./format-normaliser":54,"./parser":62,util:44,zlib:15}],61:[function(require,module,exports){(function(Buffer){"use strict";var hasSyncZlib=true;var zlib=require("zlib");var SyncReader=require("./sync-reader");var FilterSync=require("./filter-parse-sync");var Parser=require("./parser");var bitmapper=require("./bitmapper");var formatNormaliser=require("./format-normaliser");module.exports=function(buffer,options){if(!hasSyncZlib){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}var err;function handleError(_err_){err=_err_}var metaData;function handleMetaData(_metaData_){metaData=_metaData_}function handleTransColor(transColor){metaData.transColor=transColor}function handlePalette(palette){metaData.palette=palette}var gamma;function handleGamma(_gamma_){gamma=_gamma_}var inflateDataList=[];function handleInflateData(inflatedData){inflateDataList.push(inflatedData)}var reader=new SyncReader(buffer);var parser=new Parser(options,{read:reader.read.bind(reader),error:handleError,metadata:handleMetaData,gamma:handleGamma,palette:handlePalette,transColor:handleTransColor,inflateData:handleInflateData});parser.start();reader.process();if(err){throw err}var inflateData=Buffer.concat(inflateDataList);inflateDataList.length=0;var inflatedData=zlib.inflateSync(inflateData);inflateData=null;if(!inflatedData||!inflatedData.length){throw new Error("bad png - invalid inflate data response")}var unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;var bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;var normalisedBitmapData=formatNormaliser(bitmapData,metaData);metaData.data=normalisedBitmapData;metaData.gamma=gamma||0;return metaData}}).call(this,require("buffer").Buffer)},{"./bitmapper":45,"./filter-parse-sync":52,"./format-normaliser":54,"./parser":62,"./sync-reader":64,buffer:16,zlib:15}],62:[function(require,module,exports){(function(Buffer){"use strict";var constants=require("./constants");var CrcCalculator=require("./crc");var Parser=module.exports=function(options,dependencies){this._options=options;options.checkCRC=options.checkCRC!==false;this._hasIHDR=false;this._hasIEND=false;this._palette=[];this._colorType=0;this._chunks={};this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this);this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this);this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this);this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this);this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this);this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this);this.read=dependencies.read;this.error=dependencies.error;this.metadata=dependencies.metadata;this.gamma=dependencies.gamma;this.transColor=dependencies.transColor;this.palette=dependencies.palette;this.parsed=dependencies.parsed;this.inflateData=dependencies.inflateData;this.inflateData=dependencies.inflateData;this.finished=dependencies.finished};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Parser.prototype._parseSignature=function(data){var signature=constants.PNG_SIGNATURE;for(var i=0;i<signature.length;i++){if(data[i]!==signature[i]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._parseChunkBegin=function(data){var length=data.readUInt32BE(0);var type=data.readUInt32BE(4);var name="";for(var i=4;i<8;i++){name+=String.fromCharCode(data[i])}var ancillary=Boolean(data[4]&32);if(!this._hasIHDR&&type!==constants.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new CrcCalculator;this._crc.write(new Buffer(name));if(this._chunks[type]){return this._chunks[type](length)}if(!ancillary){this.error(new Error("Unsupported critical chunk type "+name));return}this.read(length+4,this._skipChunk.bind(this))};Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Parser.prototype._parseChunkEnd=function(data){var fileCrc=data.readInt32BE(0);var calcCrc=this._crc.crc32();if(this._options.checkCRC&&calcCrc!==fileCrc){this.error(new Error("Crc error - "+fileCrc+" - "+calcCrc));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))};Parser.prototype._parseIHDR=function(data){this._crc.write(data);var width=data.readUInt32BE(0);var height=data.readUInt32BE(4);var depth=data[8];var colorType=data[9];var compr=data[10];var filter=data[11];var interlace=data[12];if(depth!==8&&depth!==4&&depth!==2&&depth!==1&&depth!==16){this.error(new Error("Unsupported bit depth "+depth));return}if(!(colorType in constants.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(compr!==0){this.error(new Error("Unsupported compression method"));return}if(filter!==0){this.error(new Error("Unsupported filter method"));return}if(interlace!==0&&interlace!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=colorType;var bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:width,height:height,depth:depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp:bpp,colorType:colorType});this._handleChunkEnd()};Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))};Parser.prototype._parsePLTE=function(data){this._crc.write(data);var entries=Math.floor(data.length/3);for(var i=0;i<entries;i++){this._palette.push([data[i*3],data[i*3+1],data[i*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};Parser.prototype._handleTRNS=function(length){this.read(length,this._parseTRNS.bind(this))};Parser.prototype._parseTRNS=function(data){this._crc.write(data);if(this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(data.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(var i=0;i<data.length;i++){this._palette[i][3]=data[i]}this.palette(this._palette)}if(this._colorType===constants.COLORTYPE_GRAYSCALE){this.transColor([data.readUInt16BE(0)])}if(this._colorType===constants.COLORTYPE_COLOR){this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)])}this._handleChunkEnd()};Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))};Parser.prototype._parseGAMA=function(data){this._crc.write(data);this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION);this._handleChunkEnd()};Parser.prototype._handleIDAT=function(length){this.read(-length,this._parseIDAT.bind(this,length))};Parser.prototype._parseIDAT=function(length,data){this._crc.write(data);if(this._colorType===constants.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(data);var leftOverLength=length-data.length;if(leftOverLength>0){this._handleIDAT(leftOverLength)}else{this._handleChunkEnd()}};Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))};Parser.prototype._parseIEND=function(data){this._crc.write(data);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}).call(this,require("buffer").Buffer)},{"./constants":48,"./crc":49,buffer:16}],63:[function(require,module,exports){"use strict";var parse=require("./parser-sync");var pack=require("./packer-sync");exports.read=function(buffer,options){return parse(buffer,options||{})};exports.write=function(png){return pack(png)}},{"./packer-sync":57,"./parser-sync":61}],64:[function(require,module,exports){"use strict";var SyncReader=module.exports=function(buffer){this._buffer=buffer;this._reads=[]};SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})};SyncReader.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){var read=this._reads[0];if(this._buffer.length&&(this._buffer.length>=read.length||read.allowLess)){this._reads.shift();var buf=this._buffer;this._buffer=buf.slice(read.length);read.func.call(this,buf.slice(0,read.length))}else{break}}if(this._reads.length>0){return new Error("There are some read requests waitng on finished stream")}if(this._buffer.length>0){return new Error("unrecognised content at end of stream")}}},{}],pngjs:[function(require,module,exports){(function(process,Buffer){"use strict";var util=require("util");var Stream=require("stream");var Parser=require("./parser-async");var Packer=require("./packer-async");var PNGSync=require("./png-sync");var PNG=exports.PNG=function(options){Stream.call(this);options=options||{};this.width=options.width|0;this.height=options.height|0;this.data=this.width>0&&this.height>0?new Buffer(4*this.width*this.height):null;if(options.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new Parser(options);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(data){this.data=data;this.emit("parsed",data)}.bind(this));this._packer=new Packer(options);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream);PNG.sync=PNGSync;PNG.prototype.pack=function(){if(!this.data||!this.data.length){this.emit("error","No data provided");return this}process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this));return this};PNG.prototype.parse=function(data,callback){if(callback){var onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError);this.data=parsedData;callback(null,this)}.bind(this);onError=function(err){this.removeListener("parsed",onParsed);callback(err,null)}.bind(this);this.once("parsed",onParsed);this.once("error",onError)}this.end(data);return this};PNG.prototype.write=function(data){this._parser.write(data);return true};PNG.prototype.end=function(data){this._parser.end(data)};PNG.prototype._metadata=function(metadata){this.width=metadata.width;this.height=metadata.height;this.emit("metadata",metadata)};PNG.prototype._gamma=function(gamma){this.gamma=gamma};PNG.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){srcX|=0;srcY|=0;width|=0;height|=0;deltaX|=0;deltaY|=0;if(srcX>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height){throw new Error("bitblt reading outside image")}if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height){throw new Error("bitblt writing outside image")}for(var y=0;y<height;y++){src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)}};PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY);return this};PNG.adjustGamma=function(src){if(src.gamma){for(var y=0;y<src.height;y++){for(var x=0;x<src.width;x++){var idx=src.width*y+x<<2;for(var i=0;i<3;i++){var sample=src.data[idx+i]/255;sample=Math.pow(sample,1/2.2/src.gamma);src.data[idx+i]=Math.round(sample*255)}}}src.gamma=0}};PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)}}).call(this,require("_process"),require("buffer").Buffer)},{"./packer-async":56,"./parser-async":60,"./png-sync":63,_process:23,buffer:16,stream:40,util:44}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({pixelmatch:[function(require,module,exports){"use strict";module.exports=pixelmatch;function pixelmatch(img1,img2,output,width,height,options){if(!options)options={};var threshold=options.threshold===undefined?.1:options.threshold;var maxDelta=35215*threshold*threshold,diff=0;for(var y=0;y<height;y++){for(var x=0;x<width;x++){var pos=(y*width+x)*4;var delta=colorDelta(img1,img2,pos,pos);if(delta>maxDelta){if(!options.includeAA&&(antialiased(img1,x,y,width,height,img2)||antialiased(img2,x,y,width,height,img1))){if(output)drawPixel(output,pos,255,255,0)}else{if(output)drawPixel(output,pos,255,0,0);diff++}}else if(output){var val=blend(grayPixel(img1,pos),.1);drawPixel(output,pos,val,val,val)}}}return diff}function antialiased(img,x1,y1,width,height,img2){var x0=Math.max(x1-1,0),y0=Math.max(y1-1,0),x2=Math.min(x1+1,width-1),y2=Math.min(y1+1,height-1),pos=(y1*width+x1)*4,zeroes=0,positives=0,negatives=0,min=0,max=0,minX,minY,maxX,maxY;for(var x=x0;x<=x2;x++){for(var y=y0;y<=y2;y++){if(x===x1&&y===y1)continue;var delta=colorDelta(img,img,pos,(y*width+x)*4,true);if(delta===0)zeroes++;else if(delta<0)negatives++;else if(delta>0)positives++;if(zeroes>2)return false;if(!img2)continue;if(delta<min){min=delta;minX=x;minY=y}if(delta>max){max=delta;maxX=x;maxY=y}}}if(!img2)return true;if(negatives===0||positives===0)return false;return!antialiased(img,minX,minY,width,height)&&!antialiased(img2,minX,minY,width,height)||!antialiased(img,maxX,maxY,width,height)&&!antialiased(img2,maxX,maxY,width,height)}function colorDelta(img1,img2,k,m,yOnly){var a1=img1[k+3]/255,a2=img2[m+3]/255,r1=blend(img1[k+0],a1),g1=blend(img1[k+1],a1),b1=blend(img1[k+2],a1),r2=blend(img2[m+0],a2),g2=blend(img2[m+1],a2),b2=blend(img2[m+2],a2),y=rgb2y(r1,g1,b1)-rgb2y(r2,g2,b2);if(yOnly)return y;var i=rgb2i(r1,g1,b1)-rgb2i(r2,g2,b2),q=rgb2q(r1,g1,b1)-rgb2q(r2,g2,b2);return.5053*y*y+.299*i*i+.1957*q*q}function rgb2y(r,g,b){return r*.29889531+g*.58662247+b*.11448223}function rgb2i(r,g,b){return r*.59597799-g*.2741761-b*.32180189}function rgb2q(r,g,b){return r*.21147017-g*.52261711+b*.31114694}function blend(c,a){return 255+(c-255)*a}function drawPixel(output,pos,r,g,b){output[pos+0]=r;output[pos+1]=g;output[pos+2]=b;output[pos+3]=255}function grayPixel(img,i){var a=img[i+3]/255,r=blend(img[i+0],a),g=blend(img[i+1],a),b=blend(img[i+2],a);return rgb2y(r,g,b)}},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()<length){throw new RangeError("Invalid typed array length")}if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(length);that.__proto__=Buffer.prototype}else{if(that===null){that=new Buffer(length)}that.length=length}return that}function Buffer(arg,encodingOrOffset,length){if(!Buffer.TYPED_ARRAY_SUPPORT&&!(this instanceof Buffer)){return new Buffer(arg,encodingOrOffset,length)}if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(this,arg)}return from(this,arg,encodingOrOffset,length)}Buffer.poolSize=8192;Buffer._augment=function(arr){arr.__proto__=Buffer.prototype;return arr};function from(that,value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){return fromArrayBuffer(that,value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(that,value,encodingOrOffset)}return fromObject(that,value)}Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)};if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true})}}function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(that,size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(that,size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill)}return createBuffer(that,size)}Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)};function allocUnsafe(that,size){assertSize(size);that=createBuffer(that,size<0?0:checked(size)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<size;++i){that[i]=0}}return that}Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)};function fromString(that,string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;that=createBuffer(that,length);var actual=that.write(string,encoding);
if(actual!==length){that=that.slice(0,actual)}return that}function fromArrayLike(that,array){var length=array.length<0?0:checked(array.length)|0;that=createBuffer(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromArrayBuffer(that,array,byteOffset,length){array.byteLength;if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError("'offset' is out of bounds")}if(array.byteLength<byteOffset+(length||0)){throw new RangeError("'length' is out of bounds")}if(byteOffset===undefined&&length===undefined){array=new Uint8Array(array)}else if(length===undefined){array=new Uint8Array(array,byteOffset)}else{array=new Uint8Array(array,byteOffset,length)}if(Buffer.TYPED_ARRAY_SUPPORT){that=array;that.__proto__=Buffer.prototype}else{that=fromArrayLike(that,array)}return that}function fromObject(that,obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;that=createBuffer(that,len);if(that.length===0){return that}obj.copy(that,0,0,len);return that}if(obj){if(typeof ArrayBuffer!=="undefined"&&obj.buffer instanceof ArrayBuffer||"length"in obj){if(typeof obj.length!=="number"||isnan(obj.length)){return createBuffer(that,0)}return fromArrayLike(that,obj)}if(obj.type==="Buffer"&&isArray(obj.data)){return fromArrayLike(that,obj.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(typeof ArrayBuffer!=="undefined"&&typeof ArrayBuffer.isView==="function"&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){string=""+string}var len=string.length;if(len===0)return 0;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;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}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}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};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};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}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}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}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":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>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}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]&127)}return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;++i){newBuf[i]=this[i+start]}}return newBuf};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*=256)){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*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(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*=256)){val+=this[offset+i]*mul}mul*=128;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*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}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&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;++i){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;++i){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}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&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}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)};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;if(end===start)return 0;if(target.length===0||this.length===0)return 0;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");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){for(i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){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};Buffer.prototype.fill=function fill(val,start,end,encoding){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}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString());var len=bytes.length;for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:4,isarray:5}],3:[function(require,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")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i<l;i+=4,j+=3){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&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}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&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}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;var output="";var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],4:[function(require,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&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],6:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;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(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{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){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;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={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];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.error("(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"){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};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;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}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){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}},{}],7:[function(require,module,exports){var http=require("http");var https=module.exports;for(var key in http){if(http.hasOwnProperty(key))https[key]=http[key]}https.request=function(params,cb){if(!params)params={};params.scheme="https";params.protocol="https:";return http.request.call(this,params,cb)}},{http:27}],8:[function(require,module,exports){if(typeof Object.create==="function"){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{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],9:[function(require,module,exports){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)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],10:[function(require,module,exports){var process=module.exports={};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){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){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)}};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="";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}},{}],11:[function(require,module,exports){(function(global){(function(root){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}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}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}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;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);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&&currentValue<m){m=currentValue}}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){for(q=delta,k=base;;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("")}function toUnicode(input){return mapDomain(input,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(input){return mapDomain(input,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define("punycode",function(){return punycode})}else if(freeExports&&freeModule){if(module.exports==freeExports){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],12:[function(require,module,exports){"use strict";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=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;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]"}},{}],13:[function(require,module,exports){"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}},{}],14:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":12,"./encode":13}],15:[function(require,module,exports){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args");var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_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)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;processNextTick(onEndNT,this)}function onEndNT(self){self.end()}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}},{"./_stream_readable":17,"./_stream_writable":19,"core-util-is":22,inherits:8,"process-nextick-args":24}],16:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("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":18,"core-util-is":22,inherits:8}],17:[function(require,module,exports){(function(process){"use strict";module.exports=Readable;var processNextTick=require("process-nextick-args");var isArray=require("isarray");var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");var util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util");var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=require("./internal/streams/BufferList");var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{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||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;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;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{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)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc;return this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}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(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(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}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(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false;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(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}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;emitReadable(stream)}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)}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)break;else len=state.length}state.readingMore=false}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:cleanup;if(state.endEmitted)processNextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){debug("onunpipe");if(readable===src){cleanup()}}function onend(){debug("onend");dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=false;function cleanup(){debug("cleanup");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",cleanup);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}var increasedAwaitDrain=false;src.on("data",ondata);function ondata(chunk){debug("ondata");increasedAwaitDrain=false;var ret=dest.write(chunk);if(false===ret&&!increasedAwaitDrain){if((state.pipesCount===1&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);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)}dest.emit("pipe",src);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;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){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)}return this}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);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"){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,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}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){}}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);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()}});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)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;var ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){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{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(n<list.head.data.length){ret=list.head.data.slice(0,n);
list.head.data=list.head.data.slice(n)}else if(n===list.head.data.length){ret=list.shift()}else{ret=hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list)}return ret}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}function copyFromBuffer(n,list){var ret=bufferShim.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(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){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,require("_process"))},{"./_stream_duplex":15,"./internal/streams/BufferList":20,_process:10,buffer:2,"buffer-shims":21,"core-util-is":22,events:6,inherits:8,isarray:23,"process-nextick-args":24,"string_decoder/":33,util:1}],18:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("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("no writecb in Transform class"));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;this._readableState.needReadable=true;this._readableState.sync=false;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}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)};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)}};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{ts.needTransform=true}};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!==null&&data!==undefined)stream.push(data);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":15,"core-util-is":22,inherits:8}],19:[function(require,module,exports){(function(process){"use strict";module.exports=Writable;var processNextTick=require("process-nextick-args");var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var 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.")})}catch(_){}})();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||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}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(!Buffer.isBuffer(chunk)&&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;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,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){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=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb);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)processNextTick(cb,er);else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}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{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)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount;var buffer=new Array(l);var holder=state.corkedRequestsFree;holder.entry=entry;var count=0;while(entry){buffer[count]=entry;entry=entry.next;count+=1}doWrite(stream,state,true,state.length,buffer,"",holder.finish);state.pendingcb++;state.lastBufferedRequest=null;if(holder.next){state.corkedRequestsFree=holder.next;holder.next=null}else{state.corkedRequestsFree=new CorkedRequest(state)}}else{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(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);if(state.corked){state.corked=1;this.uncork()}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 prefinish(stream,state){if(!state.prefinished){state.prefinished=true;stream.emit("prefinish")}}function finishMaybe(stream,state){var need=needFinish(state);if(need){if(state.pendingcb===0){prefinish(stream,state);state.finished=true;stream.emit("finish")}else{prefinish(stream,state)}}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 CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(err){var entry=_this.entry;_this.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=_this}else{state.corkedRequestsFree=_this}}}}).call(this,require("_process"))},{"./_stream_duplex":15,_process:10,buffer:2,"buffer-shims":21,"core-util-is":22,events:6,inherits:8,"process-nextick-args":24,"util-deprecate":25}],20:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");module.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(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(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){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(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(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(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":21}],21:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++i<size){buf[i]=fillBuf[i%flen]}}else{buf.fill(_fill)}return buf};exports.allocUnsafe=function allocUnsafe(size){if(typeof Buffer.allocUnsafe==="function"){return Buffer.allocUnsafe(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],22:[function(require,module,exports){(function(Buffer){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"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":9}],23:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],24:[function(require,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,require("_process"))},{_process:10}],25:[function(require,module,exports){(function(global){module.exports=deprecate;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}function config(name){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:{})},{}],26:[function(require,module,exports){(function(process){var Stream=function(){try{return require("st"+"ream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=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");if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module.exports=Stream}}).call(this,require("_process"))},{"./lib/_stream_duplex.js":15,"./lib/_stream_passthrough.js":16,"./lib/_stream_readable.js":17,"./lib/_stream_transform.js":18,"./lib/_stream_writable.js":19,_process:10}],27:[function(require,module,exports){(function(global){var ClientRequest=require("./lib/request");var extend=require("xtend");var statusCodes=require("builtin-status-codes");var url=require("url");var http=exports;http.request=function(opts,cb){if(typeof opts==="string")opts=url.parse(opts);else opts=extend(opts);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||"/";if(host&&host.indexOf(":")!==-1)host="["+host+"]";opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path;opts.method=(opts.method||"GET").toUpperCase();opts.headers=opts.headers||{};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":29,"builtin-status-codes":31,url:34,xtend:36}],28:[function(require,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){}var xhr;function getXHR(){if(xhr!==undefined)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else{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}var haveArrayBuffer=typeof global.ArrayBuffer!=="undefined";var haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);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):false);exports.vbArray=isFunction(global.VBArray);function isFunction(value){return typeof value==="function"}xhr=null}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],29:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability");var inherits=require("inherits");var response=require("./response");var stream=require("readable-stream");var toArrayBuffer=require("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){useFetch=false;preferBinary=true}else if(opts.mode==="prefer-streaming"){preferBinary=false}else if(opts.mode==="allow-wrong-content-type"){preferBinary=!capability.overrideMimeType}else if(!opts.mode||opts.mode==="default"||opts.mode==="prefer-fast"){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();if(unsafeHeaders.indexOf(lowerName)!==-1)return;self._headers[lowerName]={name:name,value:value}};ClientRequest.prototype.getHeader=function(name){var self=this;return self._headers[name.toLowerCase()].value};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==="POST"||opts.method==="PUT"||opts.method==="PATCH"||opts.method==="MERGE"){if(capability.blobConstructor){body=new global.Blob(self._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""})}else{body=Buffer.concat(self._body).toString()}}if(self._mode==="fetch"){var headers=Object.keys(headersObj).map(function(name){return[headersObj[name].name,headersObj[name].value]});global.fetch(self._opts.url,{method:self._opts.method,headers:headers,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}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")}}Object.keys(headersObj).forEach(function(name){xhr.setRequestHeader(headersObj[name].name,headersObj[name].value)});self._response=null;xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();break}};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}}};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()};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(){};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,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":28,"./response":30,_process:10,buffer:2,inherits:8,"readable-stream":26,"to-arraybuffer":32}],30:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability");var inherits=require("inherits");var stream=require("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=[];self.on("end",function(){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)});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"}}};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":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(response!==null){self.push(new Buffer(response));break}case"text":try{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)&255;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":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.readAsArrayBuffer(response);break}if(self._xhr.readyState===rStates.DONE&&self._mode!=="ms-stream"){self.push(null)}}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":28,_process:10,buffer:2,inherits:8,"readable-stream":26}],31:[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"}},{}],32:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(buf.byteOffset===0&&buf.byteLength===buf.buffer.byteLength){return buf.buffer}else if(typeof buf.buffer.slice==="function"){return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}}if(Buffer.isBuffer(buf)){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:2}],33:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(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 assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],34:[function(require,module,exports){"use strict";var punycode=require("punycode");var util=require("./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}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n"," "],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:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("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)}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;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){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)}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])){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}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}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(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";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){newpart+="x"}else{newpart+=part[j]}}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{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){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)}}var hash=rest.indexOf("#");if(hash!==-1){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){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){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+=":";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]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}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(!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;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(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){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}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();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;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){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";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(!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)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";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("/")}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":35,punycode:11,querystring:14}],35:[function(require,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}}},{}],36:[function(require,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}},{}],fabric:[function(require,module,exports){(function(process,Buffer){var fabric=fabric||{version:"1.7.11"};if(typeof exports!=="undefined"){exports.fabric=fabric}if(typeof document!=="undefined"&&typeof window!=="undefined"){fabric.document=document;fabric.window=window;window.fabric=fabric}else{fabric.document=require("jsdom").jsdom(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"));if(fabric.document.createWindow){fabric.window=fabric.document.createWindow()}else{fabric.window=fabric.document.parentWindow}}fabric.isTouchSupported="ontouchstart"in fabric.document.documentElement;fabric.isLikelyNode=typeof Buffer!=="undefined"&&typeof window==="undefined";fabric.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id"];fabric.DPI=96;fabric.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)";fabric.fontPaths={};fabric.iMatrix=[1,0,0,1,0,0];fabric.charWidthsCache={};fabric.devicePixelRatio=fabric.window.devicePixelRatio||fabric.window.webkitDevicePixelRatio||fabric.window.mozDevicePixelRatio||1;(function(){function _removeEventListener(eventName,handler){if(!this.__eventListeners[eventName]){return}var eventListener=this.__eventListeners[eventName];if(handler){eventListener[eventListener.indexOf(handler)]=false}else{fabric.util.array.fill(eventListener,false)}}function observe(eventName,handler){if(!this.__eventListeners){this.__eventListeners={}}if(arguments.length===1){for(var prop in eventName){this.on(prop,eventName[prop])}}else{if(!this.__eventListeners[eventName]){this.__eventListeners[eventName]=[]}this.__eventListeners[eventName].push(handler)}return this}function stopObserving(eventName,handler){if(!this.__eventListeners){return}if(arguments.length===0){for(eventName in this.__eventListeners){_removeEventListener.call(this,eventName)}}else if(arguments.length===1&&typeof arguments[0]==="object"){for(var prop in eventName){_removeEventListener.call(this,prop,eventName[prop])}}else{_removeEventListener.call(this,eventName,handler)}return this}function fire(eventName,options){if(!this.__eventListeners){return}var listenersForEvent=this.__eventListeners[eventName];if(!listenersForEvent){return}for(var i=0,len=listenersForEvent.length;i<len;i++){listenersForEvent[i]&&listenersForEvent[i].call(this,options||{})}this.__eventListeners[eventName]=listenersForEvent.filter(function(value){return value!==false});return this}fabric.Observable={observe:observe,stopObserving:stopObserving,fire:fire,on:observe,off:stopObserving,trigger:fire}})();fabric.Collection={_objects:[],add:function(){this._objects.push.apply(this._objects,arguments);if(this._onObjectAdded){for(var i=0,length=arguments.length;i<length;i++){this._onObjectAdded(arguments[i])}}this.renderOnAddRemove&&this.renderAll();return this},insertAt:function(object,index,nonSplicing){var objects=this.getObjects();if(nonSplicing){objects[index]=object}else{objects.splice(index,0,object)}this._onObjectAdded&&this._onObjectAdded(object);this.renderOnAddRemove&&this.renderAll();return this},remove:function(){var objects=this.getObjects(),index,somethingRemoved=false;for(var i=0,length=arguments.length;i<length;i++){index=objects.indexOf(arguments[i]);if(index!==-1){somethingRemoved=true;objects.splice(index,1);this._onObjectRemoved&&this._onObjectRemoved(arguments[i])}}this.renderOnAddRemove&&somethingRemoved&&this.renderAll();return this},forEachObject:function(callback,context){var objects=this.getObjects();for(var i=0,len=objects.length;i<len;i++){callback.call(context,objects[i],i,objects)}return this},getObjects:function(type){if(typeof type==="undefined"){return this._objects}return this._objects.filter(function(o){return o.type===type})},item:function(index){return this.getObjects()[index]},isEmpty:function(){return this.getObjects().length===0},size:function(){return this.getObjects().length},contains:function(object){return this.getObjects().indexOf(object)>-1},complexity:function(){return this.getObjects().reduce(function(memo,current){memo+=current.complexity?current.complexity():0;return memo},0)}};fabric.CommonMethods={_setOptions:function(options){for(var prop in options){this.set(prop,options[prop])}},_initGradient:function(filler,property){if(filler&&filler.colorStops&&!(filler instanceof fabric.Gradient)){this.set(property,new fabric.Gradient(filler))}},_initPattern:function(filler,property,callback){if(filler&&filler.source&&!(filler instanceof fabric.Pattern)){this.set(property,new fabric.Pattern(filler,callback))}else{callback&&callback()}},_initClipping:function(options){if(!options.clipTo||typeof options.clipTo!=="string"){return}var functionBody=fabric.util.getFunctionBody(options.clipTo);if(typeof functionBody!=="undefined"){this.clipTo=new Function("ctx",functionBody)}},_setObject:function(obj){for(var prop in obj){this._set(prop,obj[prop])}},set:function(key,value){if(typeof key==="object"){this._setObject(key)}else{if(typeof value==="function"&&key!=="clipTo"){this._set(key,value(this.get(key)))}else{this._set(key,value)}}return this},_set:function(key,value){this[key]=value},toggle:function(property){var value=this.get(property);if(typeof value==="boolean"){this.set(property,!value)}return this},get:function(property){return this[property]}};(function(global){var sqrt=Math.sqrt,atan2=Math.atan2,pow=Math.pow,abs=Math.abs,PiBy180=Math.PI/180;fabric.util={removeFromArray:function(array,value){var idx=array.indexOf(value);if(idx!==-1){array.splice(idx,1)}return array},getRandomInt:function(min,max){return Math.floor(Math.random()*(max-min+1))+min},degreesToRadians:function(degrees){return degrees*PiBy180},radiansToDegrees:function(radians){return radians/PiBy180},rotatePoint:function(point,origin,radians){point.subtractEquals(origin);var v=fabric.util.rotateVector(point,radians);return new fabric.Point(v.x,v.y).addEquals(origin)},rotateVector:function(vector,radians){var sin=Math.sin(radians),cos=Math.cos(radians),rx=vector.x*cos-vector.y*sin,ry=vector.x*sin+vector.y*cos;return{x:rx,y:ry}},transformPoint:function(p,t,ignoreOffset){if(ignoreOffset){return new fabric.Point(t[0]*p.x+t[2]*p.y,t[1]*p.x+t[3]*p.y)}return new fabric.Point(t[0]*p.x+t[2]*p.y+t[4],t[1]*p.x+t[3]*p.y+t[5])},makeBoundingBoxFromPoints:function(points){var xPoints=[points[0].x,points[1].x,points[2].x,points[3].x],minX=fabric.util.array.min(xPoints),maxX=fabric.util.array.max(xPoints),width=Math.abs(minX-maxX),yPoints=[points[0].y,points[1].y,points[2].y,points[3].y],minY=fabric.util.array.min(yPoints),maxY=fabric.util.array.max(yPoints),height=Math.abs(minY-maxY);return{left:minX,top:minY,width:width,height:height}},invertTransform:function(t){var a=1/(t[0]*t[3]-t[1]*t[2]),r=[a*t[3],-a*t[1],-a*t[2],a*t[0]],o=fabric.util.transformPoint({x:t[4],y:t[5]},r,true);r[4]=-o.x;r[5]=-o.y;return r},toFixed:function(number,fractionDigits){return parseFloat(Number(number).toFixed(fractionDigits))},parseUnit:function(value,fontSize){var unit=/\D{0,2}$/.exec(value),number=parseFloat(value);if(!fontSize){fontSize=fabric.Text.DEFAULT_SVG_FONT_SIZE}switch(unit[0]){case"mm":return number*fabric.DPI/25.4;case"cm":return number*fabric.DPI/2.54;case"in":return number*fabric.DPI;case"pt":return number*fabric.DPI/72;case"pc":return number*fabric.DPI/72*12;case"em":return number*fontSize;default:return number}},falseFunction:function(){return false},getKlass:function(type,namespace){type=fabric.util.string.camelize(type.charAt(0).toUpperCase()+type.slice(1));return fabric.util.resolveNamespace(namespace)[type]},resolveNamespace:function(namespace){if(!namespace){return fabric}var parts=namespace.split("."),len=parts.length,i,obj=global||fabric.window;for(i=0;i<len;++i){obj=obj[parts[i]]}return obj},loadImage:function(url,callback,context,crossOrigin){if(!url){callback&&callback.call(context,url);return}var img=fabric.util.createImage();img.onload=function(){callback&&callback.call(context,img);img=img.onload=img.onerror=null};img.onerror=function(){fabric.log("Error loading "+img.src);callback&&callback.call(context,null,true);img=img.onload=img.onerror=null};if(url.indexOf("data")!==0&&crossOrigin){img.crossOrigin=crossOrigin}img.src=url},enlivenObjects:function(objects,callback,namespace,reviver){objects=objects||[];function onLoaded(){if(++numLoadedObjects===numTotalObjects){callback&&callback(enlivenedObjects)}}var enlivenedObjects=[],numLoadedObjects=0,numTotalObjects=objects.length,forceAsync=true;if(!numTotalObjects){callback&&callback(enlivenedObjects);return}objects.forEach(function(o,index){if(!o||!o.type){onLoaded();return}var klass=fabric.util.getKlass(o.type,namespace);klass.fromObject(o,function(obj,error){error||(enlivenedObjects[index]=obj);reviver&&reviver(o,obj,error);onLoaded()},forceAsync)})},enlivenPatterns:function(patterns,callback){patterns=patterns||[];function onLoaded(){if(++numLoadedPatterns===numPatterns){callback&&callback(enlivenedPatterns)}}var enlivenedPatterns=[],numLoadedPatterns=0,numPatterns=patterns.length;if(!numPatterns){callback&&callback(enlivenedPatterns);return}patterns.forEach(function(p,index){if(p&&p.source){new fabric.Pattern(p,function(pattern){enlivenedPatterns[index]=pattern;onLoaded()})}else{enlivenedPatterns[index]=p;onLoaded()}})},groupSVGElements:function(elements,options,path){var object;object=new fabric.PathGroup(elements,options);if(typeof path!=="undefined"){object.sourcePath=path}return object},populateWithProperties:function(source,destination,properties){if(properties&&Object.prototype.toString.call(properties)==="[object Array]"){for(var i=0,len=properties.length;i<len;i++){if(properties[i]in source){destination[properties[i]]=source[properties[i]]}}}},drawDashedLine:function(ctx,x,y,x2,y2,da){var dx=x2-x,dy=y2-y,len=sqrt(dx*dx+dy*dy),rot=atan2(dy,dx),dc=da.length,di=0,draw=true;ctx.save();ctx.translate(x,y);ctx.moveTo(0,0);ctx.rotate(rot);x=0;while(len>x){x+=da[di++%dc];if(x>len){x=len}ctx[draw?"lineTo":"moveTo"](x,0);draw=!draw}ctx.restore()},createCanvasElement:function(canvasEl){canvasEl||(canvasEl=fabric.document.createElement("canvas"));if(!canvasEl.getContext&&typeof G_vmlCanvasManager!=="undefined"){G_vmlCanvasManager.initElement(canvasEl)}return canvasEl},createImage:function(){return fabric.isLikelyNode?new(require("canvas").Image):fabric.document.createElement("img")},createAccessors:function(klass){var proto=klass.prototype,i,propName,capitalizedPropName,setterName,getterName;for(i=proto.stateProperties.length;i--;){propName=proto.stateProperties[i];capitalizedPropName=propName.charAt(0).toUpperCase()+propName.slice(1);setterName="set"+capitalizedPropName;getterName="get"+capitalizedPropName;if(!proto[getterName]){proto[getterName]=function(property){return new Function('return this.get("'+property+'")')}(propName)}if(!proto[setterName]){proto[setterName]=function(property){return new Function("value",'return this.set("'+property+'", value)')}(propName)}}},clipContext:function(receiver,ctx){ctx.save();ctx.beginPath();receiver.clipTo(ctx);ctx.clip()},multiplyTransformMatrices:function(a,b,is2x2){return[a[0]*b[0]+a[2]*b[1],a[1]*b[0]+a[3]*b[1],a[0]*b[2]+a[2]*b[3],a[1]*b[2]+a[3]*b[3],is2x2?0:a[0]*b[4]+a[2]*b[5]+a[4],is2x2?0:a[1]*b[4]+a[3]*b[5]+a[5]]},qrDecompose:function(a){var angle=atan2(a[1],a[0]),denom=pow(a[0],2)+pow(a[1],2),scaleX=sqrt(denom),scaleY=(a[0]*a[3]-a[2]*a[1])/scaleX,skewX=atan2(a[0]*a[2]+a[1]*a[3],denom);return{angle:angle/PiBy180,scaleX:scaleX,scaleY:scaleY,skewX:skewX/PiBy180,skewY:0,translateX:a[4],translateY:a[5]}},customTransformMatrix:function(scaleX,scaleY,skewX){var skewMatrixX=[1,0,abs(Math.tan(skewX*PiBy180)),1],scaleMatrix=[abs(scaleX),0,0,abs(scaleY)];return fabric.util.multiplyTransformMatrices(scaleMatrix,skewMatrixX,true)},resetObjectTransform:function(target){target.scaleX=1;target.scaleY=1;target.skewX=0;target.skewY=0;target.flipX=false;target.flipY=false;target.setAngle(0)},getFunctionBody:function(fn){return(String(fn).match(/function[^{]*\{([\s\S]*)\}/)||{})[1]},isTransparent:function(ctx,x,y,tolerance){if(tolerance>0){if(x>tolerance){x-=tolerance}else{x=0}if(y>tolerance){y-=tolerance}else{y=0}}var _isTransparent=true,i,temp,imageData=ctx.getImageData(x,y,tolerance*2||1,tolerance*2||1),l=imageData.data.length;for(i=3;i<l;i+=4){temp=imageData.data[i];_isTransparent=temp<=0;if(_isTransparent===false){break}}imageData=null;return _isTransparent},parsePreserveAspectRatioAttribute:function(attribute){var meetOrSlice="meet",alignX="Mid",alignY="Mid",aspectRatioAttrs=attribute.split(" "),align;if(aspectRatioAttrs&&aspectRatioAttrs.length){meetOrSlice=aspectRatioAttrs.pop();if(meetOrSlice!=="meet"&&meetOrSlice!=="slice"){align=meetOrSlice;meetOrSlice="meet"}else if(aspectRatioAttrs.length){align=aspectRatioAttrs.pop()}}alignX=align!=="none"?align.slice(1,4):"none";
alignY=align!=="none"?align.slice(5,8):"none";return{meetOrSlice:meetOrSlice,alignX:alignX,alignY:alignY}},clearFabricFontCache:function(fontFamily){if(!fontFamily){fabric.charWidthsCache={}}else if(fabric.charWidthsCache[fontFamily]){delete fabric.charWidthsCache[fontFamily]}}}})(typeof exports!=="undefined"?exports:this);(function(){var arcToSegmentsCache={},segmentToBezierCache={},boundsOfCurveCache={},_join=Array.prototype.join;function arcToSegments(toX,toY,rx,ry,large,sweep,rotateX){var argsString=_join.call(arguments);if(arcToSegmentsCache[argsString]){return arcToSegmentsCache[argsString]}var PI=Math.PI,th=rotateX*PI/180,sinTh=Math.sin(th),cosTh=Math.cos(th),fromX=0,fromY=0;rx=Math.abs(rx);ry=Math.abs(ry);var px=-cosTh*toX*.5-sinTh*toY*.5,py=-cosTh*toY*.5+sinTh*toX*.5,rx2=rx*rx,ry2=ry*ry,py2=py*py,px2=px*px,pl=rx2*ry2-rx2*py2-ry2*px2,root=0;if(pl<0){var s=Math.sqrt(1-pl/(rx2*ry2));rx*=s;ry*=s}else{root=(large===sweep?-1:1)*Math.sqrt(pl/(rx2*py2+ry2*px2))}var cx=root*rx*py/ry,cy=-root*ry*px/rx,cx1=cosTh*cx-sinTh*cy+toX*.5,cy1=sinTh*cx+cosTh*cy+toY*.5,mTheta=calcVectorAngle(1,0,(px-cx)/rx,(py-cy)/ry),dtheta=calcVectorAngle((px-cx)/rx,(py-cy)/ry,(-px-cx)/rx,(-py-cy)/ry);if(sweep===0&&dtheta>0){dtheta-=2*PI}else if(sweep===1&&dtheta<0){dtheta+=2*PI}var segments=Math.ceil(Math.abs(dtheta/PI*2)),result=[],mDelta=dtheta/segments,mT=8/3*Math.sin(mDelta/4)*Math.sin(mDelta/4)/Math.sin(mDelta/2),th3=mTheta+mDelta;for(var i=0;i<segments;i++){result[i]=segmentToBezier(mTheta,th3,cosTh,sinTh,rx,ry,cx1,cy1,mT,fromX,fromY);fromX=result[i][4];fromY=result[i][5];mTheta=th3;th3+=mDelta}arcToSegmentsCache[argsString]=result;return result}function segmentToBezier(th2,th3,cosTh,sinTh,rx,ry,cx1,cy1,mT,fromX,fromY){var argsString2=_join.call(arguments);if(segmentToBezierCache[argsString2]){return segmentToBezierCache[argsString2]}var costh2=Math.cos(th2),sinth2=Math.sin(th2),costh3=Math.cos(th3),sinth3=Math.sin(th3),toX=cosTh*rx*costh3-sinTh*ry*sinth3+cx1,toY=sinTh*rx*costh3+cosTh*ry*sinth3+cy1,cp1X=fromX+mT*(-cosTh*rx*sinth2-sinTh*ry*costh2),cp1Y=fromY+mT*(-sinTh*rx*sinth2+cosTh*ry*costh2),cp2X=toX+mT*(cosTh*rx*sinth3+sinTh*ry*costh3),cp2Y=toY+mT*(sinTh*rx*sinth3-cosTh*ry*costh3);segmentToBezierCache[argsString2]=[cp1X,cp1Y,cp2X,cp2Y,toX,toY];return segmentToBezierCache[argsString2]}function calcVectorAngle(ux,uy,vx,vy){var ta=Math.atan2(uy,ux),tb=Math.atan2(vy,vx);if(tb>=ta){return tb-ta}else{return 2*Math.PI-(ta-tb)}}fabric.util.drawArc=function(ctx,fx,fy,coords){var rx=coords[0],ry=coords[1],rot=coords[2],large=coords[3],sweep=coords[4],tx=coords[5],ty=coords[6],segs=[[],[],[],[]],segsNorm=arcToSegments(tx-fx,ty-fy,rx,ry,large,sweep,rot);for(var i=0,len=segsNorm.length;i<len;i++){segs[i][0]=segsNorm[i][0]+fx;segs[i][1]=segsNorm[i][1]+fy;segs[i][2]=segsNorm[i][2]+fx;segs[i][3]=segsNorm[i][3]+fy;segs[i][4]=segsNorm[i][4]+fx;segs[i][5]=segsNorm[i][5]+fy;ctx.bezierCurveTo.apply(ctx,segs[i])}};fabric.util.getBoundsOfArc=function(fx,fy,rx,ry,rot,large,sweep,tx,ty){var fromX=0,fromY=0,bound,bounds=[],segs=arcToSegments(tx-fx,ty-fy,rx,ry,large,sweep,rot);for(var i=0,len=segs.length;i<len;i++){bound=getBoundsOfCurve(fromX,fromY,segs[i][0],segs[i][1],segs[i][2],segs[i][3],segs[i][4],segs[i][5]);bounds.push({x:bound[0].x+fx,y:bound[0].y+fy});bounds.push({x:bound[1].x+fx,y:bound[1].y+fy});fromX=segs[i][4];fromY=segs[i][5]}return bounds};function getBoundsOfCurve(x0,y0,x1,y1,x2,y2,x3,y3){var argsString=_join.call(arguments);if(boundsOfCurveCache[argsString]){return boundsOfCurveCache[argsString]}var sqrt=Math.sqrt,min=Math.min,max=Math.max,abs=Math.abs,tvalues=[],bounds=[[],[]],a,b,c,t,t1,t2,b2ac,sqrtb2ac;b=6*x0-12*x1+6*x2;a=-3*x0+9*x1-9*x2+3*x3;c=3*x1-3*x0;for(var i=0;i<2;++i){if(i>0){b=6*y0-12*y1+6*y2;a=-3*y0+9*y1-9*y2+3*y3;c=3*y1-3*y0}if(abs(a)<1e-12){if(abs(b)<1e-12){continue}t=-c/b;if(0<t&&t<1){tvalues.push(t)}continue}b2ac=b*b-4*c*a;if(b2ac<0){continue}sqrtb2ac=sqrt(b2ac);t1=(-b+sqrtb2ac)/(2*a);if(0<t1&&t1<1){tvalues.push(t1)}t2=(-b-sqrtb2ac)/(2*a);if(0<t2&&t2<1){tvalues.push(t2)}}var x,y,j=tvalues.length,jlen=j,mt;while(j--){t=tvalues[j];mt=1-t;x=mt*mt*mt*x0+3*mt*mt*t*x1+3*mt*t*t*x2+t*t*t*x3;bounds[0][j]=x;y=mt*mt*mt*y0+3*mt*mt*t*y1+3*mt*t*t*y2+t*t*t*y3;bounds[1][j]=y}bounds[0][jlen]=x0;bounds[1][jlen]=y0;bounds[0][jlen+1]=x3;bounds[1][jlen+1]=y3;var result=[{x:min.apply(null,bounds[0]),y:min.apply(null,bounds[1])},{x:max.apply(null,bounds[0]),y:max.apply(null,bounds[1])}];boundsOfCurveCache[argsString]=result;return result}fabric.util.getBoundsOfCurve=getBoundsOfCurve})();(function(){var slice=Array.prototype.slice;if(!Array.prototype.indexOf){Array.prototype.indexOf=function(searchElement){if(this===void 0||this===null){throw new TypeError}var t=Object(this),len=t.length>>>0;if(len===0){return-1}var n=0;if(arguments.length>0){n=Number(arguments[1]);if(n!==n){n=0}else if(n!==0&&n!==Number.POSITIVE_INFINITY&&n!==Number.NEGATIVE_INFINITY){n=(n>0||-1)*Math.floor(Math.abs(n))}}if(n>=len){return-1}var k=n>=0?n:Math.max(len-Math.abs(n),0);for(;k<len;k++){if(k in t&&t[k]===searchElement){return k}}return-1}}if(!Array.prototype.forEach){Array.prototype.forEach=function(fn,context){for(var i=0,len=this.length>>>0;i<len;i++){if(i in this){fn.call(context,this[i],i,this)}}}}if(!Array.prototype.map){Array.prototype.map=function(fn,context){var result=[];for(var i=0,len=this.length>>>0;i<len;i++){if(i in this){result[i]=fn.call(context,this[i],i,this)}}return result}}if(!Array.prototype.every){Array.prototype.every=function(fn,context){for(var i=0,len=this.length>>>0;i<len;i++){if(i in this&&!fn.call(context,this[i],i,this)){return false}}return true}}if(!Array.prototype.some){Array.prototype.some=function(fn,context){for(var i=0,len=this.length>>>0;i<len;i++){if(i in this&&fn.call(context,this[i],i,this)){return true}}return false}}if(!Array.prototype.filter){Array.prototype.filter=function(fn,context){var result=[],val;for(var i=0,len=this.length>>>0;i<len;i++){if(i in this){val=this[i];if(fn.call(context,val,i,this)){result.push(val)}}}return result}}if(!Array.prototype.reduce){Array.prototype.reduce=function(fn){var len=this.length>>>0,i=0,rv;if(arguments.length>1){rv=arguments[1]}else{do{if(i in this){rv=this[i++];break}if(++i>=len){throw new TypeError}}while(true)}for(;i<len;i++){if(i in this){rv=fn.call(null,rv,this[i],i,this)}}return rv}}function invoke(array,method){var args=slice.call(arguments,2),result=[];for(var i=0,len=array.length;i<len;i++){result[i]=args.length?array[i][method].apply(array[i],args):array[i][method].call(array[i])}return result}function max(array,byProperty){return find(array,byProperty,function(value1,value2){return value1>=value2})}function min(array,byProperty){return find(array,byProperty,function(value1,value2){return value1<value2})}function fill(array,value){var k=array.length;while(k--){array[k]=value}return array}function find(array,byProperty,condition){if(!array||array.length===0){return}var i=array.length-1,result=byProperty?array[i][byProperty]:array[i];if(byProperty){while(i--){if(condition(array[i][byProperty],result)){result=array[i][byProperty]}}}else{while(i--){if(condition(array[i],result)){result=array[i]}}}return result}fabric.util.array={fill:fill,invoke:invoke,min:min,max:max}})();(function(){function extend(destination,source,deep){if(deep){if(!fabric.isLikelyNode&&source instanceof Element){destination=source}else if(source instanceof Array){destination=[];for(var i=0,len=source.length;i<len;i++){destination[i]=extend({},source[i],deep)}}else if(source&&typeof source==="object"){for(var property in source){if(source.hasOwnProperty(property)){destination[property]=extend({},source[property],deep)}}}else{destination=source}}else{for(var property in source){destination[property]=source[property]}}return destination}function clone(object,deep){return extend({},object,deep)}fabric.util.object={extend:extend,clone:clone}})();(function(){if(!String.prototype.trim){String.prototype.trim=function(){return this.replace(/^[\s\xA0]+/,"").replace(/[\s\xA0]+$/,"")}}function camelize(string){return string.replace(/-+(.)?/g,function(match,character){return character?character.toUpperCase():""})}function capitalize(string,firstLetterOnly){return string.charAt(0).toUpperCase()+(firstLetterOnly?string.slice(1):string.slice(1).toLowerCase())}function escapeXml(string){return string.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}fabric.util.string={camelize:camelize,capitalize:capitalize,escapeXml:escapeXml}})();(function(){var slice=Array.prototype.slice,apply=Function.prototype.apply,Dummy=function(){};if(!Function.prototype.bind){Function.prototype.bind=function(thisArg){var _this=this,args=slice.call(arguments,1),bound;if(args.length){bound=function(){return apply.call(_this,this instanceof Dummy?this:thisArg,args.concat(slice.call(arguments)))}}else{bound=function(){return apply.call(_this,this instanceof Dummy?this:thisArg,arguments)}}Dummy.prototype=this.prototype;bound.prototype=new Dummy;return bound}}})();(function(){var slice=Array.prototype.slice,emptyFunction=function(){},IS_DONTENUM_BUGGY=function(){for(var p in{toString:1}){if(p==="toString"){return false}}return true}(),addMethods=function(klass,source,parent){for(var property in source){if(property in klass.prototype&&typeof klass.prototype[property]==="function"&&(source[property]+"").indexOf("callSuper")>-1){klass.prototype[property]=function(property){return function(){var superclass=this.constructor.superclass;this.constructor.superclass=parent;var returnValue=source[property].apply(this,arguments);this.constructor.superclass=superclass;if(property!=="initialize"){return returnValue}}}(property)}else{klass.prototype[property]=source[property]}if(IS_DONTENUM_BUGGY){if(source.toString!==Object.prototype.toString){klass.prototype.toString=source.toString}if(source.valueOf!==Object.prototype.valueOf){klass.prototype.valueOf=source.valueOf}}}};function Subclass(){}function callSuper(methodName){var parentMethod=null,_this=this;while(_this.constructor.superclass){var superClassMethod=_this.constructor.superclass.prototype[methodName];if(_this[methodName]!==superClassMethod){parentMethod=superClassMethod;break}_this=_this.constructor.superclass.prototype}if(!parentMethod){return console.log("tried to callSuper "+methodName+", method not found in prototype chain",this)}return arguments.length>1?parentMethod.apply(this,slice.call(arguments,1)):parentMethod.call(this)}function createClass(){var parent=null,properties=slice.call(arguments,0);if(typeof properties[0]==="function"){parent=properties.shift()}function klass(){this.initialize.apply(this,arguments)}klass.superclass=parent;klass.subclasses=[];if(parent){Subclass.prototype=parent.prototype;klass.prototype=new Subclass;parent.subclasses.push(klass)}for(var i=0,length=properties.length;i<length;i++){addMethods(klass,properties[i],parent)}if(!klass.prototype.initialize){klass.prototype.initialize=emptyFunction}klass.prototype.constructor=klass;klass.prototype.callSuper=callSuper;return klass}fabric.util.createClass=createClass})();(function(){var unknown="unknown";function areHostMethods(object){var methodNames=Array.prototype.slice.call(arguments,1),t,i,len=methodNames.length;for(i=0;i<len;i++){t=typeof object[methodNames[i]];if(!/^(?:function|object|unknown)$/.test(t)){return false}}return true}var getElement,setElement,getUniqueId=function(){var uid=0;return function(element){return element.__uniqueID||(element.__uniqueID="uniqueID__"+uid++)}}();(function(){var elements={};getElement=function(uid){return elements[uid]};setElement=function(uid,element){elements[uid]=element}})();function createListener(uid,handler){return{handler:handler,wrappedHandler:createWrappedHandler(uid,handler)}}function createWrappedHandler(uid,handler){return function(e){handler.call(getElement(uid),e||fabric.window.event)}}function createDispatcher(uid,eventName){return function(e){if(handlers[uid]&&handlers[uid][eventName]){var handlersForEvent=handlers[uid][eventName];for(var i=0,len=handlersForEvent.length;i<len;i++){handlersForEvent[i].call(this,e||fabric.window.event)}}}}var shouldUseAddListenerRemoveListener=areHostMethods(fabric.document.documentElement,"addEventListener","removeEventListener")&&areHostMethods(fabric.window,"addEventListener","removeEventListener"),shouldUseAttachEventDetachEvent=areHostMethods(fabric.document.documentElement,"attachEvent","detachEvent")&&areHostMethods(fabric.window,"attachEvent","detachEvent"),listeners={},handlers={},addListener,removeListener;if(shouldUseAddListenerRemoveListener){addListener=function(element,eventName,handler,options){element.addEventListener(eventName,handler,shouldUseAttachEventDetachEvent?false:options)};removeListener=function(element,eventName,handler,options){element.removeEventListener(eventName,handler,shouldUseAttachEventDetachEvent?false:options)}}else if(shouldUseAttachEventDetachEvent){addListener=function(element,eventName,handler){var uid=getUniqueId(element);setElement(uid,element);if(!listeners[uid]){listeners[uid]={}}if(!listeners[uid][eventName]){listeners[uid][eventName]=[]}var listener=createListener(uid,handler);listeners[uid][eventName].push(listener);element.attachEvent("on"+eventName,listener.wrappedHandler)};removeListener=function(element,eventName,handler){var uid=getUniqueId(element),listener;if(listeners[uid]&&listeners[uid][eventName]){for(var i=0,len=listeners[uid][eventName].length;i<len;i++){listener=listeners[uid][eventName][i];if(listener&&listener.handler===handler){element.detachEvent("on"+eventName,listener.wrappedHandler);listeners[uid][eventName][i]=null}}}}}else{addListener=function(element,eventName,handler){var uid=getUniqueId(element);if(!handlers[uid]){handlers[uid]={}}if(!handlers[uid][eventName]){handlers[uid][eventName]=[];var existingHandler=element["on"+eventName];if(existingHandler){handlers[uid][eventName].push(existingHandler)}element["on"+eventName]=createDispatcher(uid,eventName)}handlers[uid][eventName].push(handler)};removeListener=function(element,eventName,handler){var uid=getUniqueId(element);if(handlers[uid]&&handlers[uid][eventName]){var handlersForEvent=handlers[uid][eventName];for(var i=0,len=handlersForEvent.length;i<len;i++){if(handlersForEvent[i]===handler){handlersForEvent.splice(i,1)}}}}}fabric.util.addListener=addListener;fabric.util.removeListener=removeListener;function getPointer(event){event||(event=fabric.window.event);var element=event.target||(typeof event.srcElement!==unknown?event.srcElement:null),scroll=fabric.util.getScrollLeftTop(element);return{x:pointerX(event)+scroll.left,y:pointerY(event)+scroll.top}}var pointerX=function(event){return typeof event.clientX!==unknown?event.clientX:0},pointerY=function(event){return typeof event.clientY!==unknown?event.clientY:0};function _getPointer(event,pageProp,clientProp){var touchProp=event.type==="touchend"?"changedTouches":"touches";return event[touchProp]&&event[touchProp][0]?event[touchProp][0][pageProp]-(event[touchProp][0][pageProp]-event[touchProp][0][clientProp])||event[clientProp]:event[clientProp]}if(fabric.isTouchSupported){pointerX=function(event){return _getPointer(event,"pageX","clientX")};pointerY=function(event){return _getPointer(event,"pageY","clientY")}}fabric.util.getPointer=getPointer;fabric.util.object.extend(fabric.util,fabric.Observable)})();(function(){function setStyle(element,styles){var elementStyle=element.style;if(!elementStyle){return element}if(typeof styles==="string"){element.style.cssText+=";"+styles;return styles.indexOf("opacity")>-1?setOpacity(element,styles.match(/opacity:\s*(\d?\.?\d*)/)[1]):element}for(var property in styles){if(property==="opacity"){setOpacity(element,styles[property])}else{var normalizedProperty=property==="float"||property==="cssFloat"?typeof elementStyle.styleFloat==="undefined"?"cssFloat":"styleFloat":property;elementStyle[normalizedProperty]=styles[property]}}return element}var parseEl=fabric.document.createElement("div"),supportsOpacity=typeof parseEl.style.opacity==="string",supportsFilters=typeof parseEl.style.filter==="string",reOpacity=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,setOpacity=function(element){return element};if(supportsOpacity){setOpacity=function(element,value){element.style.opacity=value;return element}}else if(supportsFilters){setOpacity=function(element,value){var es=element.style;if(element.currentStyle&&!element.currentStyle.hasLayout){es.zoom=1}if(reOpacity.test(es.filter)){value=value>=.9999?"":"alpha(opacity="+value*100+")";es.filter=es.filter.replace(reOpacity,value)}else{es.filter+=" alpha(opacity="+value*100+")"}return element}}fabric.util.setStyle=setStyle})();(function(){var _slice=Array.prototype.slice;function getById(id){return typeof id==="string"?fabric.document.getElementById(id):id}var sliceCanConvertNodelists,toArray=function(arrayLike){return _slice.call(arrayLike,0)};try{sliceCanConvertNodelists=toArray(fabric.document.childNodes)instanceof Array}catch(err){}if(!sliceCanConvertNodelists){toArray=function(arrayLike){var arr=new Array(arrayLike.length),i=arrayLike.length;while(i--){arr[i]=arrayLike[i]}return arr}}function makeElement(tagName,attributes){var el=fabric.document.createElement(tagName);for(var prop in attributes){if(prop==="class"){el.className=attributes[prop]}else if(prop==="for"){el.htmlFor=attributes[prop]}else{el.setAttribute(prop,attributes[prop])}}return el}function addClass(element,className){if(element&&(" "+element.className+" ").indexOf(" "+className+" ")===-1){element.className+=(element.className?" ":"")+className}}function wrapElement(element,wrapper,attributes){if(typeof wrapper==="string"){wrapper=makeElement(wrapper,attributes)}if(element.parentNode){element.parentNode.replaceChild(wrapper,element)}wrapper.appendChild(element);return wrapper}function getScrollLeftTop(element){var left=0,top=0,docElement=fabric.document.documentElement,body=fabric.document.body||{scrollLeft:0,scrollTop:0};while(element&&(element.parentNode||element.host)){element=element.parentNode||element.host;if(element===fabric.document){left=body.scrollLeft||docElement.scrollLeft||0;top=body.scrollTop||docElement.scrollTop||0}else{left+=element.scrollLeft||0;top+=element.scrollTop||0}if(element.nodeType===1&&fabric.util.getElementStyle(element,"position")==="fixed"){break}}return{left:left,top:top}}function getElementOffset(element){var docElem,doc=element&&element.ownerDocument,box={left:0,top:0},offset={left:0,top:0},scrollLeftTop,offsetAttributes={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!doc){return offset}for(var attr in offsetAttributes){offset[offsetAttributes[attr]]+=parseInt(getElementStyle(element,attr),10)||0}docElem=doc.documentElement;if(typeof element.getBoundingClientRect!=="undefined"){box=element.getBoundingClientRect()}scrollLeftTop=getScrollLeftTop(element);return{left:box.left+scrollLeftTop.left-(docElem.clientLeft||0)+offset.left,top:box.top+scrollLeftTop.top-(docElem.clientTop||0)+offset.top}}var getElementStyle;if(fabric.document.defaultView&&fabric.document.defaultView.getComputedStyle){getElementStyle=function(element,attr){var style=fabric.document.defaultView.getComputedStyle(element,null);return style?style[attr]:undefined}}else{getElementStyle=function(element,attr){var value=element.style[attr];if(!value&&element.currentStyle){value=element.currentStyle[attr]}return value}}(function(){var style=fabric.document.documentElement.style,selectProp="userSelect"in style?"userSelect":"MozUserSelect"in style?"MozUserSelect":"WebkitUserSelect"in style?"WebkitUserSelect":"KhtmlUserSelect"in style?"KhtmlUserSelect":"";function makeElementUnselectable(element){if(typeof element.onselectstart!=="undefined"){element.onselectstart=fabric.util.falseFunction}if(selectProp){element.style[selectProp]="none"}else if(typeof element.unselectable==="string"){element.unselectable="on"}return element}function makeElementSelectable(element){if(typeof element.onselectstart!=="undefined"){element.onselectstart=null}if(selectProp){element.style[selectProp]=""}else if(typeof element.unselectable==="string"){element.unselectable=""}return element}fabric.util.makeElementUnselectable=makeElementUnselectable;fabric.util.makeElementSelectable=makeElementSelectable})();(function(){function getScript(url,callback){var headEl=fabric.document.getElementsByTagName("head")[0],scriptEl=fabric.document.createElement("script"),loading=true;scriptEl.onload=scriptEl.onreadystatechange=function(e){if(loading){if(typeof this.readyState==="string"&&this.readyState!=="loaded"&&this.readyState!=="complete"){return}loading=false;callback(e||fabric.window.event);scriptEl=scriptEl.onload=scriptEl.onreadystatechange=null}};scriptEl.src=url;headEl.appendChild(scriptEl)}fabric.util.getScript=getScript})();fabric.util.getById=getById;fabric.util.toArray=toArray;fabric.util.makeElement=makeElement;fabric.util.addClass=addClass;fabric.util.wrapElement=wrapElement;fabric.util.getScrollLeftTop=getScrollLeftTop;fabric.util.getElementOffset=getElementOffset;fabric.util.getElementStyle=getElementStyle})();(function(){function addParamToUrl(url,param){return url+(/\?/.test(url)?"&":"?")+param}var makeXHR=function(){var factories=[function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP.3.0")},function(){return new XMLHttpRequest}];for(var i=factories.length;i--;){try{var req=factories[i]();if(req){return factories[i]}}catch(err){}}}();function emptyFn(){}function request(url,options){options||(options={});var method=options.method?options.method.toUpperCase():"GET",onComplete=options.onComplete||function(){},xhr=makeXHR(),body=options.body||options.parameters;xhr.onreadystatechange=function(){if(xhr.readyState===4){onComplete(xhr);xhr.onreadystatechange=emptyFn}};if(method==="GET"){body=null;if(typeof options.parameters==="string"){url=addParamToUrl(url,options.parameters)}}xhr.open(method,url,true);if(method==="POST"||method==="PUT"){xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")}xhr.send(body);return xhr}fabric.util.request=request})();fabric.log=function(){};fabric.warn=function(){};if(typeof console!=="undefined"){["log","warn"].forEach(function(methodName){if(typeof console[methodName]!=="undefined"&&typeof console[methodName].apply==="function"){fabric[methodName]=function(){return console[methodName].apply(console,arguments)}}})}(function(){function animate(options){requestAnimFrame(function(timestamp){options||(options={});var start=timestamp||+new Date,duration=options.duration||500,finish=start+duration,time,onChange=options.onChange||function(){},abort=options.abort||function(){return false},easing=options.easing||function(t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b},startValue="startValue"in options?options.startValue:0,endValue="endValue"in options?options.endValue:100,byValue=options.byValue||endValue-startValue;options.onStart&&options.onStart();(function tick(ticktime){time=ticktime||+new Date;var currentTime=time>finish?duration:time-start;if(abort()){options.onComplete&&options.onComplete();return}onChange(easing(currentTime,startValue,byValue,duration));if(time>finish){options.onComplete&&options.onComplete();return}requestAnimFrame(tick)})(start)})}var _requestAnimFrame=fabric.window.requestAnimationFrame||fabric.window.webkitRequestAnimationFrame||fabric.window.mozRequestAnimationFrame||fabric.window.oRequestAnimationFrame||fabric.window.msRequestAnimationFrame||function(callback){fabric.window.setTimeout(callback,1e3/60)};function requestAnimFrame(){return _requestAnimFrame.apply(fabric.window,arguments)}fabric.util.animate=animate;fabric.util.requestAnimFrame=requestAnimFrame})();(function(){function calculateColor(begin,end,pos){var color="rgba("+parseInt(begin[0]+pos*(end[0]-begin[0]),10)+","+parseInt(begin[1]+pos*(end[1]-begin[1]),10)+","+parseInt(begin[2]+pos*(end[2]-begin[2]),10);color+=","+(begin&&end?parseFloat(begin[3]+pos*(end[3]-begin[3])):1);color+=")";return color}function animateColor(fromColor,toColor,duration,options){var startColor=new fabric.Color(fromColor).getSource(),endColor=new fabric.Color(toColor).getSource();options=options||{};fabric.util.animate(fabric.util.object.extend(options,{duration:duration||500,startValue:startColor,endValue:endColor,byValue:endColor,easing:function(currentTime,startValue,byValue,duration){var posValue=options.colorEasing?options.colorEasing(currentTime,duration):1-Math.cos(currentTime/duration*(Math.PI/2));return calculateColor(startValue,byValue,posValue)}}))}fabric.util.animateColor=animateColor})();(function(){function normalize(a,c,p,s){if(a<Math.abs(c)){a=c;s=p/4}else{if(c===0&&a===0){s=p/(2*Math.PI)*Math.asin(1)}else{s=p/(2*Math.PI)*Math.asin(c/a)}}return{a:a,c:c,p:p,s:s}}function elastic(opts,t,d){return opts.a*Math.pow(2,10*(t-=1))*Math.sin((t*d-opts.s)*(2*Math.PI)/opts.p)}function easeOutCubic(t,b,c,d){return c*((t=t/d-1)*t*t+1)+b}function easeInOutCubic(t,b,c,d){t/=d/2;if(t<1){return c/2*t*t*t+b}return c/2*((t-=2)*t*t+2)+b}function easeInQuart(t,b,c,d){return c*(t/=d)*t*t*t+b}function easeOutQuart(t,b,c,d){return-c*((t=t/d-1)*t*t*t-1)+b}function easeInOutQuart(t,b,c,d){t/=d/2;if(t<1){return c/2*t*t*t*t+b}return-c/2*((t-=2)*t*t*t-2)+b}function easeInQuint(t,b,c,d){return c*(t/=d)*t*t*t*t+b}function easeOutQuint(t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b}function easeInOutQuint(t,b,c,d){t/=d/2;if(t<1){return c/2*t*t*t*t*t+b}return c/2*((t-=2)*t*t*t*t+2)+b}function easeInSine(t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b}function easeOutSine(t,b,c,d){return c*Math.sin(t/d*(Math.PI/2))+b}function easeInOutSine(t,b,c,d){return-c/2*(Math.cos(Math.PI*t/d)-1)+b}function easeInExpo(t,b,c,d){return t===0?b:c*Math.pow(2,10*(t/d-1))+b}function easeOutExpo(t,b,c,d){return t===d?b+c:c*(-Math.pow(2,-10*t/d)+1)+b}function easeInOutExpo(t,b,c,d){if(t===0){return b}if(t===d){return b+c}t/=d/2;if(t<1){return c/2*Math.pow(2,10*(t-1))+b}return c/2*(-Math.pow(2,-10*--t)+2)+b}function easeInCirc(t,b,c,d){return-c*(Math.sqrt(1-(t/=d)*t)-1)+b}function easeOutCirc(t,b,c,d){return c*Math.sqrt(1-(t=t/d-1)*t)+b}function easeInOutCirc(t,b,c,d){t/=d/2;if(t<1){return-c/2*(Math.sqrt(1-t*t)-1)+b}return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b}function easeInElastic(t,b,c,d){var s=1.70158,p=0,a=c;if(t===0){return b}t/=d;if(t===1){return b+c}if(!p){p=d*.3}var opts=normalize(a,c,p,s);return-elastic(opts,t,d)+b}function easeOutElastic(t,b,c,d){var s=1.70158,p=0,a=c;if(t===0){return b}t/=d;if(t===1){return b+c}if(!p){p=d*.3}var opts=normalize(a,c,p,s);return opts.a*Math.pow(2,-10*t)*Math.sin((t*d-opts.s)*(2*Math.PI)/opts.p)+opts.c+b}function easeInOutElastic(t,b,c,d){var s=1.70158,p=0,a=c;if(t===0){return b}t/=d/2;if(t===2){return b+c}if(!p){p=d*(.3*1.5)}var opts=normalize(a,c,p,s);if(t<1){return-.5*elastic(opts,t,d)+b}return opts.a*Math.pow(2,-10*(t-=1))*Math.sin((t*d-opts.s)*(2*Math.PI)/opts.p)*.5+opts.c+b}function easeInBack(t,b,c,d,s){if(s===undefined){s=1.70158}return c*(t/=d)*t*((s+1)*t-s)+b}function easeOutBack(t,b,c,d,s){if(s===undefined){s=1.70158}return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b}function easeInOutBack(t,b,c,d,s){if(s===undefined){s=1.70158}t/=d/2;if(t<1){return c/2*(t*t*(((s*=1.525)+1)*t-s))+b}return c/2*((t-=2)*t*(((s*=1.525)+1)*t+s)+2)+b}function easeInBounce(t,b,c,d){return c-easeOutBounce(d-t,0,c,d)+b}function easeOutBounce(t,b,c,d){if((t/=d)<1/2.75){return c*(7.5625*t*t)+b}else if(t<2/2.75){return c*(7.5625*(t-=1.5/2.75)*t+.75)+b}else if(t<2.5/2.75){return c*(7.5625*(t-=2.25/2.75)*t+.9375)+b}else{return c*(7.5625*(t-=2.625/2.75)*t+.984375)+b}}function easeInOutBounce(t,b,c,d){if(t<d/2){return easeInBounce(t*2,0,c,d)*.5+b}return easeOutBounce(t*2-d,0,c,d)*.5+c*.5+b}fabric.util.ease={easeInQuad:function(t,b,c,d){return c*(t/=d)*t+b},easeOutQuad:function(t,b,c,d){return-c*(t/=d)*(t-2)+b},easeInOutQuad:function(t,b,c,d){t/=d/2;if(t<1){return c/2*t*t+b}return-c/2*(--t*(t-2)-1)+b},easeInCubic:function(t,b,c,d){return c*(t/=d)*t*t+b},easeOutCubic:easeOutCubic,easeInOutCubic:easeInOutCubic,easeInQuart:easeInQuart,easeOutQuart:easeOutQuart,easeInOutQuart:easeInOutQuart,easeInQuint:easeInQuint,easeOutQuint:easeOutQuint,easeInOutQuint:easeInOutQuint,easeInSine:easeInSine,easeOutSine:easeOutSine,easeInOutSine:easeInOutSine,easeInExpo:easeInExpo,easeOutExpo:easeOutExpo,easeInOutExpo:easeInOutExpo,easeInCirc:easeInCirc,easeOutCirc:easeOutCirc,easeInOutCirc:easeInOutCirc,easeInElastic:easeInElastic,easeOutElastic:easeOutElastic,easeInOutElastic:easeInOutElastic,easeInBack:easeInBack,easeOutBack:easeOutBack,easeInOutBack:easeInOutBack,easeInBounce:easeInBounce,easeOutBounce:easeOutBounce,easeInOutBounce:easeInOutBounce}})();(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,clone=fabric.util.object.clone,toFixed=fabric.util.toFixed,parseUnit=fabric.util.parseUnit,multiplyTransformMatrices=fabric.util.multiplyTransformMatrices,reAllowedSVGTagNames=/^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/i,reViewBoxTagNames=/^(symbol|image|marker|pattern|view|svg)$/i,reNotAllowedAncestors=/^(?:pattern|defs|symbol|metadata|clipPath|mask)$/i,reAllowedParents=/^(symbol|g|a|svg)$/i,attributesMap={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","stroke-dasharray":"strokeDashArray","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"originX",opacity:"opacity"},colorAttributes={stroke:"strokeOpacity",fill:"fillOpacity"};fabric.cssRules={};fabric.gradientDefs={};function normalizeAttr(attr){if(attr in attributesMap){return attributesMap[attr]}return attr}function normalizeValue(attr,value,parentAttributes,fontSize){var isArray=Object.prototype.toString.call(value)==="[object Array]",parsed;if((attr==="fill"||attr==="stroke")&&value==="none"){value=""}else if(attr==="strokeDashArray"){if(value==="none"){value=null}else{value=value.replace(/,/g," ").split(/\s+/).map(function(n){return parseFloat(n)})}}else if(attr==="transformMatrix"){if(parentAttributes&&parentAttributes.transformMatrix){value=multiplyTransformMatrices(parentAttributes.transformMatrix,fabric.parseTransformAttribute(value))}else{value=fabric.parseTransformAttribute(value)}}else if(attr==="visible"){value=value==="none"||value==="hidden"?false:true;if(parentAttributes&&parentAttributes.visible===false){value=false}}else if(attr==="opacity"){value=parseFloat(value);if(parentAttributes&&typeof parentAttributes.opacity!=="undefined"){value*=parentAttributes.opacity}}else if(attr==="originX"){value=value==="start"?"left":value==="end"?"right":"center"}else{parsed=isArray?value.map(parseUnit):parseUnit(value,fontSize)}return!isArray&&isNaN(parsed)?value:parsed}function _setStrokeFillOpacity(attributes){for(var attr in colorAttributes){if(typeof attributes[colorAttributes[attr]]==="undefined"||attributes[attr]===""){continue}if(typeof attributes[attr]==="undefined"){if(!fabric.Object.prototype[attr]){continue}attributes[attr]=fabric.Object.prototype[attr]}if(attributes[attr].indexOf("url(")===0){continue}var color=new fabric.Color(attributes[attr]);attributes[attr]=color.setAlpha(toFixed(color.getAlpha()*attributes[colorAttributes[attr]],2)).toRgba()}return attributes}function _getMultipleNodes(doc,nodeNames){var nodeName,nodeArray=[],nodeList;for(var i=0;i<nodeNames.length;i++){nodeName=nodeNames[i];nodeList=doc.getElementsByTagName(nodeName);nodeArray=nodeArray.concat(Array.prototype.slice.call(nodeList))}return nodeArray}fabric.parseTransformAttribute=function(){
function rotateMatrix(matrix,args){var cos=Math.cos(args[0]),sin=Math.sin(args[0]),x=0,y=0;if(args.length===3){x=args[1];y=args[2]}matrix[0]=cos;matrix[1]=sin;matrix[2]=-sin;matrix[3]=cos;matrix[4]=x-(cos*x-sin*y);matrix[5]=y-(sin*x+cos*y)}function scaleMatrix(matrix,args){var multiplierX=args[0],multiplierY=args.length===2?args[1]:args[0];matrix[0]=multiplierX;matrix[3]=multiplierY}function skewMatrix(matrix,args,pos){matrix[pos]=Math.tan(fabric.util.degreesToRadians(args[0]))}function translateMatrix(matrix,args){matrix[4]=args[0];if(args.length===2){matrix[5]=args[1]}}var iMatrix=[1,0,0,1,0,0],number=fabric.reNum,commaWsp="(?:\\s+,?\\s*|,\\s*)",skewX="(?:(skewX)\\s*\\(\\s*("+number+")\\s*\\))",skewY="(?:(skewY)\\s*\\(\\s*("+number+")\\s*\\))",rotate="(?:(rotate)\\s*\\(\\s*("+number+")(?:"+commaWsp+"("+number+")"+commaWsp+"("+number+"))?\\s*\\))",scale="(?:(scale)\\s*\\(\\s*("+number+")(?:"+commaWsp+"("+number+"))?\\s*\\))",translate="(?:(translate)\\s*\\(\\s*("+number+")(?:"+commaWsp+"("+number+"))?\\s*\\))",matrix="(?:(matrix)\\s*\\(\\s*"+"("+number+")"+commaWsp+"("+number+")"+commaWsp+"("+number+")"+commaWsp+"("+number+")"+commaWsp+"("+number+")"+commaWsp+"("+number+")"+"\\s*\\))",transform="(?:"+matrix+"|"+translate+"|"+scale+"|"+rotate+"|"+skewX+"|"+skewY+")",transforms="(?:"+transform+"(?:"+commaWsp+"*"+transform+")*"+")",transformList="^\\s*(?:"+transforms+"?)\\s*$",reTransformList=new RegExp(transformList),reTransform=new RegExp(transform,"g");return function(attributeValue){var matrix=iMatrix.concat(),matrices=[];if(!attributeValue||attributeValue&&!reTransformList.test(attributeValue)){return matrix}attributeValue.replace(reTransform,function(match){var m=new RegExp(transform).exec(match).filter(function(match){return!!match}),operation=m[1],args=m.slice(2).map(parseFloat);switch(operation){case"translate":translateMatrix(matrix,args);break;case"rotate":args[0]=fabric.util.degreesToRadians(args[0]);rotateMatrix(matrix,args);break;case"scale":scaleMatrix(matrix,args);break;case"skewX":skewMatrix(matrix,args,2);break;case"skewY":skewMatrix(matrix,args,1);break;case"matrix":matrix=args;break}matrices.push(matrix.concat());matrix=iMatrix.concat()});var combinedMatrix=matrices[0];while(matrices.length>1){matrices.shift();combinedMatrix=fabric.util.multiplyTransformMatrices(combinedMatrix,matrices[0])}return combinedMatrix}}();function parseStyleString(style,oStyle){var attr,value;style.replace(/;\s*$/,"").split(";").forEach(function(chunk){var pair=chunk.split(":");attr=pair[0].trim().toLowerCase();value=pair[1].trim();oStyle[attr]=value})}function parseStyleObject(style,oStyle){var attr,value;for(var prop in style){if(typeof style[prop]==="undefined"){continue}attr=prop.toLowerCase();value=style[prop];oStyle[attr]=value}}function getGlobalStylesForElement(element,svgUid){var styles={};for(var rule in fabric.cssRules[svgUid]){if(elementMatchesRule(element,rule.split(" "))){for(var property in fabric.cssRules[svgUid][rule]){styles[property]=fabric.cssRules[svgUid][rule][property]}}}return styles}function elementMatchesRule(element,selectors){var firstMatching,parentMatching=true;firstMatching=selectorMatches(element,selectors.pop());if(firstMatching&&selectors.length){parentMatching=doesSomeParentMatch(element,selectors)}return firstMatching&&parentMatching&&selectors.length===0}function doesSomeParentMatch(element,selectors){var selector,parentMatching=true;while(element.parentNode&&element.parentNode.nodeType===1&&selectors.length){if(parentMatching){selector=selectors.pop()}element=element.parentNode;parentMatching=selectorMatches(element,selector)}return selectors.length===0}function selectorMatches(element,selector){var nodeName=element.nodeName,classNames=element.getAttribute("class"),id=element.getAttribute("id"),matcher;matcher=new RegExp("^"+nodeName,"i");selector=selector.replace(matcher,"");if(id&&selector.length){matcher=new RegExp("#"+id+"(?![a-zA-Z\\-]+)","i");selector=selector.replace(matcher,"")}if(classNames&&selector.length){classNames=classNames.split(" ");for(var i=classNames.length;i--;){matcher=new RegExp("\\."+classNames[i]+"(?![a-zA-Z\\-]+)","i");selector=selector.replace(matcher,"")}}return selector.length===0}function elementById(doc,id){var el;doc.getElementById&&(el=doc.getElementById(id));if(el){return el}var node,i,nodelist=doc.getElementsByTagName("*");for(i=0;i<nodelist.length;i++){node=nodelist[i];if(id===node.getAttribute("id")){return node}}}function parseUseDirectives(doc){var nodelist=_getMultipleNodes(doc,["use","svg:use"]),i=0;while(nodelist.length&&i<nodelist.length){var el=nodelist[i],xlink=el.getAttribute("xlink:href").substr(1),x=el.getAttribute("x")||0,y=el.getAttribute("y")||0,el2=elementById(doc,xlink).cloneNode(true),currentTrans=(el2.getAttribute("transform")||"")+" translate("+x+", "+y+")",parentNode,oldLength=nodelist.length,attr,j,attrs,l;applyViewboxTransform(el2);if(/^svg$/i.test(el2.nodeName)){var el3=el2.ownerDocument.createElement("g");for(j=0,attrs=el2.attributes,l=attrs.length;j<l;j++){attr=attrs.item(j);el3.setAttribute(attr.nodeName,attr.nodeValue)}while(el2.firstChild){el3.appendChild(el2.firstChild)}el2=el3}for(j=0,attrs=el.attributes,l=attrs.length;j<l;j++){attr=attrs.item(j);if(attr.nodeName==="x"||attr.nodeName==="y"||attr.nodeName==="xlink:href"){continue}if(attr.nodeName==="transform"){currentTrans=attr.nodeValue+" "+currentTrans}else{el2.setAttribute(attr.nodeName,attr.nodeValue)}}el2.setAttribute("transform",currentTrans);el2.setAttribute("instantiated_by_use","1");el2.removeAttribute("id");parentNode=el.parentNode;parentNode.replaceChild(el2,el);if(nodelist.length===oldLength){i++}}}var reViewBoxAttrValue=new RegExp("^"+"\\s*("+fabric.reNum+"+)\\s*,?"+"\\s*("+fabric.reNum+"+)\\s*,?"+"\\s*("+fabric.reNum+"+)\\s*,?"+"\\s*("+fabric.reNum+"+)\\s*"+"$");function applyViewboxTransform(element){var viewBoxAttr=element.getAttribute("viewBox"),scaleX=1,scaleY=1,minX=0,minY=0,viewBoxWidth,viewBoxHeight,matrix,el,widthAttr=element.getAttribute("width"),heightAttr=element.getAttribute("height"),x=element.getAttribute("x")||0,y=element.getAttribute("y")||0,preserveAspectRatio=element.getAttribute("preserveAspectRatio")||"",missingViewBox=!viewBoxAttr||!reViewBoxTagNames.test(element.nodeName)||!(viewBoxAttr=viewBoxAttr.match(reViewBoxAttrValue)),missingDimAttr=!widthAttr||!heightAttr||widthAttr==="100%"||heightAttr==="100%",toBeParsed=missingViewBox&&missingDimAttr,parsedDim={},translateMatrix="";parsedDim.width=0;parsedDim.height=0;parsedDim.toBeParsed=toBeParsed;if(toBeParsed){return parsedDim}if(missingViewBox){parsedDim.width=parseUnit(widthAttr);parsedDim.height=parseUnit(heightAttr);return parsedDim}minX=-parseFloat(viewBoxAttr[1]);minY=-parseFloat(viewBoxAttr[2]);viewBoxWidth=parseFloat(viewBoxAttr[3]);viewBoxHeight=parseFloat(viewBoxAttr[4]);if(!missingDimAttr){parsedDim.width=parseUnit(widthAttr);parsedDim.height=parseUnit(heightAttr);scaleX=parsedDim.width/viewBoxWidth;scaleY=parsedDim.height/viewBoxHeight}else{parsedDim.width=viewBoxWidth;parsedDim.height=viewBoxHeight}preserveAspectRatio=fabric.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);if(preserveAspectRatio.alignX!=="none"){scaleY=scaleX=scaleX>scaleY?scaleY:scaleX}if(scaleX===1&&scaleY===1&&minX===0&&minY===0&&x===0&&y===0){return parsedDim}if(x||y){translateMatrix=" translate("+parseUnit(x)+" "+parseUnit(y)+") "}matrix=translateMatrix+" matrix("+scaleX+" 0"+" 0 "+scaleY+" "+minX*scaleX+" "+minY*scaleY+") ";if(element.nodeName==="svg"){el=element.ownerDocument.createElement("g");while(element.firstChild){el.appendChild(element.firstChild)}element.appendChild(el)}else{el=element;matrix=el.getAttribute("transform")+matrix}el.setAttribute("transform",matrix);return parsedDim}function hasAncestorWithNodeName(element,nodeName){while(element&&(element=element.parentNode)){if(element.nodeName&&nodeName.test(element.nodeName.replace("svg:",""))&&!element.getAttribute("instantiated_by_use")){return true}}return false}fabric.parseSVGDocument=function(doc,callback,reviver,parsingOptions){if(!doc){return}parseUseDirectives(doc);var svgUid=fabric.Object.__uid++,options=applyViewboxTransform(doc),descendants=fabric.util.toArray(doc.getElementsByTagName("*"));options.crossOrigin=parsingOptions&&parsingOptions.crossOrigin;options.svgUid=svgUid;if(descendants.length===0&&fabric.isLikelyNode){descendants=doc.selectNodes('//*[name(.)!="svg"]');var arr=[];for(var i=0,len=descendants.length;i<len;i++){arr[i]=descendants[i]}descendants=arr}var elements=descendants.filter(function(el){applyViewboxTransform(el);return reAllowedSVGTagNames.test(el.nodeName.replace("svg:",""))&&!hasAncestorWithNodeName(el,reNotAllowedAncestors)});if(!elements||elements&&!elements.length){callback&&callback([],{});return}fabric.gradientDefs[svgUid]=fabric.getGradientDefs(doc);fabric.cssRules[svgUid]=fabric.getCSSRules(doc);fabric.parseElements(elements,function(instances){if(callback){callback(instances,options)}},clone(options),reviver,parsingOptions)};var reFontDeclaration=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*"+"(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+fabric.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+fabric.reNum+"))?\\s+(.*)");extend(fabric,{parseFontDeclaration:function(value,oStyle){var match=value.match(reFontDeclaration);if(!match){return}var fontStyle=match[1],fontWeight=match[3],fontSize=match[4],lineHeight=match[5],fontFamily=match[6];if(fontStyle){oStyle.fontStyle=fontStyle}if(fontWeight){oStyle.fontWeight=isNaN(parseFloat(fontWeight))?fontWeight:parseFloat(fontWeight)}if(fontSize){oStyle.fontSize=parseUnit(fontSize)}if(fontFamily){oStyle.fontFamily=fontFamily}if(lineHeight){oStyle.lineHeight=lineHeight==="normal"?1:lineHeight}},getGradientDefs:function(doc){var tagArray=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"],elList=_getMultipleNodes(doc,tagArray),el,j=0,id,xlink,gradientDefs={},idsToXlinkMap={};j=elList.length;while(j--){el=elList[j];xlink=el.getAttribute("xlink:href");id=el.getAttribute("id");if(xlink){idsToXlinkMap[id]=xlink.substr(1)}gradientDefs[id]=el}for(id in idsToXlinkMap){var el2=gradientDefs[idsToXlinkMap[id]].cloneNode(true);el=gradientDefs[id];while(el2.firstChild){el.appendChild(el2.firstChild)}}return gradientDefs},parseAttributes:function(element,attributes,svgUid){if(!element){return}var value,parentAttributes={},fontSize;if(typeof svgUid==="undefined"){svgUid=element.getAttribute("svgUid")}if(element.parentNode&&reAllowedParents.test(element.parentNode.nodeName)){parentAttributes=fabric.parseAttributes(element.parentNode,attributes,svgUid)}fontSize=parentAttributes&&parentAttributes.fontSize||element.getAttribute("font-size")||fabric.Text.DEFAULT_SVG_FONT_SIZE;var ownAttributes=attributes.reduce(function(memo,attr){value=element.getAttribute(attr);if(value){memo[attr]=value}return memo},{});ownAttributes=extend(ownAttributes,extend(getGlobalStylesForElement(element,svgUid),fabric.parseStyleAttribute(element)));var normalizedAttr,normalizedValue,normalizedStyle={};for(var attr in ownAttributes){normalizedAttr=normalizeAttr(attr);normalizedValue=normalizeValue(normalizedAttr,ownAttributes[attr],parentAttributes,fontSize);normalizedStyle[normalizedAttr]=normalizedValue}if(normalizedStyle&&normalizedStyle.font){fabric.parseFontDeclaration(normalizedStyle.font,normalizedStyle)}var mergedAttrs=extend(parentAttributes,normalizedStyle);return reAllowedParents.test(element.nodeName)?mergedAttrs:_setStrokeFillOpacity(mergedAttrs)},parseElements:function(elements,callback,options,reviver,parsingOptions){new fabric.ElementsParser(elements,callback,options,reviver,parsingOptions).parse()},parseStyleAttribute:function(element){var oStyle={},style=element.getAttribute("style");if(!style){return oStyle}if(typeof style==="string"){parseStyleString(style,oStyle)}else{parseStyleObject(style,oStyle)}return oStyle},parsePointsAttribute:function(points){if(!points){return null}points=points.replace(/,/g," ").trim();points=points.split(/\s+/);var parsedPoints=[],i,len;i=0;len=points.length;for(;i<len;i+=2){parsedPoints.push({x:parseFloat(points[i]),y:parseFloat(points[i+1])})}return parsedPoints},getCSSRules:function(doc){var styles=doc.getElementsByTagName("style"),allRules={},rules;for(var i=0,len=styles.length;i<len;i++){var styleContents=styles[i].textContent||styles[i].text;styleContents=styleContents.replace(/\/\*[\s\S]*?\*\//g,"");if(styleContents.trim()===""){continue}rules=styleContents.match(/[^{]*\{[\s\S]*?\}/g);rules=rules.map(function(rule){return rule.trim()});rules.forEach(function(rule){var match=rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),ruleObj={},declaration=match[2].trim(),propertyValuePairs=declaration.replace(/;$/,"").split(/\s*;\s*/);for(var i=0,len=propertyValuePairs.length;i<len;i++){var pair=propertyValuePairs[i].split(/\s*:\s*/),property=pair[0],value=pair[1];ruleObj[property]=value}rule=match[1];rule.split(",").forEach(function(_rule){_rule=_rule.replace(/^svg/i,"").trim();if(_rule===""){return}if(allRules[_rule]){fabric.util.object.extend(allRules[_rule],ruleObj)}else{allRules[_rule]=fabric.util.object.clone(ruleObj)}})})}return allRules},loadSVGFromURL:function(url,callback,reviver,options){url=url.replace(/^\n\s*/,"").trim();new fabric.util.request(url,{method:"get",onComplete:onComplete});function onComplete(r){var xml=r.responseXML;if(xml&&!xml.documentElement&&fabric.window.ActiveXObject&&r.responseText){xml=new ActiveXObject("Microsoft.XMLDOM");xml.async="false";xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,""))}if(!xml||!xml.documentElement){callback&&callback(null)}fabric.parseSVGDocument(xml.documentElement,function(results,_options){callback&&callback(results,_options)},reviver,options)}},loadSVGFromString:function(string,callback,reviver,options){string=string.trim();var doc;if(typeof DOMParser!=="undefined"){var parser=new DOMParser;if(parser&&parser.parseFromString){doc=parser.parseFromString(string,"text/xml")}}else if(fabric.window.ActiveXObject){doc=new ActiveXObject("Microsoft.XMLDOM");doc.async="false";doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,""))}fabric.parseSVGDocument(doc.documentElement,function(results,_options){callback(results,_options)},reviver,options)}})})(typeof exports!=="undefined"?exports:this);fabric.ElementsParser=function(elements,callback,options,reviver,parsingOptions){this.elements=elements;this.callback=callback;this.options=options;this.reviver=reviver;this.svgUid=options&&options.svgUid||0;this.parsingOptions=parsingOptions};fabric.ElementsParser.prototype.parse=function(){this.instances=new Array(this.elements.length);this.numElements=this.elements.length;this.createObjects()};fabric.ElementsParser.prototype.createObjects=function(){for(var i=0,len=this.elements.length;i<len;i++){this.elements[i].setAttribute("svgUid",this.svgUid);(function(_obj,i){setTimeout(function(){_obj.createObject(_obj.elements[i],i)},0)})(this,i)}};fabric.ElementsParser.prototype.createObject=function(el,index){var klass=fabric[fabric.util.string.capitalize(el.tagName.replace("svg:",""))];if(klass&&klass.fromElement){try{this._createObject(klass,el,index)}catch(err){fabric.log(err)}}else{this.checkIfDone()}};fabric.ElementsParser.prototype._createObject=function(klass,el,index){if(klass.async){klass.fromElement(el,this.createCallback(index,el),this.options)}else{var obj=klass.fromElement(el,this.options);this.resolveGradient(obj,"fill");this.resolveGradient(obj,"stroke");this.reviver&&this.reviver(el,obj);this.instances[index]=obj;this.checkIfDone()}};fabric.ElementsParser.prototype.createCallback=function(index,el){var _this=this;return function(obj){_this.resolveGradient(obj,"fill");_this.resolveGradient(obj,"stroke");_this.reviver&&_this.reviver(el,obj);_this.instances[index]=obj;_this.checkIfDone()}};fabric.ElementsParser.prototype.resolveGradient=function(obj,property){var instanceFillValue=obj.get(property);if(!/^url\(/.test(instanceFillValue)){return}var gradientId=instanceFillValue.slice(5,instanceFillValue.length-1);if(fabric.gradientDefs[this.svgUid][gradientId]){obj.set(property,fabric.Gradient.fromElement(fabric.gradientDefs[this.svgUid][gradientId],obj))}};fabric.ElementsParser.prototype.checkIfDone=function(){if(--this.numElements===0){this.instances=this.instances.filter(function(el){return el!=null});this.callback(this.instances)}};(function(global){"use strict";var fabric=global.fabric||(global.fabric={});if(fabric.Point){fabric.warn("fabric.Point is already defined");return}fabric.Point=Point;function Point(x,y){this.x=x;this.y=y}Point.prototype={type:"point",constructor:Point,add:function(that){return new Point(this.x+that.x,this.y+that.y)},addEquals:function(that){this.x+=that.x;this.y+=that.y;return this},scalarAdd:function(scalar){return new Point(this.x+scalar,this.y+scalar)},scalarAddEquals:function(scalar){this.x+=scalar;this.y+=scalar;return this},subtract:function(that){return new Point(this.x-that.x,this.y-that.y)},subtractEquals:function(that){this.x-=that.x;this.y-=that.y;return this},scalarSubtract:function(scalar){return new Point(this.x-scalar,this.y-scalar)},scalarSubtractEquals:function(scalar){this.x-=scalar;this.y-=scalar;return this},multiply:function(scalar){return new Point(this.x*scalar,this.y*scalar)},multiplyEquals:function(scalar){this.x*=scalar;this.y*=scalar;return this},divide:function(scalar){return new Point(this.x/scalar,this.y/scalar)},divideEquals:function(scalar){this.x/=scalar;this.y/=scalar;return this},eq:function(that){return this.x===that.x&&this.y===that.y},lt:function(that){return this.x<that.x&&this.y<that.y},lte:function(that){return this.x<=that.x&&this.y<=that.y},gt:function(that){return this.x>that.x&&this.y>that.y},gte:function(that){return this.x>=that.x&&this.y>=that.y},lerp:function(that,t){if(typeof t==="undefined"){t=.5}t=Math.max(Math.min(1,t),0);return new Point(this.x+(that.x-this.x)*t,this.y+(that.y-this.y)*t)},distanceFrom:function(that){var dx=this.x-that.x,dy=this.y-that.y;return Math.sqrt(dx*dx+dy*dy)},midPointFrom:function(that){return this.lerp(that)},min:function(that){return new Point(Math.min(this.x,that.x),Math.min(this.y,that.y))},max:function(that){return new Point(Math.max(this.x,that.x),Math.max(this.y,that.y))},toString:function(){return this.x+","+this.y},setXY:function(x,y){this.x=x;this.y=y;return this},setX:function(x){this.x=x;return this},setY:function(y){this.y=y;return this},setFromPoint:function(that){this.x=that.x;this.y=that.y;return this},swap:function(that){var x=this.x,y=this.y;this.x=that.x;this.y=that.y;that.x=x;that.y=y},clone:function(){return new Point(this.x,this.y)}}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={});if(fabric.Intersection){fabric.warn("fabric.Intersection is already defined");return}function Intersection(status){this.status=status;this.points=[]}fabric.Intersection=Intersection;fabric.Intersection.prototype={constructor:Intersection,appendPoint:function(point){this.points.push(point);return this},appendPoints:function(points){this.points=this.points.concat(points);return this}};fabric.Intersection.intersectLineLine=function(a1,a2,b1,b2){var result,uaT=(b2.x-b1.x)*(a1.y-b1.y)-(b2.y-b1.y)*(a1.x-b1.x),ubT=(a2.x-a1.x)*(a1.y-b1.y)-(a2.y-a1.y)*(a1.x-b1.x),uB=(b2.y-b1.y)*(a2.x-a1.x)-(b2.x-b1.x)*(a2.y-a1.y);if(uB!==0){var ua=uaT/uB,ub=ubT/uB;if(0<=ua&&ua<=1&&0<=ub&&ub<=1){result=new Intersection("Intersection");result.appendPoint(new fabric.Point(a1.x+ua*(a2.x-a1.x),a1.y+ua*(a2.y-a1.y)))}else{result=new Intersection}}else{if(uaT===0||ubT===0){result=new Intersection("Coincident")}else{result=new Intersection("Parallel")}}return result};fabric.Intersection.intersectLinePolygon=function(a1,a2,points){var result=new Intersection,length=points.length,b1,b2,inter;for(var i=0;i<length;i++){b1=points[i];b2=points[(i+1)%length];inter=Intersection.intersectLineLine(a1,a2,b1,b2);result.appendPoints(inter.points)}if(result.points.length>0){result.status="Intersection"}return result};fabric.Intersection.intersectPolygonPolygon=function(points1,points2){var result=new Intersection,length=points1.length;for(var i=0;i<length;i++){var a1=points1[i],a2=points1[(i+1)%length],inter=Intersection.intersectLinePolygon(a1,a2,points2);result.appendPoints(inter.points)}if(result.points.length>0){result.status="Intersection"}return result};fabric.Intersection.intersectPolygonRectangle=function(points,r1,r2){var min=r1.min(r2),max=r1.max(r2),topRight=new fabric.Point(max.x,min.y),bottomLeft=new fabric.Point(min.x,max.y),inter1=Intersection.intersectLinePolygon(min,topRight,points),inter2=Intersection.intersectLinePolygon(topRight,max,points),inter3=Intersection.intersectLinePolygon(max,bottomLeft,points),inter4=Intersection.intersectLinePolygon(bottomLeft,min,points),result=new Intersection;result.appendPoints(inter1.points);result.appendPoints(inter2.points);result.appendPoints(inter3.points);result.appendPoints(inter4.points);if(result.points.length>0){result.status="Intersection"}return result}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={});if(fabric.Color){fabric.warn("fabric.Color is already defined.");return}function Color(color){if(!color){this.setSource([0,0,0,1])}else{this._tryParsingColor(color)}}fabric.Color=Color;fabric.Color.prototype={_tryParsingColor:function(color){var source;if(color in Color.colorNameMap){color=Color.colorNameMap[color]}if(color==="transparent"){source=[255,255,255,0]}if(!source){source=Color.sourceFromHex(color)}if(!source){source=Color.sourceFromRgb(color)}if(!source){source=Color.sourceFromHsl(color)}if(!source){source=[0,0,0,1]}if(source){this.setSource(source)}},_rgbToHsl:function(r,g,b){r/=255;g/=255;b/=255;var h,s,l,max=fabric.util.array.max([r,g,b]),min=fabric.util.array.min([r,g,b]);l=(max+min)/2;if(max===min){h=s=0}else{var d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;case b:h=(r-g)/d+4;break}h/=6}return[Math.round(h*360),Math.round(s*100),Math.round(l*100)]},getSource:function(){return this._source},setSource:function(source){this._source=source},toRgb:function(){var source=this.getSource();return"rgb("+source[0]+","+source[1]+","+source[2]+")"},toRgba:function(){var source=this.getSource();return"rgba("+source[0]+","+source[1]+","+source[2]+","+source[3]+")"},toHsl:function(){var source=this.getSource(),hsl=this._rgbToHsl(source[0],source[1],source[2]);return"hsl("+hsl[0]+","+hsl[1]+"%,"+hsl[2]+"%)"},toHsla:function(){var source=this.getSource(),hsl=this._rgbToHsl(source[0],source[1],source[2]);return"hsla("+hsl[0]+","+hsl[1]+"%,"+hsl[2]+"%,"+source[3]+")"},toHex:function(){var source=this.getSource(),r,g,b;r=source[0].toString(16);r=r.length===1?"0"+r:r;g=source[1].toString(16);g=g.length===1?"0"+g:g;b=source[2].toString(16);b=b.length===1?"0"+b:b;return r.toUpperCase()+g.toUpperCase()+b.toUpperCase()},toHexa:function(){var source=this.getSource(),a;a=source[3]*255;a=a.toString(16);a=a.length===1?"0"+a:a;return this.toHex()+a.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(alpha){var source=this.getSource();source[3]=alpha;this.setSource(source);return this},toGrayscale:function(){var source=this.getSource(),average=parseInt((source[0]*.3+source[1]*.59+source[2]*.11).toFixed(0),10),currentAlpha=source[3];this.setSource([average,average,average,currentAlpha]);return this},toBlackWhite:function(threshold){var source=this.getSource(),average=(source[0]*.3+source[1]*.59+source[2]*.11).toFixed(0),currentAlpha=source[3];threshold=threshold||127;average=Number(average)<Number(threshold)?0:255;this.setSource([average,average,average,currentAlpha]);return this},overlayWith:function(otherColor){if(!(otherColor instanceof Color)){otherColor=new Color(otherColor)}var result=[],alpha=this.getAlpha(),otherAlpha=.5,source=this.getSource(),otherSource=otherColor.getSource();for(var i=0;i<3;i++){result.push(Math.round(source[i]*(1-otherAlpha)+otherSource[i]*otherAlpha))}result[3]=alpha;this.setSource(result);return this}};fabric.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;fabric.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;fabric.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;fabric.Color.colorNameMap={aqua:"#00FFFF",black:"#000000",blue:"#0000FF",fuchsia:"#FF00FF",gray:"#808080",grey:"#808080",green:"#008000",lime:"#00FF00",maroon:"#800000",navy:"#000080",olive:"#808000",orange:"#FFA500",purple:"#800080",red:"#FF0000",silver:"#C0C0C0",teal:"#008080",white:"#FFFFFF",yellow:"#FFFF00"};function hue2rgb(p,q,t){if(t<0){t+=1}if(t>1){t-=1}if(t<1/6){return p+(q-p)*6*t}if(t<1/2){return q}if(t<2/3){return p+(q-p)*(2/3-t)*6}return p}fabric.Color.fromRgb=function(color){return Color.fromSource(Color.sourceFromRgb(color))};fabric.Color.sourceFromRgb=function(color){var match=color.match(Color.reRGBa);if(match){var r=parseInt(match[1],10)/(/%$/.test(match[1])?100:1)*(/%$/.test(match[1])?255:1),g=parseInt(match[2],10)/(/%$/.test(match[2])?100:1)*(/%$/.test(match[2])?255:1),b=parseInt(match[3],10)/(/%$/.test(match[3])?100:1)*(/%$/.test(match[3])?255:1);return[parseInt(r,10),parseInt(g,10),parseInt(b,10),match[4]?parseFloat(match[4]):1]}};fabric.Color.fromRgba=Color.fromRgb;fabric.Color.fromHsl=function(color){return Color.fromSource(Color.sourceFromHsl(color))};fabric.Color.sourceFromHsl=function(color){var match=color.match(Color.reHSLa);if(!match){return}var h=(parseFloat(match[1])%360+360)%360/360,s=parseFloat(match[2])/(/%$/.test(match[2])?100:1),l=parseFloat(match[3])/(/%$/.test(match[3])?100:1),r,g,b;if(s===0){r=g=b=l}else{var q=l<=.5?l*(s+1):l+s-l*s,p=l*2-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3)}return[Math.round(r*255),Math.round(g*255),Math.round(b*255),match[4]?parseFloat(match[4]):1]};fabric.Color.fromHsla=Color.fromHsl;fabric.Color.fromHex=function(color){return Color.fromSource(Color.sourceFromHex(color))};fabric.Color.sourceFromHex=function(color){if(color.match(Color.reHex)){var value=color.slice(color.indexOf("#")+1),isShortNotation=value.length===3||value.length===4,isRGBa=value.length===8||value.length===4,r=isShortNotation?value.charAt(0)+value.charAt(0):value.substring(0,2),g=isShortNotation?value.charAt(1)+value.charAt(1):value.substring(2,4),b=isShortNotation?value.charAt(2)+value.charAt(2):value.substring(4,6),a=isRGBa?isShortNotation?value.charAt(3)+value.charAt(3):value.substring(6,8):"FF";return[parseInt(r,16),parseInt(g,16),parseInt(b,16),parseFloat((parseInt(a,16)/255).toFixed(2))]}};fabric.Color.fromSource=function(source){var oColor=new Color;oColor.setSource(source);return oColor}})(typeof exports!=="undefined"?exports:this);(function(){function getColorStop(el){var style=el.getAttribute("style"),offset=el.getAttribute("offset")||0,color,colorAlpha,opacity;offset=parseFloat(offset)/(/%$/.test(offset)?100:1);offset=offset<0?0:offset>1?1:offset;if(style){var keyValuePairs=style.split(/\s*;\s*/);if(keyValuePairs[keyValuePairs.length-1]===""){keyValuePairs.pop()}for(var i=keyValuePairs.length;i--;){var split=keyValuePairs[i].split(/\s*:\s*/),key=split[0].trim(),value=split[1].trim();if(key==="stop-color"){color=value}else if(key==="stop-opacity"){opacity=value}}}if(!color){color=el.getAttribute("stop-color")||"rgb(0,0,0)"}if(!opacity){opacity=el.getAttribute("stop-opacity")}color=new fabric.Color(color);colorAlpha=color.getAlpha();opacity=isNaN(parseFloat(opacity))?1:parseFloat(opacity);opacity*=colorAlpha;return{offset:offset,color:color.toRgb(),opacity:opacity}}function getLinearCoords(el){return{x1:el.getAttribute("x1")||0,y1:el.getAttribute("y1")||0,x2:el.getAttribute("x2")||"100%",y2:el.getAttribute("y2")||0}}function getRadialCoords(el){return{x1:el.getAttribute("fx")||el.getAttribute("cx")||"50%",y1:el.getAttribute("fy")||el.getAttribute("cy")||"50%",r1:0,x2:el.getAttribute("cx")||"50%",y2:el.getAttribute("cy")||"50%",r2:el.getAttribute("r")||"50%"}}var clone=fabric.util.object.clone;fabric.Gradient=fabric.util.createClass({offsetX:0,offsetY:0,initialize:function(options){options||(options={});var coords={};this.id=fabric.Object.__uid++;this.type=options.type||"linear";coords={x1:options.coords.x1||0,y1:options.coords.y1||0,x2:options.coords.x2||0,y2:options.coords.y2||0};if(this.type==="radial"){coords.r1=options.coords.r1||0;coords.r2=options.coords.r2||0}this.coords=coords;this.colorStops=options.colorStops.slice();if(options.gradientTransform){this.gradientTransform=options.gradientTransform}this.offsetX=options.offsetX||this.offsetX;this.offsetY=options.offsetY||this.offsetY},addColorStop:function(colorStops){for(var position in colorStops){var color=new fabric.Color(colorStops[position]);this.colorStops.push({offset:parseFloat(position),color:color.toRgb(),opacity:color.getAlpha()})}return this},toObject:function(propertiesToInclude){var object={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};fabric.util.populateWithProperties(this,object,propertiesToInclude);return object},toSVG:function(object){var coords=clone(this.coords,true),markup,commonAttributes,colorStops=clone(this.colorStops,true),needsSwap=coords.r1>coords.r2;colorStops.sort(function(a,b){return a.offset-b.offset});if(!(object.group&&object.group.type==="path-group")){for(var prop in coords){if(prop==="x1"||prop==="x2"){coords[prop]+=this.offsetX-object.width/2}else if(prop==="y1"||prop==="y2"){coords[prop]+=this.offsetY-object.height/2}}}commonAttributes='id="SVGID_'+this.id+'" gradientUnits="userSpaceOnUse"';if(this.gradientTransform){commonAttributes+=' gradientTransform="matrix('+this.gradientTransform.join(" ")+')" '}if(this.type==="linear"){markup=["<linearGradient ",commonAttributes,' x1="',coords.x1,'" y1="',coords.y1,'" x2="',coords.x2,'" y2="',coords.y2,'">\n']}else if(this.type==="radial"){markup=["<radialGradient ",commonAttributes,' cx="',needsSwap?coords.x1:coords.x2,'" cy="',needsSwap?coords.y1:coords.y2,'" r="',needsSwap?coords.r1:coords.r2,'" fx="',needsSwap?coords.x2:coords.x1,'" fy="',needsSwap?coords.y2:coords.y1,'">\n']}if(this.type==="radial"){if(needsSwap){colorStops=colorStops.concat();colorStops.reverse();for(var i=0;i<colorStops.length;i++){colorStops[i].offset=1-colorStops[i].offset}}var minRadius=Math.min(coords.r1,coords.r2);if(minRadius>0){var maxRadius=Math.max(coords.r1,coords.r2),percentageShift=minRadius/maxRadius;for(var i=0;i<colorStops.length;i++){colorStops[i].offset+=percentageShift*(1-colorStops[i].offset)}}}for(var i=0;i<colorStops.length;i++){var colorStop=colorStops[i];markup.push("<stop ",'offset="',colorStop.offset*100+"%",'" style="stop-color:',colorStop.color,colorStop.opacity!==null?";stop-opacity: "+colorStop.opacity:";",'"/>\n')}markup.push(this.type==="linear"?"</linearGradient>\n":"</radialGradient>\n");return markup.join("")},toLive:function(ctx,object){var gradient,prop,coords=fabric.util.object.clone(this.coords);if(!this.type){return}if(object.group&&object.group.type==="path-group"){for(prop in coords){if(prop==="x1"||prop==="x2"){coords[prop]+=-this.offsetX+object.width/2}else if(prop==="y1"||prop==="y2"){coords[prop]+=-this.offsetY+object.height/2}}}if(this.type==="linear"){gradient=ctx.createLinearGradient(coords.x1,coords.y1,coords.x2,coords.y2)}else if(this.type==="radial"){gradient=ctx.createRadialGradient(coords.x1,coords.y1,coords.r1,coords.x2,coords.y2,coords.r2)}for(var i=0,len=this.colorStops.length;i<len;i++){var color=this.colorStops[i].color,opacity=this.colorStops[i].opacity,offset=this.colorStops[i].offset;if(typeof opacity!=="undefined"){
color=new fabric.Color(color).setAlpha(opacity).toRgba()}gradient.addColorStop(offset,color)}return gradient}});fabric.util.object.extend(fabric.Gradient,{fromElement:function(el,instance){var colorStopEls=el.getElementsByTagName("stop"),type,gradientUnits=el.getAttribute("gradientUnits")||"objectBoundingBox",gradientTransform=el.getAttribute("gradientTransform"),colorStops=[],coords,ellipseMatrix;if(el.nodeName==="linearGradient"||el.nodeName==="LINEARGRADIENT"){type="linear"}else{type="radial"}if(type==="linear"){coords=getLinearCoords(el)}else if(type==="radial"){coords=getRadialCoords(el)}for(var i=colorStopEls.length;i--;){colorStops.push(getColorStop(colorStopEls[i]))}ellipseMatrix=_convertPercentUnitsToValues(instance,coords,gradientUnits);var gradient=new fabric.Gradient({type:type,coords:coords,colorStops:colorStops,offsetX:-instance.left,offsetY:-instance.top});if(gradientTransform||ellipseMatrix!==""){gradient.gradientTransform=fabric.parseTransformAttribute((gradientTransform||"")+ellipseMatrix)}return gradient},forObject:function(obj,options){options||(options={});_convertPercentUnitsToValues(obj,options.coords,"userSpaceOnUse");return new fabric.Gradient(options)}});function _convertPercentUnitsToValues(object,options,gradientUnits){var propValue,addFactor=0,multFactor=1,ellipseMatrix="";for(var prop in options){if(options[prop]==="Infinity"){options[prop]=1}else if(options[prop]==="-Infinity"){options[prop]=0}propValue=parseFloat(options[prop],10);if(typeof options[prop]==="string"&&/^\d+%$/.test(options[prop])){multFactor=.01}else{multFactor=1}if(prop==="x1"||prop==="x2"||prop==="r2"){multFactor*=gradientUnits==="objectBoundingBox"?object.width:1;addFactor=gradientUnits==="objectBoundingBox"?object.left||0:0}else if(prop==="y1"||prop==="y2"){multFactor*=gradientUnits==="objectBoundingBox"?object.height:1;addFactor=gradientUnits==="objectBoundingBox"?object.top||0:0}options[prop]=propValue*multFactor+addFactor}if(object.type==="ellipse"&&options.r2!==null&&gradientUnits==="objectBoundingBox"&&object.rx!==object.ry){var scaleFactor=object.ry/object.rx;ellipseMatrix=" scale(1, "+scaleFactor+")";if(options.y1){options.y1/=scaleFactor}if(options.y2){options.y2/=scaleFactor}}return ellipseMatrix}})();(function(){"use strict";var toFixed=fabric.util.toFixed;fabric.Pattern=fabric.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,initialize:function(options,callback){options||(options={});this.id=fabric.Object.__uid++;this.setOptions(options);if(!options.source||options.source&&typeof options.source!=="string"){callback&&callback(this);return}if(typeof fabric.util.getFunctionBody(options.source)!=="undefined"){this.source=new Function(fabric.util.getFunctionBody(options.source));callback&&callback(this)}else{var _this=this;this.source=fabric.util.createImage();fabric.util.loadImage(options.source,function(img){_this.source=img;callback&&callback(_this)})}},toObject:function(propertiesToInclude){var NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS,source,object;if(typeof this.source==="function"){source=String(this.source)}else if(typeof this.source.src==="string"){source=this.source.src}else if(typeof this.source==="object"&&this.source.toDataURL){source=this.source.toDataURL()}object={type:"pattern",source:source,repeat:this.repeat,offsetX:toFixed(this.offsetX,NUM_FRACTION_DIGITS),offsetY:toFixed(this.offsetY,NUM_FRACTION_DIGITS)};fabric.util.populateWithProperties(this,object,propertiesToInclude);return object},toSVG:function(object){var patternSource=typeof this.source==="function"?this.source():this.source,patternWidth=patternSource.width/object.width,patternHeight=patternSource.height/object.height,patternOffsetX=this.offsetX/object.width,patternOffsetY=this.offsetY/object.height,patternImgSrc="";if(this.repeat==="repeat-x"||this.repeat==="no-repeat"){patternHeight=1}if(this.repeat==="repeat-y"||this.repeat==="no-repeat"){patternWidth=1}if(patternSource.src){patternImgSrc=patternSource.src}else if(patternSource.toDataURL){patternImgSrc=patternSource.toDataURL()}return'<pattern id="SVGID_'+this.id+'" x="'+patternOffsetX+'" y="'+patternOffsetY+'" width="'+patternWidth+'" height="'+patternHeight+'">\n'+'<image x="0" y="0"'+' width="'+patternSource.width+'" height="'+patternSource.height+'" xlink:href="'+patternImgSrc+'"></image>\n'+"</pattern>\n"},setOptions:function(options){for(var prop in options){this[prop]=options[prop]}},toLive:function(ctx){var source=typeof this.source==="function"?this.source():this.source;if(!source){return""}if(typeof source.src!=="undefined"){if(!source.complete){return""}if(source.naturalWidth===0||source.naturalHeight===0){return""}}return ctx.createPattern(source,this.repeat)}})})();(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),toFixed=fabric.util.toFixed;if(fabric.Shadow){fabric.warn("fabric.Shadow is already defined.");return}fabric.Shadow=fabric.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:false,includeDefaultValues:true,initialize:function(options){if(typeof options==="string"){options=this._parseShadow(options)}for(var prop in options){this[prop]=options[prop]}this.id=fabric.Object.__uid++},_parseShadow:function(shadow){var shadowStr=shadow.trim(),offsetsAndBlur=fabric.Shadow.reOffsetsAndBlur.exec(shadowStr)||[],color=shadowStr.replace(fabric.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)";return{color:color.trim(),offsetX:parseInt(offsetsAndBlur[1],10)||0,offsetY:parseInt(offsetsAndBlur[2],10)||0,blur:parseInt(offsetsAndBlur[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(object){var fBoxX=40,fBoxY=40,NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS,offset=fabric.util.rotateVector({x:this.offsetX,y:this.offsetY},fabric.util.degreesToRadians(-object.angle)),BLUR_BOX=20;if(object.width&&object.height){fBoxX=toFixed((Math.abs(offset.x)+this.blur)/object.width,NUM_FRACTION_DIGITS)*100+BLUR_BOX;fBoxY=toFixed((Math.abs(offset.y)+this.blur)/object.height,NUM_FRACTION_DIGITS)*100+BLUR_BOX}if(object.flipX){offset.x*=-1}if(object.flipY){offset.y*=-1}return'<filter id="SVGID_'+this.id+'" y="-'+fBoxY+'%" height="'+(100+2*fBoxY)+'%" '+'x="-'+fBoxX+'%" width="'+(100+2*fBoxX)+'%" '+">\n"+' <feGaussianBlur in="SourceAlpha" stdDeviation="'+toFixed(this.blur?this.blur/2:0,NUM_FRACTION_DIGITS)+'"></feGaussianBlur>\n'+' <feOffset dx="'+toFixed(offset.x,NUM_FRACTION_DIGITS)+'" dy="'+toFixed(offset.y,NUM_FRACTION_DIGITS)+'" result="oBlur" ></feOffset>\n'+' <feFlood flood-color="'+this.color+'"/>\n'+' <feComposite in2="oBlur" operator="in" />\n'+" <feMerge>\n"+" <feMergeNode></feMergeNode>\n"+' <feMergeNode in="SourceGraphic"></feMergeNode>\n'+" </feMerge>\n"+"</filter>\n"},toObject:function(){if(this.includeDefaultValues){return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke}}var obj={},proto=fabric.Shadow.prototype;["color","blur","offsetX","offsetY","affectStroke"].forEach(function(prop){if(this[prop]!==proto[prop]){obj[prop]=this[prop]}},this);return obj}});fabric.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/})(typeof exports!=="undefined"?exports:this);(function(){"use strict";if(fabric.StaticCanvas){fabric.warn("fabric.StaticCanvas is already defined.");return}var extend=fabric.util.object.extend,getElementOffset=fabric.util.getElementOffset,removeFromArray=fabric.util.removeFromArray,toFixed=fabric.util.toFixed,transformPoint=fabric.util.transformPoint,invertTransform=fabric.util.invertTransform,CANVAS_INIT_ERROR=new Error("Could not initialize `canvas` element");fabric.StaticCanvas=fabric.util.createClass(fabric.CommonMethods,{initialize:function(el,options){options||(options={});this._initStatic(el,options)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:true,stateful:false,renderOnAddRemove:true,clipTo:null,controlsAboveOverlay:false,allowTouchScrolling:false,imageSmoothingEnabled:true,viewportTransform:fabric.iMatrix.concat(),backgroundVpt:true,overlayVpt:true,onBeforeScaleRotate:function(){},enableRetinaScaling:true,vptCoords:{},skipOffscreen:false,_initStatic:function(el,options){var cb=fabric.StaticCanvas.prototype.renderAll.bind(this);this._objects=[];this._createLowerCanvas(el);this._initOptions(options);this._setImageSmoothing();if(!this.interactive){this._initRetinaScaling()}if(options.overlayImage){this.setOverlayImage(options.overlayImage,cb)}if(options.backgroundImage){this.setBackgroundImage(options.backgroundImage,cb)}if(options.backgroundColor){this.setBackgroundColor(options.backgroundColor,cb)}if(options.overlayColor){this.setOverlayColor(options.overlayColor,cb)}this.calcOffset()},_isRetinaScaling:function(){return fabric.devicePixelRatio!==1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?fabric.devicePixelRatio:1},_initRetinaScaling:function(){if(!this._isRetinaScaling()){return}this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio);this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio);this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio)},calcOffset:function(){this._offset=getElementOffset(this.lowerCanvasEl);return this},setOverlayImage:function(image,callback,options){return this.__setBgOverlayImage("overlayImage",image,callback,options)},setBackgroundImage:function(image,callback,options){return this.__setBgOverlayImage("backgroundImage",image,callback,options)},setOverlayColor:function(overlayColor,callback){return this.__setBgOverlayColor("overlayColor",overlayColor,callback)},setBackgroundColor:function(backgroundColor,callback){return this.__setBgOverlayColor("backgroundColor",backgroundColor,callback)},_setImageSmoothing:function(){var ctx=this.getContext();ctx.imageSmoothingEnabled=ctx.imageSmoothingEnabled||ctx.webkitImageSmoothingEnabled||ctx.mozImageSmoothingEnabled||ctx.msImageSmoothingEnabled||ctx.oImageSmoothingEnabled;ctx.imageSmoothingEnabled=this.imageSmoothingEnabled},__setBgOverlayImage:function(property,image,callback,options){if(typeof image==="string"){fabric.util.loadImage(image,function(img){img&&(this[property]=new fabric.Image(img,options));callback&&callback(img)},this,options&&options.crossOrigin)}else{options&&image.setOptions(options);this[property]=image;callback&&callback(image)}return this},__setBgOverlayColor:function(property,color,callback){this[property]=color;this._initGradient(color,property);this._initPattern(color,property,callback);return this},_createCanvasElement:function(canvasEl){var element=fabric.util.createCanvasElement(canvasEl);if(!element.style){element.style={}}if(!element){throw CANVAS_INIT_ERROR}if(typeof element.getContext==="undefined"){throw CANVAS_INIT_ERROR}return element},_initOptions:function(options){this._setOptions(options);this.width=this.width||parseInt(this.lowerCanvasEl.width,10)||0;this.height=this.height||parseInt(this.lowerCanvasEl.height,10)||0;if(!this.lowerCanvasEl.style){return}this.lowerCanvasEl.width=this.width;this.lowerCanvasEl.height=this.height;this.lowerCanvasEl.style.width=this.width+"px";this.lowerCanvasEl.style.height=this.height+"px";this.viewportTransform=this.viewportTransform.slice()},_createLowerCanvas:function(canvasEl){this.lowerCanvasEl=fabric.util.getById(canvasEl)||this._createCanvasElement(canvasEl);fabric.util.addClass(this.lowerCanvasEl,"lower-canvas");if(this.interactive){this._applyCanvasStyle(this.lowerCanvasEl)}this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(value,options){return this.setDimensions({width:value},options)},setHeight:function(value,options){return this.setDimensions({height:value},options)},setDimensions:function(dimensions,options){var cssValue;options=options||{};for(var prop in dimensions){cssValue=dimensions[prop];if(!options.cssOnly){this._setBackstoreDimension(prop,dimensions[prop]);cssValue+="px"}if(!options.backstoreOnly){this._setCssDimension(prop,cssValue)}}this._initRetinaScaling();this._setImageSmoothing();this.calcOffset();if(!options.cssOnly){this.renderAll()}return this},_setBackstoreDimension:function(prop,value){this.lowerCanvasEl[prop]=value;if(this.upperCanvasEl){this.upperCanvasEl[prop]=value}if(this.cacheCanvasEl){this.cacheCanvasEl[prop]=value}this[prop]=value;return this},_setCssDimension:function(prop,value){this.lowerCanvasEl.style[prop]=value;if(this.upperCanvasEl){this.upperCanvasEl.style[prop]=value}if(this.wrapperEl){this.wrapperEl.style[prop]=value}return this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(vpt){var activeGroup=this._activeGroup,object,ingoreVpt=false,skipAbsolute=true;this.viewportTransform=vpt;for(var i=0,len=this._objects.length;i<len;i++){object=this._objects[i];object.group||object.setCoords(ingoreVpt,skipAbsolute)}if(activeGroup){activeGroup.setCoords(ingoreVpt,skipAbsolute)}this.calcViewportBoundaries();this.renderAll();return this},zoomToPoint:function(point,value){var before=point,vpt=this.viewportTransform.slice(0);point=transformPoint(point,invertTransform(this.viewportTransform));vpt[0]=value;vpt[3]=value;var after=transformPoint(point,vpt);vpt[4]+=before.x-after.x;vpt[5]+=before.y-after.y;return this.setViewportTransform(vpt)},setZoom:function(value){this.zoomToPoint(new fabric.Point(0,0),value);return this},absolutePan:function(point){var vpt=this.viewportTransform.slice(0);vpt[4]=-point.x;vpt[5]=-point.y;return this.setViewportTransform(vpt)},relativePan:function(point){return this.absolutePan(new fabric.Point(-point.x-this.viewportTransform[4],-point.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(obj){this.stateful&&obj.setupState();obj._set("canvas",this);obj.setCoords();this.fire("object:added",{target:obj});obj.fire("added")},_onObjectRemoved:function(obj){this.fire("object:removed",{target:obj});obj.fire("removed");delete obj.canvas},clearContext:function(ctx){ctx.clearRect(0,0,this.width,this.height);return this},getContext:function(){return this.contextContainer},clear:function(){this._objects.length=0;this.backgroundImage=null;this.overlayImage=null;this.backgroundColor="";this.overlayColor="";if(this._hasITextHandlers){this.off("mouse:up",this._mouseUpITextHandler);this._iTextInstances=null;this._hasITextHandlers=false}this.clearContext(this.contextContainer);this.fire("canvas:cleared");this.renderAll();return this},renderAll:function(){var canvasToDrawOn=this.contextContainer;this.renderCanvas(canvasToDrawOn,this._objects);return this},calcViewportBoundaries:function(){var points={},width=this.getWidth(),height=this.getHeight(),iVpt=invertTransform(this.viewportTransform);points.tl=transformPoint({x:0,y:0},iVpt);points.br=transformPoint({x:width,y:height},iVpt);points.tr=new fabric.Point(points.br.x,points.tl.y);points.bl=new fabric.Point(points.tl.x,points.br.y);this.vptCoords=points;return points},renderCanvas:function(ctx,objects){this.calcViewportBoundaries();this.clearContext(ctx);this.fire("before:render");if(this.clipTo){fabric.util.clipContext(this,ctx)}this._renderBackground(ctx);ctx.save();ctx.transform.apply(ctx,this.viewportTransform);this._renderObjects(ctx,objects);ctx.restore();if(!this.controlsAboveOverlay&&this.interactive){this.drawControls(ctx)}if(this.clipTo){ctx.restore()}this._renderOverlay(ctx);if(this.controlsAboveOverlay&&this.interactive){this.drawControls(ctx)}this.fire("after:render")},_renderObjects:function(ctx,objects){for(var i=0,length=objects.length;i<length;++i){objects[i]&&objects[i].render(ctx)}},_renderBackgroundOrOverlay:function(ctx,property){var object=this[property+"Color"];if(object){ctx.fillStyle=object.toLive?object.toLive(ctx,this):object;ctx.fillRect(object.offsetX||0,object.offsetY||0,this.width,this.height)}object=this[property+"Image"];if(object){if(this[property+"Vpt"]){ctx.save();ctx.transform.apply(ctx,this.viewportTransform)}object.render(ctx);this[property+"Vpt"]&&ctx.restore()}},_renderBackground:function(ctx){this._renderBackgroundOrOverlay(ctx,"background")},_renderOverlay:function(ctx){this._renderBackgroundOrOverlay(ctx,"overlay")},getCenter:function(){return{top:this.getHeight()/2,left:this.getWidth()/2}},centerObjectH:function(object){return this._centerObject(object,new fabric.Point(this.getCenter().left,object.getCenterPoint().y))},centerObjectV:function(object){return this._centerObject(object,new fabric.Point(object.getCenterPoint().x,this.getCenter().top))},centerObject:function(object){var center=this.getCenter();return this._centerObject(object,new fabric.Point(center.left,center.top))},viewportCenterObject:function(object){var vpCenter=this.getVpCenter();return this._centerObject(object,vpCenter)},viewportCenterObjectH:function(object){var vpCenter=this.getVpCenter();this._centerObject(object,new fabric.Point(vpCenter.x,object.getCenterPoint().y));return this},viewportCenterObjectV:function(object){var vpCenter=this.getVpCenter();return this._centerObject(object,new fabric.Point(object.getCenterPoint().x,vpCenter.y))},getVpCenter:function(){var center=this.getCenter(),iVpt=invertTransform(this.viewportTransform);return transformPoint({x:center.left,y:center.top},iVpt)},_centerObject:function(object,center){object.setPositionByOrigin(center,"center","center");this.renderAll();return this},toDatalessJSON:function(propertiesToInclude){return this.toDatalessObject(propertiesToInclude)},toObject:function(propertiesToInclude){return this._toObjectMethod("toObject",propertiesToInclude)},toDatalessObject:function(propertiesToInclude){return this._toObjectMethod("toDatalessObject",propertiesToInclude)},_toObjectMethod:function(methodName,propertiesToInclude){var data={objects:this._toObjects(methodName,propertiesToInclude)};extend(data,this.__serializeBgOverlay(methodName,propertiesToInclude));fabric.util.populateWithProperties(this,data,propertiesToInclude);return data},_toObjects:function(methodName,propertiesToInclude){return this.getObjects().filter(function(object){return!object.excludeFromExport}).map(function(instance){return this._toObject(instance,methodName,propertiesToInclude)},this)},_toObject:function(instance,methodName,propertiesToInclude){var originalValue;if(!this.includeDefaultValues){originalValue=instance.includeDefaultValues;instance.includeDefaultValues=false}var object=instance[methodName](propertiesToInclude);if(!this.includeDefaultValues){instance.includeDefaultValues=originalValue}return object},__serializeBgOverlay:function(methodName,propertiesToInclude){var data={};if(this.backgroundColor){data.background=this.backgroundColor.toObject?this.backgroundColor.toObject(propertiesToInclude):this.backgroundColor}if(this.overlayColor){data.overlay=this.overlayColor.toObject?this.overlayColor.toObject(propertiesToInclude):this.overlayColor}if(this.backgroundImage){data.backgroundImage=this._toObject(this.backgroundImage,methodName,propertiesToInclude)}if(this.overlayImage){data.overlayImage=this._toObject(this.overlayImage,methodName,propertiesToInclude)}return data},svgViewportTransformation:true,toSVG:function(options,reviver){options||(options={});var markup=[];this._setSVGPreamble(markup,options);this._setSVGHeader(markup,options);this._setSVGBgOverlayColor(markup,"backgroundColor");this._setSVGBgOverlayImage(markup,"backgroundImage",reviver);this._setSVGObjects(markup,reviver);this._setSVGBgOverlayColor(markup,"overlayColor");this._setSVGBgOverlayImage(markup,"overlayImage",reviver);markup.push("</svg>");return markup.join("")},_setSVGPreamble:function(markup,options){if(options.suppressPreamble){return}markup.push('<?xml version="1.0" encoding="',options.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(markup,options){var width=options.width||this.width,height=options.height||this.height,vpt,viewBox='viewBox="0 0 '+this.width+" "+this.height+'" ',NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS;if(options.viewBox){viewBox='viewBox="'+options.viewBox.x+" "+options.viewBox.y+" "+options.viewBox.width+" "+options.viewBox.height+'" '}else{if(this.svgViewportTransformation){vpt=this.viewportTransform;viewBox='viewBox="'+toFixed(-vpt[4]/vpt[0],NUM_FRACTION_DIGITS)+" "+toFixed(-vpt[5]/vpt[3],NUM_FRACTION_DIGITS)+" "+toFixed(this.width/vpt[0],NUM_FRACTION_DIGITS)+" "+toFixed(this.height/vpt[3],NUM_FRACTION_DIGITS)+'" '}}markup.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',width,'" ','height="',height,'" ',viewBox,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",fabric.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),"</defs>\n")},createSVGRefElementsMarkup:function(){var _this=this,markup=["backgroundColor","overlayColor"].map(function(prop){var fill=_this[prop];if(fill&&fill.toLive){return fill.toSVG(_this,false)}});return markup.join("")},createSVGFontFacesMarkup:function(){var markup="",fontList={},obj,fontFamily,style,row,rowIndex,_char,charIndex,fontPaths=fabric.fontPaths,objects=this.getObjects();for(var i=0,len=objects.length;i<len;i++){obj=objects[i];fontFamily=obj.fontFamily;if(obj.type.indexOf("text")===-1||fontList[fontFamily]||!fontPaths[fontFamily]){continue}fontList[fontFamily]=true;if(!obj.styles){continue}style=obj.styles;for(rowIndex in style){row=style[rowIndex];for(charIndex in row){_char=row[charIndex];fontFamily=_char.fontFamily;if(!fontList[fontFamily]&&fontPaths[fontFamily]){fontList[fontFamily]=true}}}}for(var j in fontList){markup+=[" @font-face {\n"," font-family: '",j,"';\n"," src: url('",fontPaths[j],"');\n"," }\n"].join("")}if(markup){markup=[' <style type="text/css">',"<![CDATA[\n",markup,"]]>","</style>\n"].join("")}return markup},_setSVGObjects:function(markup,reviver){var instance;for(var i=0,objects=this.getObjects(),len=objects.length;i<len;i++){instance=objects[i];if(instance.excludeFromExport){continue}this._setSVGObject(markup,instance,reviver)}},_setSVGObject:function(markup,instance,reviver){markup.push(instance.toSVG(reviver))},_setSVGBgOverlayImage:function(markup,property,reviver){if(this[property]&&this[property].toSVG){markup.push(this[property].toSVG(reviver))}},_setSVGBgOverlayColor:function(markup,property){var filler=this[property];if(!filler){return}if(filler.toLive){var repeat=filler.repeat;markup.push('<rect transform="translate(',this.width/2,",",this.height/2,')"',' x="',filler.offsetX-this.width/2,'" y="',filler.offsetY-this.height/2,'" ','width="',repeat==="repeat-y"||repeat==="no-repeat"?filler.source.width:this.width,'" height="',repeat==="repeat-x"||repeat==="no-repeat"?filler.source.height:this.height,'" fill="url(#SVGID_'+filler.id+')"',"></rect>\n")}else{markup.push('<rect x="0" y="0" ','width="',this.width,'" height="',this.height,'" fill="',this[property],'"',"></rect>\n")}},sendToBack:function(object){if(!object){return this}var activeGroup=this._activeGroup,i,obj,objs;if(object===activeGroup){objs=activeGroup._objects;for(i=objs.length;i--;){obj=objs[i];removeFromArray(this._objects,obj);this._objects.unshift(obj)}}else{removeFromArray(this._objects,object);this._objects.unshift(object)}return this.renderAll&&this.renderAll()},bringToFront:function(object){if(!object){return this}var activeGroup=this._activeGroup,i,obj,objs;if(object===activeGroup){objs=activeGroup._objects;for(i=0;i<objs.length;i++){obj=objs[i];removeFromArray(this._objects,obj);this._objects.push(obj)}}else{removeFromArray(this._objects,object);this._objects.push(object)}return this.renderAll&&this.renderAll()},sendBackwards:function(object,intersecting){if(!object){return this}var activeGroup=this._activeGroup,i,obj,idx,newIdx,objs;if(object===activeGroup){objs=activeGroup._objects;for(i=0;i<objs.length;i++){obj=objs[i];idx=this._objects.indexOf(obj);if(idx!==0){newIdx=idx-1;removeFromArray(this._objects,obj);this._objects.splice(newIdx,0,obj)}}}else{idx=this._objects.indexOf(object);if(idx!==0){newIdx=this._findNewLowerIndex(object,idx,intersecting);removeFromArray(this._objects,object);this._objects.splice(newIdx,0,object)}}this.renderAll&&this.renderAll();return this},_findNewLowerIndex:function(object,idx,intersecting){var newIdx;if(intersecting){newIdx=idx;for(var i=idx-1;i>=0;--i){var isIntersecting=object.intersectsWithObject(this._objects[i])||object.isContainedWithinObject(this._objects[i])||this._objects[i].isContainedWithinObject(object);if(isIntersecting){newIdx=i;break}}}else{newIdx=idx-1}return newIdx},bringForward:function(object,intersecting){if(!object){return this}var activeGroup=this._activeGroup,i,obj,idx,newIdx,objs;if(object===activeGroup){objs=activeGroup._objects;for(i=objs.length;i--;){obj=objs[i];idx=this._objects.indexOf(obj);if(idx!==this._objects.length-1){newIdx=idx+1;removeFromArray(this._objects,obj);this._objects.splice(newIdx,0,obj)}}}else{idx=this._objects.indexOf(object);if(idx!==this._objects.length-1){newIdx=this._findNewUpperIndex(object,idx,intersecting);removeFromArray(this._objects,object);this._objects.splice(newIdx,0,object)}}this.renderAll&&this.renderAll();return this},_findNewUpperIndex:function(object,idx,intersecting){var newIdx;if(intersecting){newIdx=idx;for(var i=idx+1;i<this._objects.length;++i){var isIntersecting=object.intersectsWithObject(this._objects[i])||object.isContainedWithinObject(this._objects[i])||this._objects[i].isContainedWithinObject(object);if(isIntersecting){newIdx=i;break}}}else{newIdx=idx+1}return newIdx},moveTo:function(object,index){removeFromArray(this._objects,object);this._objects.splice(index,0,object);return this.renderAll&&this.renderAll()},dispose:function(){this.clear();return this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): "+"{ objects: "+this.getObjects().length+" }>"}});extend(fabric.StaticCanvas.prototype,fabric.Observable);extend(fabric.StaticCanvas.prototype,fabric.Collection);extend(fabric.StaticCanvas.prototype,fabric.DataURLExporter);extend(fabric.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(methodName){var el=fabric.util.createCanvasElement();if(!el||!el.getContext){return null}var ctx=el.getContext("2d");if(!ctx){return null}switch(methodName){case"getImageData":return typeof ctx.getImageData!=="undefined";case"setLineDash":return typeof ctx.setLineDash!=="undefined";case"toDataURL":return typeof el.toDataURL!=="undefined";case"toDataURLWithQuality":try{el.toDataURL("image/jpeg",0);return true}catch(e){}return false;default:return null}}});fabric.StaticCanvas.prototype.toJSON=fabric.StaticCanvas.prototype.toObject})();fabric.BaseBrush=fabric.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeDashArray:null,setShadow:function(options){this.shadow=new fabric.Shadow(options);return this},_setBrushStyles:function(){var ctx=this.canvas.contextTop;ctx.strokeStyle=this.color;ctx.lineWidth=this.width;ctx.lineCap=this.strokeLineCap;ctx.lineJoin=this.strokeLineJoin;if(this.strokeDashArray&&fabric.StaticCanvas.supports("setLineDash")){ctx.setLineDash(this.strokeDashArray)}},_setShadow:function(){if(!this.shadow){return}var ctx=this.canvas.contextTop,zoom=this.canvas.getZoom();ctx.shadowColor=this.shadow.color;ctx.shadowBlur=this.shadow.blur*zoom;ctx.shadowOffsetX=this.shadow.offsetX*zoom;ctx.shadowOffsetY=this.shadow.offsetY*zoom},_resetShadow:function(){var ctx=this.canvas.contextTop;ctx.shadowColor="";ctx.shadowBlur=ctx.shadowOffsetX=ctx.shadowOffsetY=0}});(function(){fabric.PencilBrush=fabric.util.createClass(fabric.BaseBrush,{initialize:function(canvas){this.canvas=canvas;this._points=[]},onMouseDown:function(pointer){this._prepareForDrawing(pointer);this._captureDrawingPath(pointer);this._render()},onMouseMove:function(pointer){this._captureDrawingPath(pointer);this.canvas.clearContext(this.canvas.contextTop);this._render()},onMouseUp:function(){this._finalizeAndAddPath()},_prepareForDrawing:function(pointer){var p=new fabric.Point(pointer.x,pointer.y);this._reset();this._addPoint(p);this.canvas.contextTop.moveTo(p.x,p.y)},_addPoint:function(point){this._points.push(point)},_reset:function(){this._points.length=0;this._setBrushStyles();this._setShadow()},_captureDrawingPath:function(pointer){var pointerPoint=new fabric.Point(pointer.x,pointer.y);this._addPoint(pointerPoint)},_render:function(){var ctx=this.canvas.contextTop,v=this.canvas.viewportTransform,p1=this._points[0],p2=this._points[1];ctx.save();ctx.transform(v[0],v[1],v[2],v[3],v[4],v[5]);ctx.beginPath();if(this._points.length===2&&p1.x===p2.x&&p1.y===p2.y){p1.x-=.5;p2.x+=.5}ctx.moveTo(p1.x,p1.y);for(var i=1,len=this._points.length;i<len;i++){var midPoint=p1.midPointFrom(p2);ctx.quadraticCurveTo(p1.x,p1.y,midPoint.x,midPoint.y);p1=this._points[i];p2=this._points[i+1]}ctx.lineTo(p1.x,p1.y);ctx.stroke();ctx.restore()},convertPointsToSVGPath:function(points){var path=[],p1=new fabric.Point(points[0].x,points[0].y),p2=new fabric.Point(points[1].x,points[1].y);path.push("M ",points[0].x," ",points[0].y," ");for(var i=1,len=points.length;i<len;i++){var midPoint=p1.midPointFrom(p2);path.push("Q ",p1.x," ",p1.y," ",midPoint.x," ",midPoint.y," ");p1=new fabric.Point(points[i].x,points[i].y);if(i+1<points.length){p2=new fabric.Point(points[i+1].x,points[i+1].y)}}path.push("L ",p1.x," ",p1.y," ");return path},createPath:function(pathData){var path=new fabric.Path(pathData,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray,originX:"center",originY:"center"});if(this.shadow){this.shadow.affectStroke=true;path.setShadow(this.shadow)}return path},_finalizeAndAddPath:function(){var ctx=this.canvas.contextTop;ctx.closePath();var pathData=this.convertPointsToSVGPath(this._points).join("");if(pathData==="M 0 0 Q 0 0 0 0 L 0 0"){this.canvas.renderAll();return}var path=this.createPath(pathData);this.canvas.add(path);path.setCoords();this.canvas.clearContext(this.canvas.contextTop);this._resetShadow();this.canvas.renderAll();this.canvas.fire("path:created",{path:path})}})})();fabric.CircleBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,initialize:function(canvas){this.canvas=canvas;this.points=[]},drawDot:function(pointer){var point=this.addPoint(pointer),ctx=this.canvas.contextTop,v=this.canvas.viewportTransform;ctx.save();ctx.transform(v[0],v[1],v[2],v[3],v[4],v[5]);ctx.fillStyle=point.fill;ctx.beginPath();ctx.arc(point.x,point.y,point.radius,0,Math.PI*2,false);ctx.closePath();ctx.fill();ctx.restore()},onMouseDown:function(pointer){this.points.length=0;this.canvas.clearContext(this.canvas.contextTop);this._setShadow();this.drawDot(pointer)},onMouseMove:function(pointer){this.drawDot(pointer)},onMouseUp:function(){var originalRenderOnAddRemove=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=false;var circles=[];for(var i=0,len=this.points.length;i<len;i++){var point=this.points[i],circle=new fabric.Circle({radius:point.radius,left:point.x,top:point.y,originX:"center",originY:"center",fill:point.fill});this.shadow&&circle.setShadow(this.shadow);circles.push(circle)}var group=new fabric.Group(circles,{originX:"center",originY:"center"});group.canvas=this.canvas;this.canvas.add(group);this.canvas.fire("path:created",{path:group});this.canvas.clearContext(this.canvas.contextTop);this._resetShadow();this.canvas.renderOnAddRemove=originalRenderOnAddRemove;this.canvas.renderAll()},addPoint:function(pointer){var pointerPoint=new fabric.Point(pointer.x,pointer.y),circleRadius=fabric.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,circleColor=new fabric.Color(this.color).setAlpha(fabric.util.getRandomInt(0,100)/100).toRgba();
pointerPoint.radius=circleRadius;pointerPoint.fill=circleColor;this.points.push(pointerPoint);return pointerPoint}});fabric.SprayBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:false,optimizeOverlapping:true,initialize:function(canvas){this.canvas=canvas;this.sprayChunks=[]},onMouseDown:function(pointer){this.sprayChunks.length=0;this.canvas.clearContext(this.canvas.contextTop);this._setShadow();this.addSprayChunk(pointer);this.render()},onMouseMove:function(pointer){this.addSprayChunk(pointer);this.render()},onMouseUp:function(){var originalRenderOnAddRemove=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=false;var rects=[];for(var i=0,ilen=this.sprayChunks.length;i<ilen;i++){var sprayChunk=this.sprayChunks[i];for(var j=0,jlen=sprayChunk.length;j<jlen;j++){var rect=new fabric.Rect({width:sprayChunk[j].width,height:sprayChunk[j].width,left:sprayChunk[j].x+1,top:sprayChunk[j].y+1,originX:"center",originY:"center",fill:this.color});this.shadow&&rect.setShadow(this.shadow);rects.push(rect)}}if(this.optimizeOverlapping){rects=this._getOptimizedRects(rects)}var group=new fabric.Group(rects,{originX:"center",originY:"center"});group.canvas=this.canvas;this.canvas.add(group);this.canvas.fire("path:created",{path:group});this.canvas.clearContext(this.canvas.contextTop);this._resetShadow();this.canvas.renderOnAddRemove=originalRenderOnAddRemove;this.canvas.renderAll()},_getOptimizedRects:function(rects){var uniqueRects={},key;for(var i=0,len=rects.length;i<len;i++){key=rects[i].left+""+rects[i].top;if(!uniqueRects[key]){uniqueRects[key]=rects[i]}}var uniqueRectsArray=[];for(key in uniqueRects){uniqueRectsArray.push(uniqueRects[key])}return uniqueRectsArray},render:function(){var ctx=this.canvas.contextTop;ctx.fillStyle=this.color;var v=this.canvas.viewportTransform;ctx.save();ctx.transform(v[0],v[1],v[2],v[3],v[4],v[5]);for(var i=0,len=this.sprayChunkPoints.length;i<len;i++){var point=this.sprayChunkPoints[i];if(typeof point.opacity!=="undefined"){ctx.globalAlpha=point.opacity}ctx.fillRect(point.x,point.y,point.width,point.width)}ctx.restore()},addSprayChunk:function(pointer){this.sprayChunkPoints=[];var x,y,width,radius=this.width/2;for(var i=0;i<this.density;i++){x=fabric.util.getRandomInt(pointer.x-radius,pointer.x+radius);y=fabric.util.getRandomInt(pointer.y-radius,pointer.y+radius);if(this.dotWidthVariance){width=fabric.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance)}else{width=this.dotWidth}var point=new fabric.Point(x,y);point.width=width;if(this.randomOpacity){point.opacity=fabric.util.getRandomInt(0,100)/100}this.sprayChunkPoints.push(point)}this.sprayChunks.push(this.sprayChunkPoints)}});fabric.PatternBrush=fabric.util.createClass(fabric.PencilBrush,{getPatternSrc:function(){var dotWidth=20,dotDistance=5,patternCanvas=fabric.document.createElement("canvas"),patternCtx=patternCanvas.getContext("2d");patternCanvas.width=patternCanvas.height=dotWidth+dotDistance;patternCtx.fillStyle=this.color;patternCtx.beginPath();patternCtx.arc(dotWidth/2,dotWidth/2,dotWidth/2,0,Math.PI*2,false);patternCtx.closePath();patternCtx.fill();return patternCanvas},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(){return this.canvas.contextTop.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(){this.callSuper("_setBrushStyles");this.canvas.contextTop.strokeStyle=this.getPattern()},createPath:function(pathData){var path=this.callSuper("createPath",pathData),topLeft=path._getLeftTopCoords().scalarAdd(path.strokeWidth/2);path.stroke=new fabric.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-topLeft.x,offsetY:-topLeft.y});return path}});(function(){var getPointer=fabric.util.getPointer,degreesToRadians=fabric.util.degreesToRadians,radiansToDegrees=fabric.util.radiansToDegrees,atan2=Math.atan2,abs=Math.abs,supportLineDash=fabric.StaticCanvas.supports("setLineDash"),STROKE_OFFSET=.5;fabric.Canvas=fabric.util.createClass(fabric.StaticCanvas,{initialize:function(el,options){options||(options={});this._initStatic(el,options);this._initInteractive();this._createCacheCanvas()},uniScaleTransform:false,uniScaleKey:"shiftKey",centeredScaling:false,centeredRotation:false,centeredKey:"altKey",altActionKey:"shiftKey",interactive:true,selection:true,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",rotationCursor:"crosshair",containerClass:"canvas-container",perPixelTargetFind:false,targetFindTolerance:0,skipTargetFind:false,isDrawingMode:false,preserveObjectStacking:false,snapAngle:0,snapThreshold:null,stopContextMenu:false,fireRightClick:false,fireMiddleClick:false,_initInteractive:function(){this._currentTransform=null;this._groupSelector=null;this._initWrapperElement();this._createUpperCanvas();this._initEventListeners();this._initRetinaScaling();this.freeDrawingBrush=fabric.PencilBrush&&new fabric.PencilBrush(this);this.calcOffset()},_chooseObjectsToRender:function(){var activeGroup=this.getActiveGroup(),activeObject=this.getActiveObject(),object,objsToRender=[],activeGroupObjects=[];if((activeGroup||activeObject)&&!this.preserveObjectStacking){for(var i=0,length=this._objects.length;i<length;i++){object=this._objects[i];if((!activeGroup||!activeGroup.contains(object))&&object!==activeObject){objsToRender.push(object)}else{activeGroupObjects.push(object)}}if(activeGroup){activeGroup._set("_objects",activeGroupObjects);objsToRender.push(activeGroup)}activeObject&&objsToRender.push(activeObject)}else{objsToRender=this._objects}return objsToRender},renderAll:function(){if(this.contextTopDirty&&!this._groupSelector&&!this.isDrawingMode){this.clearContext(this.contextTop);this.contextTopDirty=false}var canvasToDrawOn=this.contextContainer;this.renderCanvas(canvasToDrawOn,this._chooseObjectsToRender());return this},renderTop:function(){var ctx=this.contextTop;this.clearContext(ctx);if(this.selection&&this._groupSelector){this._drawSelection(ctx)}this.fire("after:render");this.contextTopDirty=true;return this},_resetCurrentTransform:function(){var t=this._currentTransform;t.target.set({scaleX:t.original.scaleX,scaleY:t.original.scaleY,skewX:t.original.skewX,skewY:t.original.skewY,left:t.original.left,top:t.original.top});if(this._shouldCenterTransform(t.target)){if(t.action==="rotate"){this._setOriginToCenter(t.target)}else{if(t.originX!=="center"){if(t.originX==="right"){t.mouseXSign=-1}else{t.mouseXSign=1}}if(t.originY!=="center"){if(t.originY==="bottom"){t.mouseYSign=-1}else{t.mouseYSign=1}}t.originX="center";t.originY="center"}}else{t.originX=t.original.originX;t.originY=t.original.originY}},containsPoint:function(e,target,point){var ignoreZoom=true,pointer=point||this.getPointer(e,ignoreZoom),xy;if(target.group&&target.group===this.getActiveGroup()){xy=this._normalizePointer(target.group,pointer)}else{xy={x:pointer.x,y:pointer.y}}return target.containsPoint(xy)||target._findTargetCorner(pointer)},_normalizePointer:function(object,pointer){var m=object.calcTransformMatrix(),invertedM=fabric.util.invertTransform(m),vptPointer=this.restorePointerVpt(pointer);return fabric.util.transformPoint(vptPointer,invertedM)},isTargetTransparent:function(target,x,y){var hasBorders=target.hasBorders,transparentCorners=target.transparentCorners,ctx=this.contextCache,originalColor=target.selectionBackgroundColor;target.hasBorders=target.transparentCorners=false;target.selectionBackgroundColor="";ctx.save();ctx.transform.apply(ctx,this.viewportTransform);target.render(ctx);ctx.restore();target.active&&target._renderControls(ctx);target.hasBorders=hasBorders;target.transparentCorners=transparentCorners;target.selectionBackgroundColor=originalColor;var isTransparent=fabric.util.isTransparent(ctx,x,y,this.targetFindTolerance);this.clearContext(ctx);return isTransparent},_shouldClearSelection:function(e,target){var activeGroup=this.getActiveGroup(),activeObject=this.getActiveObject();return!target||target&&activeGroup&&!activeGroup.contains(target)&&activeGroup!==target&&!e[this.selectionKey]||target&&!target.evented||target&&!target.selectable&&activeObject&&activeObject!==target},_shouldCenterTransform:function(target){if(!target){return}var t=this._currentTransform,centerTransform;if(t.action==="scale"||t.action==="scaleX"||t.action==="scaleY"){centerTransform=this.centeredScaling||target.centeredScaling}else if(t.action==="rotate"){centerTransform=this.centeredRotation||target.centeredRotation}return centerTransform?!t.altKey:t.altKey},_getOriginFromCorner:function(target,corner){var origin={x:target.originX,y:target.originY};if(corner==="ml"||corner==="tl"||corner==="bl"){origin.x="right"}else if(corner==="mr"||corner==="tr"||corner==="br"){origin.x="left"}if(corner==="tl"||corner==="mt"||corner==="tr"){origin.y="bottom"}else if(corner==="bl"||corner==="mb"||corner==="br"){origin.y="top"}return origin},_getActionFromCorner:function(target,corner,e){if(!corner){return"drag"}switch(corner){case"mtr":return"rotate";case"ml":case"mr":return e[this.altActionKey]?"skewY":"scaleX";case"mt":case"mb":return e[this.altActionKey]?"skewX":"scaleY";default:return"scale"}},_setupCurrentTransform:function(e,target){if(!target){return}var pointer=this.getPointer(e),corner=target._findTargetCorner(this.getPointer(e,true)),action=this._getActionFromCorner(target,corner,e),origin=this._getOriginFromCorner(target,corner);this._currentTransform={target:target,action:action,corner:corner,scaleX:target.scaleX,scaleY:target.scaleY,skewX:target.skewX,skewY:target.skewY,offsetX:pointer.x-target.left,offsetY:pointer.y-target.top,originX:origin.x,originY:origin.y,ex:pointer.x,ey:pointer.y,lastX:pointer.x,lastY:pointer.y,left:target.left,top:target.top,theta:degreesToRadians(target.angle),width:target.width*target.scaleX,mouseXSign:1,mouseYSign:1,shiftKey:e.shiftKey,altKey:e[this.centeredKey]};this._currentTransform.original={left:target.left,top:target.top,scaleX:target.scaleX,scaleY:target.scaleY,skewX:target.skewX,skewY:target.skewY,originX:origin.x,originY:origin.y};this._resetCurrentTransform()},_translateObject:function(x,y){var transform=this._currentTransform,target=transform.target,newLeft=x-transform.offsetX,newTop=y-transform.offsetY,moveX=!target.get("lockMovementX")&&target.left!==newLeft,moveY=!target.get("lockMovementY")&&target.top!==newTop;moveX&&target.set("left",newLeft);moveY&&target.set("top",newTop);return moveX||moveY},_changeSkewTransformOrigin:function(mouseMove,t,by){var property="originX",origins={0:"center"},skew=t.target.skewX,originA="left",originB="right",corner=t.corner==="mt"||t.corner==="ml"?1:-1,flipSign=1;mouseMove=mouseMove>0?1:-1;if(by==="y"){skew=t.target.skewY;originA="top";originB="bottom";property="originY"}origins[-1]=originA;origins[1]=originB;t.target.flipX&&(flipSign*=-1);t.target.flipY&&(flipSign*=-1);if(skew===0){t.skewSign=-corner*mouseMove*flipSign;t[property]=origins[-mouseMove]}else{skew=skew>0?1:-1;t.skewSign=skew;t[property]=origins[skew*corner*flipSign]}},_skewObject:function(x,y,by){var t=this._currentTransform,target=t.target,skewed=false,lockSkewingX=target.get("lockSkewingX"),lockSkewingY=target.get("lockSkewingY");if(lockSkewingX&&by==="x"||lockSkewingY&&by==="y"){return false}var center=target.getCenterPoint(),actualMouseByCenter=target.toLocalPoint(new fabric.Point(x,y),"center","center")[by],lastMouseByCenter=target.toLocalPoint(new fabric.Point(t.lastX,t.lastY),"center","center")[by],actualMouseByOrigin,constraintPosition,dim=target._getTransformedDimensions();this._changeSkewTransformOrigin(actualMouseByCenter-lastMouseByCenter,t,by);actualMouseByOrigin=target.toLocalPoint(new fabric.Point(x,y),t.originX,t.originY)[by];constraintPosition=target.translateToOriginPoint(center,t.originX,t.originY);skewed=this._setObjectSkew(actualMouseByOrigin,t,by,dim);t.lastX=x;t.lastY=y;target.setPositionByOrigin(constraintPosition,t.originX,t.originY);return skewed},_setObjectSkew:function(localMouse,transform,by,_dim){var target=transform.target,newValue,skewed=false,skewSign=transform.skewSign,newDim,dimNoSkew,otherBy,_otherBy,_by,newDimMouse,skewX,skewY;if(by==="x"){otherBy="y";_otherBy="Y";_by="X";skewX=0;skewY=target.skewY}else{otherBy="x";_otherBy="X";_by="Y";skewX=target.skewX;skewY=0}dimNoSkew=target._getTransformedDimensions(skewX,skewY);newDimMouse=2*Math.abs(localMouse)-dimNoSkew[by];if(newDimMouse<=2){newValue=0}else{newValue=skewSign*Math.atan(newDimMouse/target["scale"+_by]/(dimNoSkew[otherBy]/target["scale"+_otherBy]));newValue=fabric.util.radiansToDegrees(newValue)}skewed=target["skew"+_by]!==newValue;target.set("skew"+_by,newValue);if(target["skew"+_otherBy]!==0){newDim=target._getTransformedDimensions();newValue=_dim[otherBy]/newDim[otherBy]*target["scale"+_otherBy];target.set("scale"+_otherBy,newValue)}return skewed},_scaleObject:function(x,y,by){var t=this._currentTransform,target=t.target,lockScalingX=target.get("lockScalingX"),lockScalingY=target.get("lockScalingY"),lockScalingFlip=target.get("lockScalingFlip");if(lockScalingX&&lockScalingY){return false}var constraintPosition=target.translateToOriginPoint(target.getCenterPoint(),t.originX,t.originY),localMouse=target.toLocalPoint(new fabric.Point(x,y),t.originX,t.originY),dim=target._getTransformedDimensions(),scaled=false;this._setLocalMouse(localMouse,t);scaled=this._setObjectScale(localMouse,t,lockScalingX,lockScalingY,by,lockScalingFlip,dim);target.setPositionByOrigin(constraintPosition,t.originX,t.originY);return scaled},_setObjectScale:function(localMouse,transform,lockScalingX,lockScalingY,by,lockScalingFlip,_dim){var target=transform.target,forbidScalingX=false,forbidScalingY=false,scaled=false,changeX,changeY,scaleX,scaleY;scaleX=localMouse.x*target.scaleX/_dim.x;scaleY=localMouse.y*target.scaleY/_dim.y;changeX=target.scaleX!==scaleX;changeY=target.scaleY!==scaleY;if(lockScalingFlip&&scaleX<=0&&scaleX<target.scaleX){forbidScalingX=true}if(lockScalingFlip&&scaleY<=0&&scaleY<target.scaleY){forbidScalingY=true}if(by==="equally"&&!lockScalingX&&!lockScalingY){forbidScalingX||forbidScalingY||(scaled=this._scaleObjectEqually(localMouse,target,transform,_dim))}else if(!by){forbidScalingX||lockScalingX||target.set("scaleX",scaleX)&&(scaled=scaled||changeX);forbidScalingY||lockScalingY||target.set("scaleY",scaleY)&&(scaled=scaled||changeY)}else if(by==="x"&&!target.get("lockUniScaling")){forbidScalingX||lockScalingX||target.set("scaleX",scaleX)&&(scaled=scaled||changeX)}else if(by==="y"&&!target.get("lockUniScaling")){forbidScalingY||lockScalingY||target.set("scaleY",scaleY)&&(scaled=scaled||changeY)}transform.newScaleX=scaleX;transform.newScaleY=scaleY;forbidScalingX||forbidScalingY||this._flipObject(transform,by);return scaled},_scaleObjectEqually:function(localMouse,target,transform,_dim){var dist=localMouse.y+localMouse.x,lastDist=_dim.y*transform.original.scaleY/target.scaleY+_dim.x*transform.original.scaleX/target.scaleX,scaled;transform.newScaleX=transform.original.scaleX*dist/lastDist;transform.newScaleY=transform.original.scaleY*dist/lastDist;scaled=transform.newScaleX!==target.scaleX||transform.newScaleY!==target.scaleY;target.set("scaleX",transform.newScaleX);target.set("scaleY",transform.newScaleY);return scaled},_flipObject:function(transform,by){if(transform.newScaleX<0&&by!=="y"){if(transform.originX==="left"){transform.originX="right"}else if(transform.originX==="right"){transform.originX="left"}}if(transform.newScaleY<0&&by!=="x"){if(transform.originY==="top"){transform.originY="bottom"}else if(transform.originY==="bottom"){transform.originY="top"}}},_setLocalMouse:function(localMouse,t){var target=t.target,zoom=this.getZoom(),padding=target.padding/zoom;if(t.originX==="right"){localMouse.x*=-1}else if(t.originX==="center"){localMouse.x*=t.mouseXSign*2;if(localMouse.x<0){t.mouseXSign=-t.mouseXSign}}if(t.originY==="bottom"){localMouse.y*=-1}else if(t.originY==="center"){localMouse.y*=t.mouseYSign*2;if(localMouse.y<0){t.mouseYSign=-t.mouseYSign}}if(abs(localMouse.x)>padding){if(localMouse.x<0){localMouse.x+=padding}else{localMouse.x-=padding}}else{localMouse.x=0}if(abs(localMouse.y)>padding){if(localMouse.y<0){localMouse.y+=padding}else{localMouse.y-=padding}}else{localMouse.y=0}},_rotateObject:function(x,y){var t=this._currentTransform;if(t.target.get("lockRotation")){return false}var lastAngle=atan2(t.ey-t.top,t.ex-t.left),curAngle=atan2(y-t.top,x-t.left),angle=radiansToDegrees(curAngle-lastAngle+t.theta),hasRoated=true;if(t.target.snapAngle>0){var snapAngle=t.target.snapAngle,snapThreshold=t.target.snapThreshold||snapAngle,rightAngleLocked=Math.ceil(angle/snapAngle)*snapAngle,leftAngleLocked=Math.floor(angle/snapAngle)*snapAngle;if(Math.abs(angle-leftAngleLocked)<snapThreshold){angle=leftAngleLocked}else if(Math.abs(angle-rightAngleLocked)<snapThreshold){angle=rightAngleLocked}}if(angle<0){angle=360+angle}angle%=360;if(t.target.angle===angle){hasRoated=false}else{t.target.angle=angle}return hasRoated},setCursor:function(value){this.upperCanvasEl.style.cursor=value},_resetObjectTransform:function(target){target.scaleX=1;target.scaleY=1;target.skewX=0;target.skewY=0;target.setAngle(0)},_drawSelection:function(ctx){var groupSelector=this._groupSelector,left=groupSelector.left,top=groupSelector.top,aleft=abs(left),atop=abs(top);if(this.selectionColor){ctx.fillStyle=this.selectionColor;ctx.fillRect(groupSelector.ex-(left>0?0:-left),groupSelector.ey-(top>0?0:-top),aleft,atop)}if(!this.selectionLineWidth||!this.selectionBorderColor){return}ctx.lineWidth=this.selectionLineWidth;ctx.strokeStyle=this.selectionBorderColor;if(this.selectionDashArray.length>1&&!supportLineDash){var px=groupSelector.ex+STROKE_OFFSET-(left>0?0:aleft),py=groupSelector.ey+STROKE_OFFSET-(top>0?0:atop);ctx.beginPath();fabric.util.drawDashedLine(ctx,px,py,px+aleft,py,this.selectionDashArray);fabric.util.drawDashedLine(ctx,px,py+atop-1,px+aleft,py+atop-1,this.selectionDashArray);fabric.util.drawDashedLine(ctx,px,py,px,py+atop,this.selectionDashArray);fabric.util.drawDashedLine(ctx,px+aleft-1,py,px+aleft-1,py+atop,this.selectionDashArray);ctx.closePath();ctx.stroke()}else{fabric.Object.prototype._setLineDash.call(this,ctx,this.selectionDashArray);ctx.strokeRect(groupSelector.ex+STROKE_OFFSET-(left>0?0:aleft),groupSelector.ey+STROKE_OFFSET-(top>0?0:atop),aleft,atop)}},findTarget:function(e,skipGroup){if(this.skipTargetFind){return}var ignoreZoom=true,pointer=this.getPointer(e,ignoreZoom),activeGroup=this.getActiveGroup(),activeObject=this.getActiveObject(),activeTarget;if(activeGroup&&!skipGroup&&activeGroup===this._searchPossibleTargets([activeGroup],pointer)){this._fireOverOutEvents(activeGroup,e);return activeGroup}if(activeObject&&activeObject._findTargetCorner(pointer)){this._fireOverOutEvents(activeObject,e);return activeObject}if(activeObject&&activeObject===this._searchPossibleTargets([activeObject],pointer)){if(!this.preserveObjectStacking){this._fireOverOutEvents(activeObject,e);return activeObject}else{activeTarget=activeObject}}this.targets=[];var target=this._searchPossibleTargets(this._objects,pointer);if(e[this.altSelectionKey]&&target&&activeTarget&&target!==activeTarget){target=activeTarget}this._fireOverOutEvents(target,e);return target},_fireOverOutEvents:function(target,e){if(target){if(this._hoveredTarget!==target){if(this._hoveredTarget){this.fire("mouse:out",{target:this._hoveredTarget,e:e});this._hoveredTarget.fire("mouseout",{e:e})}this.fire("mouse:over",{target:target,e:e});target.fire("mouseover",{e:e});this._hoveredTarget=target}}else if(this._hoveredTarget){this.fire("mouse:out",{target:this._hoveredTarget,e:e});this._hoveredTarget.fire("mouseout",{e:e});this._hoveredTarget=null}},_checkTarget:function(pointer,obj){if(obj&&obj.visible&&obj.evented&&this.containsPoint(null,obj,pointer)){if((this.perPixelTargetFind||obj.perPixelTargetFind)&&!obj.isEditing){var isTransparent=this.isTargetTransparent(obj,pointer.x,pointer.y);if(!isTransparent){return true}}else{return true}}},_searchPossibleTargets:function(objects,pointer){var target,i=objects.length,normalizedPointer,subTarget;while(i--){if(this._checkTarget(pointer,objects[i])){target=objects[i];if(target.type==="group"&&target.subTargetCheck){normalizedPointer=this._normalizePointer(target,pointer);subTarget=this._searchPossibleTargets(target._objects,normalizedPointer);subTarget&&this.targets.push(subTarget)}break}}return target},restorePointerVpt:function(pointer){return fabric.util.transformPoint(pointer,fabric.util.invertTransform(this.viewportTransform))},getPointer:function(e,ignoreZoom,upperCanvasEl){if(!upperCanvasEl){upperCanvasEl=this.upperCanvasEl}var pointer=getPointer(e),bounds=upperCanvasEl.getBoundingClientRect(),boundsWidth=bounds.width||0,boundsHeight=bounds.height||0,cssScale;if(!boundsWidth||!boundsHeight){if("top"in bounds&&"bottom"in bounds){boundsHeight=Math.abs(bounds.top-bounds.bottom)}if("right"in bounds&&"left"in bounds){boundsWidth=Math.abs(bounds.right-bounds.left)}}this.calcOffset();pointer.x=pointer.x-this._offset.left;pointer.y=pointer.y-this._offset.top;if(!ignoreZoom){pointer=this.restorePointerVpt(pointer)}if(boundsWidth===0||boundsHeight===0){cssScale={width:1,height:1}}else{cssScale={width:upperCanvasEl.width/boundsWidth,height:upperCanvasEl.height/boundsHeight}}return{x:pointer.x*cssScale.width,y:pointer.y*cssScale.height}},_createUpperCanvas:function(){var lowerCanvasClass=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,"");this.upperCanvasEl=this._createCanvasElement();fabric.util.addClass(this.upperCanvasEl,"upper-canvas "+lowerCanvasClass);this.wrapperEl.appendChild(this.upperCanvasEl);this._copyCanvasStyle(this.lowerCanvasEl,this.upperCanvasEl);this._applyCanvasStyle(this.upperCanvasEl);this.contextTop=this.upperCanvasEl.getContext("2d")},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement();this.cacheCanvasEl.setAttribute("width",this.width);this.cacheCanvasEl.setAttribute("height",this.height);this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=fabric.util.wrapElement(this.lowerCanvasEl,"div",{"class":this.containerClass});fabric.util.setStyle(this.wrapperEl,{width:this.getWidth()+"px",height:this.getHeight()+"px",position:"relative"});fabric.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(element){var width=this.getWidth()||element.width,height=this.getHeight()||element.height;fabric.util.setStyle(element,{position:"absolute",width:width+"px",height:height+"px",left:0,top:0,"touch-action":"none"});element.width=width;element.height=height;fabric.util.makeElementUnselectable(element)},_copyCanvasStyle:function(fromEl,toEl){toEl.style.cssText=fromEl.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},_setActiveObject:function(object){var obj=this._activeObject;if(obj){obj.set("active",false);if(object!==obj&&obj.onDeselect&&typeof obj.onDeselect==="function"){obj.onDeselect()}}this._activeObject=object;object.set("active",true)},setActiveObject:function(object,e){var currentActiveObject=this.getActiveObject();if(currentActiveObject&&currentActiveObject!==object){currentActiveObject.fire("deselected",{e:e})}this._setActiveObject(object);this.renderAll();this.fire("object:selected",{target:object,e:e});object.fire("selected",{e:e});return this},getActiveObject:function(){return this._activeObject},_onObjectRemoved:function(obj){if(this.getActiveObject()===obj){this.fire("before:selection:cleared",{target:obj});this._discardActiveObject();this.fire("selection:cleared",{target:obj});obj.fire("deselected")}if(this._hoveredTarget===obj){this._hoveredTarget=null}this.callSuper("_onObjectRemoved",obj)},_discardActiveObject:function(){var obj=this._activeObject;if(obj){obj.set("active",false);if(obj.onDeselect&&typeof obj.onDeselect==="function"){obj.onDeselect()}}this._activeObject=null},discardActiveObject:function(e){var activeObject=this._activeObject;if(activeObject){this.fire("before:selection:cleared",{target:activeObject,e:e});this._discardActiveObject();this.fire("selection:cleared",{e:e});activeObject.fire("deselected",{e:e})}return this},_setActiveGroup:function(group){this._activeGroup=group;if(group){group.set("active",true)}},setActiveGroup:function(group,e){this._setActiveGroup(group);if(group){this.fire("object:selected",{target:group,e:e});group.fire("selected",{e:e})}return this},getActiveGroup:function(){return this._activeGroup},_discardActiveGroup:function(){var g=this.getActiveGroup();if(g){g.destroy()}this.setActiveGroup(null)},discardActiveGroup:function(e){var g=this.getActiveGroup();if(g){this.fire("before:selection:cleared",{e:e,target:g});this._discardActiveGroup();this.fire("selection:cleared",{e:e})}return this},deactivateAll:function(){var allObjects=this.getObjects(),i=0,len=allObjects.length,obj;for(;i<len;i++){obj=allObjects[i];obj&&obj.set("active",false)}this._discardActiveGroup();this._discardActiveObject();return this},deactivateAllWithDispatch:function(e){this.discardActiveGroup(e);this.discardActiveObject(e);this.deactivateAll();return this},dispose:function(){this.callSuper("dispose");var wrapper=this.wrapperEl;this.removeListeners();wrapper.removeChild(this.upperCanvasEl);wrapper.removeChild(this.lowerCanvasEl);delete this.upperCanvasEl;if(wrapper.parentNode){wrapper.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl)}delete this.wrapperEl;return this},clear:function(){this.discardActiveGroup();this.discardActiveObject();this.clearContext(this.contextTop);return this.callSuper("clear")},drawControls:function(ctx){var activeGroup=this.getActiveGroup();if(activeGroup){activeGroup._renderControls(ctx)}else{this._drawObjectsControls(ctx)}},_drawObjectsControls:function(ctx){for(var i=0,len=this._objects.length;i<len;++i){if(!this._objects[i]||!this._objects[i].active){continue}this._objects[i]._renderControls(ctx)}},_toObject:function(instance,methodName,propertiesToInclude){var originalProperties=this._realizeGroupTransformOnObject(instance),object=this.callSuper("_toObject",instance,methodName,propertiesToInclude);this._unwindGroupTransformOnObject(instance,originalProperties);return object},_realizeGroupTransformOnObject:function(instance){var layoutProps=["angle","flipX","flipY","height","left","scaleX","scaleY","top","width"];if(instance.group&&instance.group===this.getActiveGroup()){var originalValues={};layoutProps.forEach(function(prop){originalValues[prop]=instance[prop]});this.getActiveGroup().realizeTransform(instance);return originalValues}else{return null}},_unwindGroupTransformOnObject:function(instance,originalValues){if(originalValues){instance.set(originalValues)}},_setSVGObject:function(markup,instance,reviver){var originalProperties;originalProperties=this._realizeGroupTransformOnObject(instance);this.callSuper("_setSVGObject",markup,instance,reviver);this._unwindGroupTransformOnObject(instance,originalProperties)}});for(var prop in fabric.StaticCanvas){if(prop!=="prototype"){fabric.Canvas[prop]=fabric.StaticCanvas[prop]}}if(fabric.isTouchSupported){fabric.Canvas.prototype._setCursorFromEvent=function(){}}fabric.Element=fabric.Canvas})();(function(){var cursorOffset={mt:0,tr:1,mr:2,br:3,mb:4,bl:5,ml:6,tl:7},addListener=fabric.util.addListener,removeListener=fabric.util.removeListener;fabric.util.object.extend(fabric.Canvas.prototype,{cursorMap:["n-resize","ne-resize","e-resize","se-resize","s-resize","sw-resize","w-resize","nw-resize"],_initEventListeners:function(){this._bindEvents();addListener(fabric.window,"resize",this._onResize);addListener(this.upperCanvasEl,"mousedown",this._onMouseDown);addListener(this.upperCanvasEl,"mousemove",this._onMouseMove);addListener(this.upperCanvasEl,"mouseout",this._onMouseOut);addListener(this.upperCanvasEl,"mouseenter",this._onMouseEnter);addListener(this.upperCanvasEl,"wheel",this._onMouseWheel);addListener(this.upperCanvasEl,"contextmenu",this._onContextMenu);addListener(this.upperCanvasEl,"touchstart",this._onMouseDown,{passive:false});addListener(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:false});if(typeof eventjs!=="undefined"&&"add"in eventjs){eventjs.add(this.upperCanvasEl,"gesture",this._onGesture);eventjs.add(this.upperCanvasEl,"drag",this._onDrag);eventjs.add(this.upperCanvasEl,"orientation",this._onOrientationChange);eventjs.add(this.upperCanvasEl,"shake",this._onShake);eventjs.add(this.upperCanvasEl,"longpress",this._onLongPress)}},_bindEvents:function(){this._onMouseDown=this._onMouseDown.bind(this);this._onMouseMove=this._onMouseMove.bind(this);this._onMouseUp=this._onMouseUp.bind(this);this._onResize=this._onResize.bind(this);this._onGesture=this._onGesture.bind(this);this._onDrag=this._onDrag.bind(this);this._onShake=this._onShake.bind(this);this._onLongPress=this._onLongPress.bind(this);this._onOrientationChange=this._onOrientationChange.bind(this);this._onMouseWheel=this._onMouseWheel.bind(this);this._onMouseOut=this._onMouseOut.bind(this);this._onMouseEnter=this._onMouseEnter.bind(this);this._onContextMenu=this._onContextMenu.bind(this)},removeListeners:function(){removeListener(fabric.window,"resize",this._onResize);removeListener(this.upperCanvasEl,"mousedown",this._onMouseDown);removeListener(this.upperCanvasEl,"mousemove",this._onMouseMove);removeListener(this.upperCanvasEl,"mouseout",this._onMouseOut);removeListener(this.upperCanvasEl,"mouseenter",this._onMouseEnter);removeListener(this.upperCanvasEl,"wheel",this._onMouseWheel);removeListener(this.upperCanvasEl,"contextmenu",this._onContextMenu);removeListener(this.upperCanvasEl,"touchstart",this._onMouseDown);removeListener(this.upperCanvasEl,"touchmove",this._onMouseMove);if(typeof eventjs!=="undefined"&&"remove"in eventjs){eventjs.remove(this.upperCanvasEl,"gesture",this._onGesture);eventjs.remove(this.upperCanvasEl,"drag",this._onDrag);eventjs.remove(this.upperCanvasEl,"orientation",this._onOrientationChange);eventjs.remove(this.upperCanvasEl,"shake",this._onShake);eventjs.remove(this.upperCanvasEl,"longpress",this._onLongPress)}},_onGesture:function(e,self){this.__onTransformGesture&&this.__onTransformGesture(e,self)},_onDrag:function(e,self){this.__onDrag&&this.__onDrag(e,self)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var target=this._hoveredTarget;this.fire("mouse:out",{target:target,e:e});this._hoveredTarget=null;target&&target.fire("mouseout",{e:e});if(this._iTextInstances){this._iTextInstances.forEach(function(obj){if(obj.isEditing){obj.hiddenTextarea.focus()}})}},_onMouseEnter:function(e){if(!this.findTarget(e)){this.fire("mouse:over",{target:null,e:e});this._hoveredTarget=null}},_onOrientationChange:function(e,self){this.__onOrientationChange&&this.__onOrientationChange(e,self)},_onShake:function(e,self){this.__onShake&&this.__onShake(e,self)},_onLongPress:function(e,self){this.__onLongPress&&this.__onLongPress(e,self)},_onContextMenu:function(e){if(this.stopContextMenu){e.stopPropagation();e.preventDefault()}return false},_onMouseDown:function(e){this.__onMouseDown(e);addListener(fabric.document,"touchend",this._onMouseUp,{passive:false});addListener(fabric.document,"touchmove",this._onMouseMove,{passive:false});removeListener(this.upperCanvasEl,"mousemove",this._onMouseMove);removeListener(this.upperCanvasEl,"touchmove",this._onMouseMove);if(e.type==="touchstart"){removeListener(this.upperCanvasEl,"mousedown",this._onMouseDown)}else{addListener(fabric.document,"mouseup",this._onMouseUp);addListener(fabric.document,"mousemove",this._onMouseMove)}},_onMouseUp:function(e){this.__onMouseUp(e);removeListener(fabric.document,"mouseup",this._onMouseUp);removeListener(fabric.document,"touchend",this._onMouseUp);
removeListener(fabric.document,"mousemove",this._onMouseMove);removeListener(fabric.document,"touchmove",this._onMouseMove);addListener(this.upperCanvasEl,"mousemove",this._onMouseMove);addListener(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:false});if(e.type==="touchend"){var _this=this;setTimeout(function(){addListener(_this.upperCanvasEl,"mousedown",_this._onMouseDown)},400)}},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault();this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(target,pointer){var activeObject=this.getActiveGroup()||this.getActiveObject();if(activeObject&&activeObject.isEditing&&target===activeObject){return false}return!!(target&&(target.isMoving||target!==activeObject)||!target&&!!activeObject||!target&&!activeObject&&!this._groupSelector||pointer&&this._previousPointer&&this.selection&&(pointer.x!==this._previousPointer.x||pointer.y!==this._previousPointer.y))},__onMouseUp:function(e){var target,searchTarget=true,transform=this._currentTransform,groupSelector=this._groupSelector,isClick=!groupSelector||groupSelector.left===0&&groupSelector.top===0;if(this.isDrawingMode&&this._isCurrentlyDrawing){this._onMouseUpInDrawingMode(e);return}if(transform){this._finalizeCurrentTransform();searchTarget=!transform.actionPerformed}target=searchTarget?this.findTarget(e,true):transform.target;var shouldRender=this._shouldRender(target,this.getPointer(e));if(target||!isClick){this._maybeGroupObjects(e)}else{this._groupSelector=null;this._currentTransform=null}if(target){target.isMoving=false}this._handleCursorAndEvent(e,target,"up");target&&(target.__corner=0);shouldRender&&this.renderAll()},_handleCursorAndEvent:function(e,target,eventType){this._setCursorFromEvent(e,target);this._handleEvent(e,eventType,target?target:null)},_handleEvent:function(e,eventType,targetObj){var target=typeof targetObj==="undefined"?this.findTarget(e):targetObj,targets=this.targets||[],options={e:e,target:target,subTargets:targets};this.fire("mouse:"+eventType,options);target&&target.fire("mouse"+eventType,options);for(var i=0;i<targets.length;i++){targets[i].fire("mouse"+eventType,options)}},_finalizeCurrentTransform:function(){var transform=this._currentTransform,target=transform.target;if(target._scaling){target._scaling=false}target.setCoords();this._restoreOriginXY(target);if(transform.actionPerformed||this.stateful&&target.hasStateChanged()){this.fire("object:modified",{target:target});target.fire("modified")}},_restoreOriginXY:function(target){if(this._previousOriginX&&this._previousOriginY){var originPoint=target.translateToOriginPoint(target.getCenterPoint(),this._previousOriginX,this._previousOriginY);target.originX=this._previousOriginX;target.originY=this._previousOriginY;target.left=originPoint.x;target.top=originPoint.y;this._previousOriginX=null;this._previousOriginY=null}},_onMouseDownInDrawingMode:function(e){this._isCurrentlyDrawing=true;this.discardActiveObject(e).renderAll();if(this.clipTo){fabric.util.clipContext(this,this.contextTop)}var pointer=this.getPointer(e);this.freeDrawingBrush.onMouseDown(pointer);this._handleEvent(e,"down")},_onMouseMoveInDrawingMode:function(e){if(this._isCurrentlyDrawing){var pointer=this.getPointer(e);this.freeDrawingBrush.onMouseMove(pointer)}this.setCursor(this.freeDrawingCursor);this._handleEvent(e,"move")},_onMouseUpInDrawingMode:function(e){this._isCurrentlyDrawing=false;if(this.clipTo){this.contextTop.restore()}this.freeDrawingBrush.onMouseUp();this._handleEvent(e,"up")},__onMouseDown:function(e){var target=this.findTarget(e);var isRightClick="which"in e?e.which===3:e.button===2;if(isRightClick){if(this.fireRightClick){this._handleEvent(e,"down",target?target:null)}return}var isMiddleClick="which"in e?e.which===2:e.button===1;if(isMiddleClick){if(this.fireMiddleClick){this._handleEvent(e,"down",target?target:null)}return}if(this.isDrawingMode){this._onMouseDownInDrawingMode(e);return}if(this._currentTransform){return}var pointer=this.getPointer(e,true);this._previousPointer=pointer;var shouldRender=this._shouldRender(target,pointer),shouldGroup=this._shouldGroup(e,target);if(this._shouldClearSelection(e,target)){this._clearSelection(e,target,pointer)}else if(shouldGroup){this._handleGrouping(e,target);target=this.getActiveGroup()}if(target){if(target.selectable&&(target.__corner||!shouldGroup)){this._beforeTransform(e,target);this._setupCurrentTransform(e,target)}var activeObject=this.getActiveObject();if(target!==this.getActiveGroup()&&target!==activeObject){this.deactivateAll();if(target.selectable){activeObject&&activeObject.fire("deselected",{e:e});this.setActiveObject(target,e)}}}this._handleEvent(e,"down",target?target:null);shouldRender&&this.renderAll()},_beforeTransform:function(e,target){this.stateful&&target.saveState();if(target._findTargetCorner(this.getPointer(e))){this.onBeforeScaleRotate(target)}},_clearSelection:function(e,target,pointer){this.deactivateAllWithDispatch(e);if(target&&target.selectable){this.setActiveObject(target,e)}else if(this.selection){this._groupSelector={ex:pointer.x,ey:pointer.y,top:0,left:0}}},_setOriginToCenter:function(target){this._previousOriginX=this._currentTransform.target.originX;this._previousOriginY=this._currentTransform.target.originY;var center=target.getCenterPoint();target.originX="center";target.originY="center";target.left=center.x;target.top=center.y;this._currentTransform.left=target.left;this._currentTransform.top=target.top},_setCenterToOrigin:function(target){var originPoint=target.translateToOriginPoint(target.getCenterPoint(),this._previousOriginX,this._previousOriginY);target.originX=this._previousOriginX;target.originY=this._previousOriginY;target.left=originPoint.x;target.top=originPoint.y;this._previousOriginX=null;this._previousOriginY=null},__onMouseMove:function(e){var target,pointer;if(this.isDrawingMode){this._onMouseMoveInDrawingMode(e);return}if(typeof e.touches!=="undefined"&&e.touches.length>1){return}var groupSelector=this._groupSelector;if(groupSelector){pointer=this.getPointer(e,true);groupSelector.left=pointer.x-groupSelector.ex;groupSelector.top=pointer.y-groupSelector.ey;this.renderTop()}else if(!this._currentTransform){target=this.findTarget(e);this._setCursorFromEvent(e,target)}else{this._transformObject(e)}this._handleEvent(e,"move",target?target:null)},__onMouseWheel:function(e){this._handleEvent(e,"wheel")},_transformObject:function(e){var pointer=this.getPointer(e),transform=this._currentTransform;transform.reset=false;transform.target.isMoving=true;transform.shiftKey=e.shiftKey;transform.altKey=e[this.centeredKey];this._beforeScaleTransform(e,transform);this._performTransformAction(e,transform,pointer);transform.actionPerformed&&this.renderAll()},_performTransformAction:function(e,transform,pointer){var x=pointer.x,y=pointer.y,target=transform.target,action=transform.action,actionPerformed=false;if(action==="rotate"){(actionPerformed=this._rotateObject(x,y))&&this._fire("rotating",target,e)}else if(action==="scale"){(actionPerformed=this._onScale(e,transform,x,y))&&this._fire("scaling",target,e)}else if(action==="scaleX"){(actionPerformed=this._scaleObject(x,y,"x"))&&this._fire("scaling",target,e)}else if(action==="scaleY"){(actionPerformed=this._scaleObject(x,y,"y"))&&this._fire("scaling",target,e)}else if(action==="skewX"){(actionPerformed=this._skewObject(x,y,"x"))&&this._fire("skewing",target,e)}else if(action==="skewY"){(actionPerformed=this._skewObject(x,y,"y"))&&this._fire("skewing",target,e)}else{actionPerformed=this._translateObject(x,y);if(actionPerformed){this._fire("moving",target,e);this.setCursor(target.moveCursor||this.moveCursor)}}transform.actionPerformed=transform.actionPerformed||actionPerformed},_fire:function(eventName,target,e){this.fire("object:"+eventName,{target:target,e:e});target.fire(eventName,{e:e})},_beforeScaleTransform:function(e,transform){if(transform.action==="scale"||transform.action==="scaleX"||transform.action==="scaleY"){var centerTransform=this._shouldCenterTransform(transform.target);if(centerTransform&&(transform.originX!=="center"||transform.originY!=="center")||!centerTransform&&transform.originX==="center"&&transform.originY==="center"){this._resetCurrentTransform();transform.reset=true}}},_onScale:function(e,transform,x,y){if((e[this.uniScaleKey]||this.uniScaleTransform)&&!transform.target.get("lockUniScaling")){transform.currentAction="scale";return this._scaleObject(x,y)}else{if(!transform.reset&&transform.currentAction==="scale"){this._resetCurrentTransform()}transform.currentAction="scaleEqually";return this._scaleObject(x,y,"equally")}},_setCursorFromEvent:function(e,target){if(!target||!target.selectable){this.setCursor(this.defaultCursor);return false}var hoverCursor=target.hoverCursor||this.hoverCursor,activeGroup=this.getActiveGroup(),corner=target._findTargetCorner&&(!activeGroup||!activeGroup.contains(target))&&target._findTargetCorner(this.getPointer(e,true));if(!corner){this.setCursor(hoverCursor)}else{this._setCornerCursor(corner,target,e)}return true},_setCornerCursor:function(corner,target,e){if(corner in cursorOffset){this.setCursor(this._getRotatedCornerCursor(corner,target,e))}else if(corner==="mtr"&&target.hasRotatingPoint){this.setCursor(this.rotationCursor)}else{this.setCursor(this.defaultCursor);return false}},_getRotatedCornerCursor:function(corner,target,e){var n=Math.round(target.getAngle()%360/45);if(n<0){n+=8}n+=cursorOffset[corner];if(e[this.altActionKey]&&cursorOffset[corner]%2===0){n+=2}n%=8;return this.cursorMap[n]}})})();(function(){var min=Math.min,max=Math.max;fabric.util.object.extend(fabric.Canvas.prototype,{_shouldGroup:function(e,target){var activeObject=this.getActiveObject();return e[this.selectionKey]&&target&&target.selectable&&(this.getActiveGroup()||activeObject&&activeObject!==target)&&this.selection},_handleGrouping:function(e,target){var activeGroup=this.getActiveGroup();if(target===activeGroup){target=this.findTarget(e,true);if(!target){return}}if(activeGroup){this._updateActiveGroup(target,e)}else{this._createActiveGroup(target,e)}if(this._activeGroup){this._activeGroup.saveCoords()}},_updateActiveGroup:function(target,e){var activeGroup=this.getActiveGroup();if(activeGroup.contains(target)){activeGroup.removeWithUpdate(target);target.set("active",false);if(activeGroup.size()===1){this.discardActiveGroup(e);this.setActiveObject(activeGroup.item(0),e);return}}else{activeGroup.addWithUpdate(target)}this.fire("selection:created",{target:activeGroup,e:e});activeGroup.set("active",true)},_createActiveGroup:function(target,e){if(this._activeObject&&target!==this._activeObject){var group=this._createGroup(target);group.addWithUpdate();this.setActiveGroup(group,e);this._activeObject=null;this.fire("selection:created",{target:group,e:e})}target.set("active",true)},_createGroup:function(target){var objects=this.getObjects(),isActiveLower=objects.indexOf(this._activeObject)<objects.indexOf(target),groupObjects=isActiveLower?[this._activeObject,target]:[target,this._activeObject];this._activeObject.isEditing&&this._activeObject.exitEditing();return new fabric.Group(groupObjects,{canvas:this})},_groupSelectedObjects:function(e){var group=this._collectObjects();if(group.length===1){this.setActiveObject(group[0],e)}else if(group.length>1){group=new fabric.Group(group.reverse(),{canvas:this});group.addWithUpdate();this.setActiveGroup(group,e);group.saveCoords();this.fire("selection:created",{target:group,e:e});this.renderAll()}},_collectObjects:function(){var group=[],currentObject,x1=this._groupSelector.ex,y1=this._groupSelector.ey,x2=x1+this._groupSelector.left,y2=y1+this._groupSelector.top,selectionX1Y1=new fabric.Point(min(x1,x2),min(y1,y2)),selectionX2Y2=new fabric.Point(max(x1,x2),max(y1,y2)),isClick=x1===x2&&y1===y2;for(var i=this._objects.length;i--;){currentObject=this._objects[i];if(!currentObject||!currentObject.selectable||!currentObject.visible){continue}if(currentObject.intersectsWithRect(selectionX1Y1,selectionX2Y2)||currentObject.isContainedWithinRect(selectionX1Y1,selectionX2Y2)||currentObject.containsPoint(selectionX1Y1)||currentObject.containsPoint(selectionX2Y2)){currentObject.set("active",true);group.push(currentObject);if(isClick){break}}}return group},_maybeGroupObjects:function(e){if(this.selection&&this._groupSelector){this._groupSelectedObjects(e)}var activeGroup=this.getActiveGroup();if(activeGroup){activeGroup.setObjectsCoords().setCoords();activeGroup.isMoving=false;this.setCursor(this.defaultCursor)}this._groupSelector=null;this._currentTransform=null}})})();(function(){var supportQuality=fabric.StaticCanvas.supports("toDataURLWithQuality");fabric.util.object.extend(fabric.StaticCanvas.prototype,{toDataURL:function(options){options||(options={});var format=options.format||"png",quality=options.quality||1,multiplier=options.multiplier||1,cropping={left:options.left||0,top:options.top||0,width:options.width||0,height:options.height||0};return this.__toDataURLWithMultiplier(format,quality,cropping,multiplier)},__toDataURLWithMultiplier:function(format,quality,cropping,multiplier){var origWidth=this.getWidth(),origHeight=this.getHeight(),scaledWidth=(cropping.width||this.getWidth())*multiplier,scaledHeight=(cropping.height||this.getHeight())*multiplier,zoom=this.getZoom(),newZoom=zoom*multiplier,vp=this.viewportTransform,translateX=(vp[4]-cropping.left)*multiplier,translateY=(vp[5]-cropping.top)*multiplier,newVp=[newZoom,0,0,newZoom,translateX,translateY],originalInteractive=this.interactive;this.viewportTransform=newVp;this.interactive&&(this.interactive=false);if(origWidth!==scaledWidth||origHeight!==scaledHeight){this.setDimensions({width:scaledWidth,height:scaledHeight})}else{this.renderAll()}var data=this.__toDataURL(format,quality,cropping);originalInteractive&&(this.interactive=originalInteractive);this.viewportTransform=vp;this.setDimensions({width:origWidth,height:origHeight});return data},__toDataURL:function(format,quality){var canvasEl=this.contextContainer.canvas;if(format==="jpg"){format="jpeg"}var data=supportQuality?canvasEl.toDataURL("image/"+format,quality):canvasEl.toDataURL("image/"+format);return data},toDataURLWithMultiplier:function(format,multiplier,quality){return this.toDataURL({format:format,multiplier:multiplier,quality:quality})}})})();fabric.util.object.extend(fabric.StaticCanvas.prototype,{loadFromDatalessJSON:function(json,callback,reviver){return this.loadFromJSON(json,callback,reviver)},loadFromJSON:function(json,callback,reviver){if(!json){return}var serialized=typeof json==="string"?JSON.parse(json):fabric.util.object.clone(json);this.clear();var _this=this;this._enlivenObjects(serialized.objects,function(){_this._setBgOverlay(serialized,function(){delete serialized.objects;delete serialized.backgroundImage;delete serialized.overlayImage;delete serialized.background;delete serialized.overlay;_this._setOptions(serialized);callback&&callback()})},reviver);return this},_setBgOverlay:function(serialized,callback){var _this=this,loaded={backgroundColor:false,overlayColor:false,backgroundImage:false,overlayImage:false};if(!serialized.backgroundImage&&!serialized.overlayImage&&!serialized.background&&!serialized.overlay){callback&&callback();return}var cbIfLoaded=function(){if(loaded.backgroundImage&&loaded.overlayImage&&loaded.backgroundColor&&loaded.overlayColor){_this.renderAll();callback&&callback()}};this.__setBgOverlay("backgroundImage",serialized.backgroundImage,loaded,cbIfLoaded);this.__setBgOverlay("overlayImage",serialized.overlayImage,loaded,cbIfLoaded);this.__setBgOverlay("backgroundColor",serialized.background,loaded,cbIfLoaded);this.__setBgOverlay("overlayColor",serialized.overlay,loaded,cbIfLoaded)},__setBgOverlay:function(property,value,loaded,callback){var _this=this;if(!value){loaded[property]=true;callback&&callback();return}if(property==="backgroundImage"||property==="overlayImage"){fabric.util.enlivenObjects([value],function(enlivedObject){_this[property]=enlivedObject[0];loaded[property]=true;callback&&callback()})}else{this["set"+fabric.util.string.capitalize(property,true)](value,function(){loaded[property]=true;callback&&callback()})}},_enlivenObjects:function(objects,callback,reviver){var _this=this;if(!objects||objects.length===0){callback&&callback();return}var renderOnAddRemove=this.renderOnAddRemove;this.renderOnAddRemove=false;fabric.util.enlivenObjects(objects,function(enlivenedObjects){enlivenedObjects.forEach(function(obj,index){_this.insertAt(obj,index)});_this.renderOnAddRemove=renderOnAddRemove;callback&&callback()},null,reviver)},_toDataURL:function(format,callback){this.clone(function(clone){callback(clone.toDataURL(format))})},_toDataURLWithMultiplier:function(format,multiplier,callback){this.clone(function(clone){callback(clone.toDataURLWithMultiplier(format,multiplier))})},clone:function(callback,properties){var data=JSON.stringify(this.toJSON(properties));this.cloneWithoutData(function(clone){clone.loadFromJSON(data,function(){callback&&callback(clone)})})},cloneWithoutData:function(callback){var el=fabric.document.createElement("canvas");el.width=this.getWidth();el.height=this.getHeight();var clone=new fabric.Canvas(el);clone.clipTo=this.clipTo;if(this.backgroundImage){clone.setBackgroundImage(this.backgroundImage.src,function(){clone.renderAll();callback&&callback(clone)});clone.backgroundImageOpacity=this.backgroundImageOpacity;clone.backgroundImageStretch=this.backgroundImageStretch}else{callback&&callback(clone)}}});(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,clone=fabric.util.object.clone,toFixed=fabric.util.toFixed,capitalize=fabric.util.string.capitalize,degreesToRadians=fabric.util.degreesToRadians,supportsLineDash=fabric.StaticCanvas.supports("setLineDash"),objectCaching=!fabric.isLikelyNode;if(fabric.Object){return}fabric.Object=fabric.util.createClass(fabric.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:false,flipY:false,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,transparentCorners:true,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgba(102,153,255,0.75)",borderDashArray:null,cornerColor:"rgba(102,153,255,0.5)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:false,centeredRotation:true,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:10,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,transformMatrix:null,minScaleLimit:.01,selectable:true,evented:true,visible:true,hasControls:true,hasBorders:true,hasRotatingPoint:true,rotatingPointOffset:40,perPixelTargetFind:false,includeDefaultValues:true,clipTo:null,lockMovementX:false,lockMovementY:false,lockRotation:false,lockScalingX:false,lockScalingY:false,lockUniScaling:false,lockSkewingX:false,lockSkewingY:false,lockScalingFlip:false,excludeFromExport:false,objectCaching:objectCaching,statefullCache:false,noScaleCache:true,dirty:true,needsItsOwnCache:false,stateProperties:("top left width height scaleX scaleY flipX flipY originX originY transformMatrix "+"stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit "+"angle opacity fill fillRule globalCompositeOperation shadow clipTo visible backgroundColor "+"skewX skewY").split(" "),cacheProperties:("fill stroke strokeWidth strokeDashArray width height stroke strokeWidth strokeDashArray"+" strokeLineCap strokeLineJoin strokeMiterLimit fillRule backgroundColor").split(" "),initialize:function(options){options=options||{};if(options){this.setOptions(options)}if(this.objectCaching){this._createCacheCanvas()}},_createCacheCanvas:function(){this._cacheProperties={};this._cacheCanvas=fabric.document.createElement("canvas");this._cacheContext=this._cacheCanvas.getContext("2d");this._updateCacheCanvas()},_getCacheCanvasDimensions:function(){var zoom=this.canvas&&this.canvas.getZoom()||1,objectScale=this.getObjectScaling(),dim=this._getNonTransformedDimensions(),retina=this.canvas&&this.canvas._isRetinaScaling()?fabric.devicePixelRatio:1,zoomX=objectScale.scaleX*zoom*retina,zoomY=objectScale.scaleY*zoom*retina,width=dim.x*zoomX,height=dim.y*zoomY;return{width:width+2,height:height+2,zoomX:zoomX,zoomY:zoomY}},_updateCacheCanvas:function(){if(this.noScaleCache&&this.canvas&&this.canvas._currentTransform){var action=this.canvas._currentTransform.action;if(action.slice(0,5)==="scale"){return false}}var dims=this._getCacheCanvasDimensions(),width=dims.width,height=dims.height,zoomX=dims.zoomX,zoomY=dims.zoomY;if(width!==this.cacheWidth||height!==this.cacheHeight){this._cacheCanvas.width=Math.ceil(width);this._cacheCanvas.height=Math.ceil(height);this._cacheContext.translate(width/2,height/2);this._cacheContext.scale(zoomX,zoomY);this.cacheWidth=width;this.cacheHeight=height;this.zoomX=zoomX;this.zoomY=zoomY;return true}return false},setOptions:function(options){this._setOptions(options);this._initGradient(options.fill,"fill");this._initGradient(options.stroke,"stroke");this._initClipping(options);this._initPattern(options.fill,"fill");this._initPattern(options.stroke,"stroke")},transform:function(ctx,fromLeft){if(this.group&&!this.group._transformDone&&this.group===this.canvas._activeGroup){this.group.transform(ctx)}var center=fromLeft?this._getLeftTopCoords():this.getCenterPoint();ctx.translate(center.x,center.y);this.angle&&ctx.rotate(degreesToRadians(this.angle));ctx.scale(this.scaleX*(this.flipX?-1:1),this.scaleY*(this.flipY?-1:1));this.skewX&&ctx.transform(1,0,Math.tan(degreesToRadians(this.skewX)),1,0,0);this.skewY&&ctx.transform(1,Math.tan(degreesToRadians(this.skewY)),0,1,0,0)},toObject:function(propertiesToInclude){var NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS,object={type:this.type,originX:this.originX,originY:this.originY,left:toFixed(this.left,NUM_FRACTION_DIGITS),top:toFixed(this.top,NUM_FRACTION_DIGITS),width:toFixed(this.width,NUM_FRACTION_DIGITS),height:toFixed(this.height,NUM_FRACTION_DIGITS),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:toFixed(this.strokeWidth,NUM_FRACTION_DIGITS),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:toFixed(this.strokeMiterLimit,NUM_FRACTION_DIGITS),scaleX:toFixed(this.scaleX,NUM_FRACTION_DIGITS),scaleY:toFixed(this.scaleY,NUM_FRACTION_DIGITS),angle:toFixed(this.getAngle(),NUM_FRACTION_DIGITS),flipX:this.flipX,flipY:this.flipY,opacity:toFixed(this.opacity,NUM_FRACTION_DIGITS),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,clipTo:this.clipTo&&String(this.clipTo),backgroundColor:this.backgroundColor,fillRule:this.fillRule,globalCompositeOperation:this.globalCompositeOperation,transformMatrix:this.transformMatrix?this.transformMatrix.concat():null,skewX:toFixed(this.skewX,NUM_FRACTION_DIGITS),skewY:toFixed(this.skewY,NUM_FRACTION_DIGITS)};fabric.util.populateWithProperties(this,object,propertiesToInclude);if(!this.includeDefaultValues){object=this._removeDefaultValues(object)}return object},toDatalessObject:function(propertiesToInclude){return this.toObject(propertiesToInclude)},_removeDefaultValues:function(object){var prototype=fabric.util.getKlass(object.type).prototype,stateProperties=prototype.stateProperties;stateProperties.forEach(function(prop){if(object[prop]===prototype[prop]){delete object[prop]}var isArray=Object.prototype.toString.call(object[prop])==="[object Array]"&&Object.prototype.toString.call(prototype[prop])==="[object Array]";if(isArray&&object[prop].length===0&&prototype[prop].length===0){delete object[prop]}});return object},toString:function(){return"#<fabric."+capitalize(this.type)+">"},getObjectScaling:function(){var scaleX=this.scaleX,scaleY=this.scaleY;if(this.group){var scaling=this.group.getObjectScaling();scaleX*=scaling.scaleX;scaleY*=scaling.scaleY}return{scaleX:scaleX,scaleY:scaleY}},_set:function(key,value){var shouldConstrainValue=key==="scaleX"||key==="scaleY";if(shouldConstrainValue){value=this._constrainScale(value)}if(key==="scaleX"&&value<0){this.flipX=!this.flipX;value*=-1}else if(key==="scaleY"&&value<0){this.flipY=!this.flipY;value*=-1}else if(key==="shadow"&&value&&!(value instanceof fabric.Shadow)){value=new fabric.Shadow(value)}else if(key==="dirty"&&this.group){this.group.set("dirty",value)}this[key]=value;if(this.cacheProperties.indexOf(key)>-1){if(this.group){this.group.set("dirty",true)}this.dirty=true}if(this.group&&this.stateProperties.indexOf(key)>-1){this.group.set("dirty",true)}if(key==="width"||key==="height"){this.minScaleLimit=Math.min(.1,1/Math.max(this.width,this.height))}return this},setOnGroup:function(){},setSourcePath:function(value){this.sourcePath=value;return this},getViewportTransform:function(){if(this.canvas&&this.canvas.viewportTransform){return this.canvas.viewportTransform}return fabric.iMatrix.concat()},render:function(ctx,noTransform){if(this.width===0&&this.height===0||!this.visible){return}if(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()){return}ctx.save();this._setupCompositeOperation(ctx);this.drawSelectionBackground(ctx);if(!noTransform){this.transform(ctx)}this._setOpacity(ctx);this._setShadow(ctx);if(this.transformMatrix){ctx.transform.apply(ctx,this.transformMatrix)}this.clipTo&&fabric.util.clipContext(this,ctx);if(this.shouldCache()){if(!this._cacheCanvas){this._createCacheCanvas()}if(this.isCacheDirty(noTransform)){this.statefullCache&&this.saveState({propertySet:"cacheProperties"});this.drawObject(this._cacheContext,noTransform);this.dirty=false}this.drawCacheOnCanvas(ctx)}else{this.drawObject(ctx,noTransform);if(noTransform&&this.objectCaching&&this.statefullCache){this.saveState({propertySet:"cacheProperties"})}}this.clipTo&&ctx.restore();ctx.restore()},shouldCache:function(){return this.objectCaching&&(!this.group||this.needsItsOwnCache||!this.group.isCaching())},willDrawShadow:function(){return!!this.shadow},drawObject:function(ctx,noTransform){this._renderBackground(ctx);this._setStrokeStyles(ctx);this._setFillStyles(ctx);this._render(ctx,noTransform)},drawCacheOnCanvas:function(ctx){ctx.scale(1/this.zoomX,1/this.zoomY);ctx.drawImage(this._cacheCanvas,-this.cacheWidth/2,-this.cacheHeight/2)},isCacheDirty:function(skipCanvas){if(!skipCanvas&&this._updateCacheCanvas()){return true}else{if(this.dirty||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(!skipCanvas){var width=this.cacheWidth/this.zoomX;var height=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-width/2,-height/2,width,height)}return true}}return false},_renderBackground:function(ctx){if(!this.backgroundColor){return}var dim=this._getNonTransformedDimensions();ctx.fillStyle=this.backgroundColor;ctx.fillRect(-dim.x/2,-dim.y/2,dim.x,dim.y);this._removeShadow(ctx)},_setOpacity:function(ctx){ctx.globalAlpha*=this.opacity},_setStrokeStyles:function(ctx){if(this.stroke){ctx.lineWidth=this.strokeWidth;ctx.lineCap=this.strokeLineCap;ctx.lineJoin=this.strokeLineJoin;ctx.miterLimit=this.strokeMiterLimit;ctx.strokeStyle=this.stroke.toLive?this.stroke.toLive(ctx,this):this.stroke}},_setFillStyles:function(ctx){if(this.fill){ctx.fillStyle=this.fill.toLive?this.fill.toLive(ctx,this):this.fill}},_setLineDash:function(ctx,dashArray,alternative){if(!dashArray){return}if(1&dashArray.length){dashArray.push.apply(dashArray,dashArray)}if(supportsLineDash){ctx.setLineDash(dashArray)}else{alternative&&alternative(ctx)}},_renderControls:function(ctx){if(!this.active||this.group&&this.group!==this.canvas.getActiveGroup()){return}var vpt=this.getViewportTransform(),matrix=this.calcTransformMatrix(),options;matrix=fabric.util.multiplyTransformMatrices(vpt,matrix);options=fabric.util.qrDecompose(matrix);ctx.save();ctx.translate(options.translateX,options.translateY);ctx.lineWidth=1*this.borderScaleFactor;if(!this.group){ctx.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1}if(this.group&&this.group===this.canvas.getActiveGroup()){ctx.rotate(degreesToRadians(options.angle));this.drawBordersInGroup(ctx,options)}else{ctx.rotate(degreesToRadians(this.angle));this.drawBorders(ctx)}this.drawControls(ctx);ctx.restore()},_setShadow:function(ctx){if(!this.shadow){return}var multX=this.canvas&&this.canvas.viewportTransform[0]||1,multY=this.canvas&&this.canvas.viewportTransform[3]||1,scaling=this.getObjectScaling();if(this.canvas&&this.canvas._isRetinaScaling()){multX*=fabric.devicePixelRatio;multY*=fabric.devicePixelRatio}ctx.shadowColor=this.shadow.color;ctx.shadowBlur=this.shadow.blur*(multX+multY)*(scaling.scaleX+scaling.scaleY)/4;ctx.shadowOffsetX=this.shadow.offsetX*multX*scaling.scaleX;ctx.shadowOffsetY=this.shadow.offsetY*multY*scaling.scaleY},_removeShadow:function(ctx){if(!this.shadow){return}ctx.shadowColor="";ctx.shadowBlur=ctx.shadowOffsetX=ctx.shadowOffsetY=0},_applyPatternGradientTransform:function(ctx,filler){if(!filler.toLive){return}var transform=filler.gradientTransform||filler.patternTransform;if(transform){ctx.transform.apply(ctx,transform)}var offsetX=-this.width/2+filler.offsetX||0,offsetY=-this.height/2+filler.offsetY||0;ctx.translate(offsetX,offsetY)},_renderFill:function(ctx){if(!this.fill){return}ctx.save();this._applyPatternGradientTransform(ctx,this.fill);if(this.fillRule==="evenodd"){ctx.fill("evenodd")}else{ctx.fill()}ctx.restore()},_renderStroke:function(ctx){if(!this.stroke||this.strokeWidth===0){return}if(this.shadow&&!this.shadow.affectStroke){this._removeShadow(ctx)}ctx.save();this._setLineDash(ctx,this.strokeDashArray,this._renderDashedStroke);this._applyPatternGradientTransform(ctx,this.stroke);ctx.stroke();ctx.restore()},clone:function(callback,propertiesToInclude){if(this.constructor.fromObject){return this.constructor.fromObject(this.toObject(propertiesToInclude),callback)}return new fabric.Object(this.toObject(propertiesToInclude))},cloneAsImage:function(callback,options){var dataUrl=this.toDataURL(options);fabric.util.loadImage(dataUrl,function(img){if(callback){callback(new fabric.Image(img))}});return this},toDataURL:function(options){options||(options={});var el=fabric.util.createCanvasElement(),boundingRect=this.getBoundingRect();el.width=boundingRect.width;el.height=boundingRect.height;fabric.util.wrapElement(el,"div");var canvas=new fabric.StaticCanvas(el,{enableRetinaScaling:options.enableRetinaScaling});if(options.format==="jpg"){options.format="jpeg"}if(options.format==="jpeg"){canvas.backgroundColor="#fff"}var origParams={active:this.get("active"),left:this.getLeft(),top:this.getTop()};this.set("active",false);this.setPositionByOrigin(new fabric.Point(canvas.getWidth()/2,canvas.getHeight()/2),"center","center");var originalCanvas=this.canvas;canvas.add(this);var data=canvas.toDataURL(options);this.set(origParams).setCoords();this.canvas=originalCanvas;canvas.dispose();canvas=null;return data},isType:function(type){return this.type===type},complexity:function(){return 1},toJSON:function(propertiesToInclude){return this.toObject(propertiesToInclude)},setGradient:function(property,options){options||(options={});var gradient={colorStops:[]};gradient.type=options.type||(options.r1||options.r2?"radial":"linear");gradient.coords={x1:options.x1,y1:options.y1,x2:options.x2,y2:options.y2};if(options.r1||options.r2){gradient.coords.r1=options.r1;gradient.coords.r2=options.r2}gradient.gradientTransform=options.gradientTransform;fabric.Gradient.prototype.addColorStop.call(gradient,options.colorStops);return this.set(property,fabric.Gradient.forObject(this,gradient))},setPatternFill:function(options){return this.set("fill",new fabric.Pattern(options))},setShadow:function(options){
return this.set("shadow",options?new fabric.Shadow(options):null)},setColor:function(color){this.set("fill",color);return this},setAngle:function(angle){var shouldCenterOrigin=(this.originX!=="center"||this.originY!=="center")&&this.centeredRotation;if(shouldCenterOrigin){this._setOriginToCenter()}this.set("angle",angle);if(shouldCenterOrigin){this._resetOrigin()}return this},centerH:function(){this.canvas&&this.canvas.centerObjectH(this);return this},viewportCenterH:function(){this.canvas&&this.canvas.viewportCenterObjectH(this);return this},centerV:function(){this.canvas&&this.canvas.centerObjectV(this);return this},viewportCenterV:function(){this.canvas&&this.canvas.viewportCenterObjectV(this);return this},center:function(){this.canvas&&this.canvas.centerObject(this);return this},viewportCenter:function(){this.canvas&&this.canvas.viewportCenterObject(this);return this},remove:function(){this.canvas&&this.canvas.remove(this);return this},getLocalPointer:function(e,pointer){pointer=pointer||this.canvas.getPointer(e);var pClicked=new fabric.Point(pointer.x,pointer.y),objectLeftTop=this._getLeftTopCoords();if(this.angle){pClicked=fabric.util.rotatePoint(pClicked,objectLeftTop,degreesToRadians(-this.angle))}return{x:pClicked.x-objectLeftTop.x,y:pClicked.y-objectLeftTop.y}},_setupCompositeOperation:function(ctx){if(this.globalCompositeOperation){ctx.globalCompositeOperation=this.globalCompositeOperation}}});fabric.util.createAccessors(fabric.Object);fabric.Object.prototype.rotate=fabric.Object.prototype.setAngle;extend(fabric.Object.prototype,fabric.Observable);fabric.Object.NUM_FRACTION_DIGITS=2;fabric.Object._fromObject=function(className,object,callback,forceAsync,extraParam){var klass=fabric[className];object=clone(object,true);if(forceAsync){fabric.util.enlivenPatterns([object.fill,object.stroke],function(patterns){if(typeof patterns[0]!=="undefined"){object.fill=patterns[0]}if(typeof patterns[1]!=="undefined"){object.stroke=patterns[1]}var instance=extraParam?new klass(object[extraParam],object):new klass(object);callback&&callback(instance)})}else{var instance=extraParam?new klass(object[extraParam],object):new klass(object);callback&&callback(instance);return instance}};fabric.Object.__uid=0})(typeof exports!=="undefined"?exports:this);(function(){var degreesToRadians=fabric.util.degreesToRadians,originXOffset={left:-.5,center:0,right:.5},originYOffset={top:-.5,center:0,bottom:.5};fabric.util.object.extend(fabric.Object.prototype,{translateToGivenOrigin:function(point,fromOriginX,fromOriginY,toOriginX,toOriginY){var x=point.x,y=point.y,offsetX,offsetY,dim;if(typeof fromOriginX==="string"){fromOriginX=originXOffset[fromOriginX]}else{fromOriginX-=.5}if(typeof toOriginX==="string"){toOriginX=originXOffset[toOriginX]}else{toOriginX-=.5}offsetX=toOriginX-fromOriginX;if(typeof fromOriginY==="string"){fromOriginY=originYOffset[fromOriginY]}else{fromOriginY-=.5}if(typeof toOriginY==="string"){toOriginY=originYOffset[toOriginY]}else{toOriginY-=.5}offsetY=toOriginY-fromOriginY;if(offsetX||offsetY){dim=this._getTransformedDimensions();x=point.x+offsetX*dim.x;y=point.y+offsetY*dim.y}return new fabric.Point(x,y)},translateToCenterPoint:function(point,originX,originY){var p=this.translateToGivenOrigin(point,originX,originY,"center","center");if(this.angle){return fabric.util.rotatePoint(p,point,degreesToRadians(this.angle))}return p},translateToOriginPoint:function(center,originX,originY){var p=this.translateToGivenOrigin(center,"center","center",originX,originY);if(this.angle){return fabric.util.rotatePoint(p,center,degreesToRadians(this.angle))}return p},getCenterPoint:function(){var leftTop=new fabric.Point(this.left,this.top);return this.translateToCenterPoint(leftTop,this.originX,this.originY)},getPointByOrigin:function(originX,originY){var center=this.getCenterPoint();return this.translateToOriginPoint(center,originX,originY)},toLocalPoint:function(point,originX,originY){var center=this.getCenterPoint(),p,p2;if(typeof originX!=="undefined"&&typeof originY!=="undefined"){p=this.translateToGivenOrigin(center,"center","center",originX,originY)}else{p=new fabric.Point(this.left,this.top)}p2=new fabric.Point(point.x,point.y);if(this.angle){p2=fabric.util.rotatePoint(p2,center,-degreesToRadians(this.angle))}return p2.subtractEquals(p)},setPositionByOrigin:function(pos,originX,originY){var center=this.translateToCenterPoint(pos,originX,originY),position=this.translateToOriginPoint(center,this.originX,this.originY);this.set("left",position.x);this.set("top",position.y)},adjustPosition:function(to){var angle=degreesToRadians(this.angle),hypotFull=this.getWidth(),xFull=Math.cos(angle)*hypotFull,yFull=Math.sin(angle)*hypotFull,offsetFrom,offsetTo;if(typeof this.originX==="string"){offsetFrom=originXOffset[this.originX]}else{offsetFrom=this.originX-.5}if(typeof to==="string"){offsetTo=originXOffset[to]}else{offsetTo=to-.5}this.left+=xFull*(offsetTo-offsetFrom);this.top+=yFull*(offsetTo-offsetFrom);this.setCoords();this.originX=to},_setOriginToCenter:function(){this._originalOriginX=this.originX;this._originalOriginY=this.originY;var center=this.getCenterPoint();this.originX="center";this.originY="center";this.left=center.x;this.top=center.y},_resetOrigin:function(){var originPoint=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX;this.originY=this._originalOriginY;this.left=originPoint.x;this.top=originPoint.y;this._originalOriginX=null;this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")},onDeselect:function(){}})})();(function(){function getCoords(coords){return[new fabric.Point(coords.tl.x,coords.tl.y),new fabric.Point(coords.tr.x,coords.tr.y),new fabric.Point(coords.br.x,coords.br.y),new fabric.Point(coords.bl.x,coords.bl.y)]}var degreesToRadians=fabric.util.degreesToRadians,multiplyMatrices=fabric.util.multiplyTransformMatrices;fabric.util.object.extend(fabric.Object.prototype,{oCoords:null,aCoords:null,getCoords:function(absolute,calculate){if(!this.oCoords){this.setCoords()}var coords=absolute?this.aCoords:this.oCoords;return getCoords(calculate?this.calcCoords(absolute):coords)},intersectsWithRect:function(pointTL,pointBR,absolute,calculate){var coords=this.getCoords(absolute,calculate),intersection=fabric.Intersection.intersectPolygonRectangle(coords,pointTL,pointBR);return intersection.status==="Intersection"},intersectsWithObject:function(other,absolute,calculate){var intersection=fabric.Intersection.intersectPolygonPolygon(this.getCoords(absolute,calculate),other.getCoords(absolute,calculate));return intersection.status==="Intersection"||other.isContainedWithinObject(this,absolute,calculate)||this.isContainedWithinObject(other,absolute,calculate)},isContainedWithinObject:function(other,absolute,calculate){var points=this.getCoords(absolute,calculate),i=0,lines=other._getImageLines(calculate?other.calcCoords(absolute):absolute?other.aCoords:other.oCoords);for(;i<4;i++){if(!other.containsPoint(points[i],lines)){return false}}return true},isContainedWithinRect:function(pointTL,pointBR,absolute,calculate){var boundingRect=this.getBoundingRect(absolute,calculate);return boundingRect.left>=pointTL.x&&boundingRect.left+boundingRect.width<=pointBR.x&&boundingRect.top>=pointTL.y&&boundingRect.top+boundingRect.height<=pointBR.y},containsPoint:function(point,lines,absolute,calculate){var lines=lines||this._getImageLines(calculate?this.calcCoords(absolute):absolute?this.aCoords:this.oCoords),xPoints=this._findCrossPoints(point,lines);return xPoints!==0&&xPoints%2===1},isOnScreen:function(calculate){if(!this.canvas){return false}var pointTL=this.canvas.vptCoords.tl,pointBR=this.canvas.vptCoords.br;var points=this.getCoords(true,calculate),point;for(var i=0;i<4;i++){point=points[i];if(point.x<=pointBR.x&&point.x>=pointTL.x&&point.y<=pointBR.y&&point.y>=pointTL.y){return true}}if(this.intersectsWithRect(pointTL,pointBR,true)){return true}var centerPoint={x:(pointTL.x+pointBR.x)/2,y:(pointTL.y+pointBR.y)/2};if(this.containsPoint(centerPoint,null,true)){return true}return false},_getImageLines:function(oCoords){return{topline:{o:oCoords.tl,d:oCoords.tr},rightline:{o:oCoords.tr,d:oCoords.br},bottomline:{o:oCoords.br,d:oCoords.bl},leftline:{o:oCoords.bl,d:oCoords.tl}}},_findCrossPoints:function(point,lines){var b1,b2,a1,a2,xi,xcount=0,iLine;for(var lineKey in lines){iLine=lines[lineKey];if(iLine.o.y<point.y&&iLine.d.y<point.y){continue}if(iLine.o.y>=point.y&&iLine.d.y>=point.y){continue}if(iLine.o.x===iLine.d.x&&iLine.o.x>=point.x){xi=iLine.o.x}else{b1=0;b2=(iLine.d.y-iLine.o.y)/(iLine.d.x-iLine.o.x);a1=point.y-b1*point.x;a2=iLine.o.y-b2*iLine.o.x;xi=-(a1-a2)/(b1-b2)}if(xi>=point.x){xcount+=1}if(xcount===2){break}}return xcount},getBoundingRectWidth:function(){return this.getBoundingRect().width},getBoundingRectHeight:function(){return this.getBoundingRect().height},getBoundingRect:function(absolute,calculate){var coords=this.getCoords(absolute,calculate);return fabric.util.makeBoundingBoxFromPoints(coords)},getWidth:function(){return this._getTransformedDimensions().x},getHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(value){if(Math.abs(value)<this.minScaleLimit){if(value<0){return-this.minScaleLimit}else{return this.minScaleLimit}}return value},scale:function(value){value=this._constrainScale(value);if(value<0){this.flipX=!this.flipX;this.flipY=!this.flipY;value*=-1}this.scaleX=value;this.scaleY=value;return this.setCoords()},scaleToWidth:function(value){var boundingRectFactor=this.getBoundingRect().width/this.getWidth();return this.scale(value/this.width/boundingRectFactor)},scaleToHeight:function(value){var boundingRectFactor=this.getBoundingRect().height/this.getHeight();return this.scale(value/this.height/boundingRectFactor)},calcCoords:function(absolute){var theta=degreesToRadians(this.angle),vpt=this.getViewportTransform(),dim=absolute?this._getTransformedDimensions():this._calculateCurrentDimensions(),currentWidth=dim.x,currentHeight=dim.y,sinTh=Math.sin(theta),cosTh=Math.cos(theta),_angle=currentWidth>0?Math.atan(currentHeight/currentWidth):0,_hypotenuse=currentWidth/Math.cos(_angle)/2,offsetX=Math.cos(_angle+theta)*_hypotenuse,offsetY=Math.sin(_angle+theta)*_hypotenuse,center=this.getCenterPoint(),coords=absolute?center:fabric.util.transformPoint(center,vpt),tl=new fabric.Point(coords.x-offsetX,coords.y-offsetY),tr=new fabric.Point(tl.x+currentWidth*cosTh,tl.y+currentWidth*sinTh),bl=new fabric.Point(tl.x-currentHeight*sinTh,tl.y+currentHeight*cosTh),br=new fabric.Point(coords.x+offsetX,coords.y+offsetY);if(!absolute){var ml=new fabric.Point((tl.x+bl.x)/2,(tl.y+bl.y)/2),mt=new fabric.Point((tr.x+tl.x)/2,(tr.y+tl.y)/2),mr=new fabric.Point((br.x+tr.x)/2,(br.y+tr.y)/2),mb=new fabric.Point((br.x+bl.x)/2,(br.y+bl.y)/2),mtr=new fabric.Point(mt.x+sinTh*this.rotatingPointOffset,mt.y-cosTh*this.rotatingPointOffset)}var coords={tl:tl,tr:tr,br:br,bl:bl};if(!absolute){coords.ml=ml;coords.mt=mt;coords.mr=mr;coords.mb=mb;coords.mtr=mtr}return coords},setCoords:function(ignoreZoom,skipAbsolute){this.oCoords=this.calcCoords(ignoreZoom);if(!skipAbsolute){this.aCoords=this.calcCoords(true)}ignoreZoom||this._setCornerCoords&&this._setCornerCoords();return this},_calcRotateMatrix:function(){if(this.angle){var theta=degreesToRadians(this.angle),cos=Math.cos(theta),sin=Math.sin(theta);if(cos===6.123233995736766e-17||cos===-1.8369701987210297e-16){cos=0}return[cos,sin,-sin,cos,0,0]}return fabric.iMatrix.concat()},calcTransformMatrix:function(skipGroup){var center=this.getCenterPoint(),translateMatrix=[1,0,0,1,center.x,center.y],rotateMatrix=this._calcRotateMatrix(),dimensionMatrix=this._calcDimensionsTransformMatrix(this.skewX,this.skewY,true),matrix=this.group&&!skipGroup?this.group.calcTransformMatrix():fabric.iMatrix.concat();matrix=multiplyMatrices(matrix,translateMatrix);matrix=multiplyMatrices(matrix,rotateMatrix);matrix=multiplyMatrices(matrix,dimensionMatrix);return matrix},_calcDimensionsTransformMatrix:function(skewX,skewY,flipping){var skewMatrixX=[1,0,Math.tan(degreesToRadians(skewX)),1],skewMatrixY=[1,Math.tan(degreesToRadians(skewY)),0,1],scaleX=this.scaleX*(flipping&&this.flipX?-1:1),scaleY=this.scaleY*(flipping&&this.flipY?-1:1),scaleMatrix=[scaleX,0,0,scaleY],m=multiplyMatrices(scaleMatrix,skewMatrixX,true);return multiplyMatrices(m,skewMatrixY,true)},_getNonTransformedDimensions:function(){var strokeWidth=this.strokeWidth,w=this.width+strokeWidth,h=this.height+strokeWidth;return{x:w,y:h}},_getTransformedDimensions:function(skewX,skewY){if(typeof skewX==="undefined"){skewX=this.skewX}if(typeof skewY==="undefined"){skewY=this.skewY}var dimensions=this._getNonTransformedDimensions(),dimX=dimensions.x/2,dimY=dimensions.y/2,points=[{x:-dimX,y:-dimY},{x:dimX,y:-dimY},{x:-dimX,y:dimY},{x:dimX,y:dimY}],i,transformMatrix=this._calcDimensionsTransformMatrix(skewX,skewY,false),bbox;for(i=0;i<points.length;i++){points[i]=fabric.util.transformPoint(points[i],transformMatrix)}bbox=fabric.util.makeBoundingBoxFromPoints(points);return{x:bbox.width,y:bbox.height}},_calculateCurrentDimensions:function(){var vpt=this.getViewportTransform(),dim=this._getTransformedDimensions(),p=fabric.util.transformPoint(dim,vpt,true);return p.scalarAdd(2*this.padding)}})})();fabric.util.object.extend(fabric.Object.prototype,{sendToBack:function(){if(this.group){fabric.StaticCanvas.prototype.sendToBack.call(this.group,this)}else{this.canvas.sendToBack(this)}return this},bringToFront:function(){if(this.group){fabric.StaticCanvas.prototype.bringToFront.call(this.group,this)}else{this.canvas.bringToFront(this)}return this},sendBackwards:function(intersecting){if(this.group){fabric.StaticCanvas.prototype.sendBackwards.call(this.group,this,intersecting)}else{this.canvas.sendBackwards(this,intersecting)}return this},bringForward:function(intersecting){if(this.group){fabric.StaticCanvas.prototype.bringForward.call(this.group,this,intersecting)}else{this.canvas.bringForward(this,intersecting)}return this},moveTo:function(index){if(this.group){fabric.StaticCanvas.prototype.moveTo.call(this.group,this,index)}else{this.canvas.moveTo(this,index)}return this}});(function(){function getSvgColorString(prop,value){if(!value){return prop+": none; "}else if(value.toLive){return prop+": url(#SVGID_"+value.id+"); "}else{var color=new fabric.Color(value),str=prop+": "+color.toRgb()+"; ",opacity=color.getAlpha();if(opacity!==1){str+=prop+"-opacity: "+opacity.toString()+"; "}return str}}fabric.util.object.extend(fabric.Object.prototype,{getSvgStyles:function(skipShadow){var fillRule=this.fillRule,strokeWidth=this.strokeWidth?this.strokeWidth:"0",strokeDashArray=this.strokeDashArray?this.strokeDashArray.join(" "):"none",strokeLineCap=this.strokeLineCap?this.strokeLineCap:"butt",strokeLineJoin=this.strokeLineJoin?this.strokeLineJoin:"miter",strokeMiterLimit=this.strokeMiterLimit?this.strokeMiterLimit:"4",opacity=typeof this.opacity!=="undefined"?this.opacity:"1",visibility=this.visible?"":" visibility: hidden;",filter=skipShadow?"":this.getSvgFilter(),fill=getSvgColorString("fill",this.fill),stroke=getSvgColorString("stroke",this.stroke);return[stroke,"stroke-width: ",strokeWidth,"; ","stroke-dasharray: ",strokeDashArray,"; ","stroke-linecap: ",strokeLineCap,"; ","stroke-linejoin: ",strokeLineJoin,"; ","stroke-miterlimit: ",strokeMiterLimit,"; ",fill,"fill-rule: ",fillRule,"; ","opacity: ",opacity,";",filter,visibility].join("")},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgId:function(){return this.id?'id="'+this.id+'" ':""},getSvgTransform:function(){if(this.group&&this.group.type==="path-group"){return""}var toFixed=fabric.util.toFixed,angle=this.getAngle(),skewX=this.getSkewX()%360,skewY=this.getSkewY()%360,center=this.getCenterPoint(),NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS,translatePart=this.type==="path-group"?"":"translate("+toFixed(center.x,NUM_FRACTION_DIGITS)+" "+toFixed(center.y,NUM_FRACTION_DIGITS)+")",anglePart=angle!==0?" rotate("+toFixed(angle,NUM_FRACTION_DIGITS)+")":"",scalePart=this.scaleX===1&&this.scaleY===1?"":" scale("+toFixed(this.scaleX,NUM_FRACTION_DIGITS)+" "+toFixed(this.scaleY,NUM_FRACTION_DIGITS)+")",skewXPart=skewX!==0?" skewX("+toFixed(skewX,NUM_FRACTION_DIGITS)+")":"",skewYPart=skewY!==0?" skewY("+toFixed(skewY,NUM_FRACTION_DIGITS)+")":"",addTranslateX=this.type==="path-group"?this.width:0,flipXPart=this.flipX?" matrix(-1 0 0 1 "+addTranslateX+" 0) ":"",addTranslateY=this.type==="path-group"?this.height:0,flipYPart=this.flipY?" matrix(1 0 0 -1 0 "+addTranslateY+")":"";return[translatePart,anglePart,scalePart,flipXPart,flipYPart,skewXPart,skewYPart].join("")},getSvgTransformMatrix:function(){return this.transformMatrix?" matrix("+this.transformMatrix.join(" ")+") ":""},_createBaseSVGMarkup:function(){var markup=[];if(this.fill&&this.fill.toLive){markup.push(this.fill.toSVG(this,false))}if(this.stroke&&this.stroke.toLive){markup.push(this.stroke.toSVG(this,false))}if(this.shadow){markup.push(this.shadow.toSVG(this))}return markup}})})();(function(){var extend=fabric.util.object.extend,originalSet="stateProperties";function saveProps(origin,destination,props){var tmpObj={},deep=true;props.forEach(function(prop){tmpObj[prop]=origin[prop]});extend(origin[destination],tmpObj,deep)}function _isEqual(origValue,currentValue,firstPass){if(!fabric.isLikelyNode&&origValue instanceof Element){return origValue===currentValue}else if(origValue instanceof Array){if(origValue.length!==currentValue.length){return false}for(var i=0,len=origValue.length;i<len;i++){if(origValue[i]!==currentValue[i]){return false}}return true}else if(origValue&&typeof origValue==="object"){if(!firstPass&&Object.keys(origValue).length!==Object.keys(currentValue).length){return false}for(var key in origValue){if(!_isEqual(origValue[key],currentValue[key])){return false}}return true}else{return origValue===currentValue}}fabric.util.object.extend(fabric.Object.prototype,{hasStateChanged:function(propertySet){propertySet=propertySet||originalSet;propertySet="_"+propertySet;if(!Object.keys(this[propertySet]).length){return true}return!_isEqual(this[propertySet],this,true)},saveState:function(options){var propertySet=options&&options.propertySet||originalSet,destination="_"+propertySet;if(!this[destination]){return this.setupState(options)}saveProps(this,destination,this[propertySet]);if(options&&options.stateProperties){saveProps(this,destination,options.stateProperties)}return this},setupState:function(options){options=options||{};var propertySet=options.propertySet||originalSet;options.propertySet=propertySet;this["_"+propertySet]={};this.saveState(options);return this}})})();(function(){var degreesToRadians=fabric.util.degreesToRadians,isVML=function(){return typeof G_vmlCanvasManager!=="undefined"};fabric.util.object.extend(fabric.Object.prototype,{_controlsVisibility:null,_findTargetCorner:function(pointer){if(!this.hasControls||!this.active){return false}var ex=pointer.x,ey=pointer.y,xPoints,lines;this.__corner=0;for(var i in this.oCoords){if(!this.isControlVisible(i)){continue}if(i==="mtr"&&!this.hasRotatingPoint){continue}if(this.get("lockUniScaling")&&(i==="mt"||i==="mr"||i==="mb"||i==="ml")){continue}lines=this._getImageLines(this.oCoords[i].corner);xPoints=this._findCrossPoints({x:ex,y:ey},lines);if(xPoints!==0&&xPoints%2===1){this.__corner=i;return i}}return false},_setCornerCoords:function(){var coords=this.oCoords,newTheta=degreesToRadians(45-this.angle),cornerHypotenuse=this.cornerSize*.707106,cosHalfOffset=cornerHypotenuse*Math.cos(newTheta),sinHalfOffset=cornerHypotenuse*Math.sin(newTheta),x,y;for(var point in coords){x=coords[point].x;y=coords[point].y;coords[point].corner={tl:{x:x-sinHalfOffset,y:y-cosHalfOffset},tr:{x:x+cosHalfOffset,y:y-sinHalfOffset},bl:{x:x-cosHalfOffset,y:y+sinHalfOffset},br:{x:x+sinHalfOffset,y:y+cosHalfOffset}}}},drawSelectionBackground:function(ctx){if(!this.selectionBackgroundColor||this.group||!this.active||this.canvas&&!this.canvas.interactive){return this}ctx.save();var center=this.getCenterPoint(),wh=this._calculateCurrentDimensions(),vpt=this.canvas.viewportTransform;ctx.translate(center.x,center.y);ctx.scale(1/vpt[0],1/vpt[3]);ctx.rotate(degreesToRadians(this.angle));ctx.fillStyle=this.selectionBackgroundColor;ctx.fillRect(-wh.x/2,-wh.y/2,wh.x,wh.y);ctx.restore();return this},drawBorders:function(ctx){if(!this.hasBorders){return this}var wh=this._calculateCurrentDimensions(),strokeWidth=1/this.borderScaleFactor,width=wh.x+strokeWidth,height=wh.y+strokeWidth;ctx.save();ctx.strokeStyle=this.borderColor;this._setLineDash(ctx,this.borderDashArray,null);ctx.strokeRect(-width/2,-height/2,width,height);if(this.hasRotatingPoint&&this.isControlVisible("mtr")&&!this.get("lockRotation")&&this.hasControls){var rotateHeight=-height/2;ctx.beginPath();ctx.moveTo(0,rotateHeight);ctx.lineTo(0,rotateHeight-this.rotatingPointOffset);ctx.closePath();ctx.stroke()}ctx.restore();return this},drawBordersInGroup:function(ctx,options){if(!this.hasBorders){return this}var p=this._getNonTransformedDimensions(),matrix=fabric.util.customTransformMatrix(options.scaleX,options.scaleY,options.skewX),wh=fabric.util.transformPoint(p,matrix),strokeWidth=1/this.borderScaleFactor,width=wh.x+strokeWidth,height=wh.y+strokeWidth;ctx.save();this._setLineDash(ctx,this.borderDashArray,null);ctx.strokeStyle=this.borderColor;ctx.strokeRect(-width/2,-height/2,width,height);ctx.restore();return this},drawControls:function(ctx){if(!this.hasControls){return this}var wh=this._calculateCurrentDimensions(),width=wh.x,height=wh.y,scaleOffset=this.cornerSize,left=-(width+scaleOffset)/2,top=-(height+scaleOffset)/2,methodName=this.transparentCorners?"stroke":"fill";ctx.save();ctx.strokeStyle=ctx.fillStyle=this.cornerColor;if(!this.transparentCorners){ctx.strokeStyle=this.cornerStrokeColor}this._setLineDash(ctx,this.cornerDashArray,null);this._drawControl("tl",ctx,methodName,left,top);this._drawControl("tr",ctx,methodName,left+width,top);this._drawControl("bl",ctx,methodName,left,top+height);this._drawControl("br",ctx,methodName,left+width,top+height);if(!this.get("lockUniScaling")){this._drawControl("mt",ctx,methodName,left+width/2,top);this._drawControl("mb",ctx,methodName,left+width/2,top+height);this._drawControl("mr",ctx,methodName,left+width,top+height/2);this._drawControl("ml",ctx,methodName,left,top+height/2)}if(this.hasRotatingPoint){this._drawControl("mtr",ctx,methodName,left+width/2,top-this.rotatingPointOffset)}ctx.restore();return this},_drawControl:function(control,ctx,methodName,left,top){if(!this.isControlVisible(control)){return}var size=this.cornerSize,stroke=!this.transparentCorners&&this.cornerStrokeColor;switch(this.cornerStyle){case"circle":ctx.beginPath();ctx.arc(left+size/2,top+size/2,size/2,0,2*Math.PI,false);ctx[methodName]();if(stroke){ctx.stroke()}break;default:isVML()||this.transparentCorners||ctx.clearRect(left,top,size,size);ctx[methodName+"Rect"](left,top,size,size);if(stroke){ctx.strokeRect(left,top,size,size)}}},isControlVisible:function(controlName){return this._getControlsVisibility()[controlName]},setControlVisible:function(controlName,visible){this._getControlsVisibility()[controlName]=visible;return this},setControlsVisibility:function(options){options||(options={});for(var p in options){this.setControlVisible(p,options[p])}return this},_getControlsVisibility:function(){if(!this._controlsVisibility){this._controlsVisibility={tl:true,tr:true,br:true,bl:true,ml:true,mt:true,mr:true,mb:true,mtr:true}}return this._controlsVisibility}})})();fabric.util.object.extend(fabric.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(object,callbacks){callbacks=callbacks||{};var empty=function(){},onComplete=callbacks.onComplete||empty,onChange=callbacks.onChange||empty,_this=this;fabric.util.animate({startValue:object.get("left"),endValue:this.getCenter().left,duration:this.FX_DURATION,onChange:function(value){object.set("left",value);_this.renderAll();onChange()},onComplete:function(){object.setCoords();onComplete()}});return this},fxCenterObjectV:function(object,callbacks){callbacks=callbacks||{};var empty=function(){},onComplete=callbacks.onComplete||empty,onChange=callbacks.onChange||empty,_this=this;fabric.util.animate({startValue:object.get("top"),endValue:this.getCenter().top,duration:this.FX_DURATION,onChange:function(value){object.set("top",value);_this.renderAll();onChange()},onComplete:function(){object.setCoords();onComplete()}});return this},fxRemove:function(object,callbacks){callbacks=callbacks||{};var empty=function(){},onComplete=callbacks.onComplete||empty,onChange=callbacks.onChange||empty,_this=this;fabric.util.animate({startValue:object.get("opacity"),endValue:0,duration:this.FX_DURATION,onStart:function(){object.set("active",false)},onChange:function(value){object.set("opacity",value);_this.renderAll();onChange()},onComplete:function(){_this.remove(object);onComplete()}});return this}});fabric.util.object.extend(fabric.Object.prototype,{animate:function(){if(arguments[0]&&typeof arguments[0]==="object"){var propsToAnimate=[],prop,skipCallbacks;for(prop in arguments[0]){propsToAnimate.push(prop)}for(var i=0,len=propsToAnimate.length;i<len;i++){prop=propsToAnimate[i];skipCallbacks=i!==len-1;this._animate(prop,arguments[0][prop],arguments[1],skipCallbacks)}}else{this._animate.apply(this,arguments)}return this},_animate:function(property,to,options,skipCallbacks){var _this=this,propPair;to=to.toString();if(!options){options={}}else{options=fabric.util.object.clone(options)}if(~property.indexOf(".")){propPair=property.split(".")}var currentValue=propPair?this.get(propPair[0])[propPair[1]]:this.get(property);if(!("from"in options)){options.from=currentValue}if(~to.indexOf("=")){to=currentValue+parseFloat(to.replace("=",""))}else{to=parseFloat(to)}fabric.util.animate({startValue:options.from,endValue:to,byValue:options.by,easing:options.easing,duration:options.duration,abort:options.abort&&function(){return options.abort.call(_this)},onChange:function(value){if(propPair){_this[propPair[0]][propPair[1]]=value}else{_this.set(property,value)}if(skipCallbacks){return}options.onChange&&options.onChange()},onComplete:function(){if(skipCallbacks){return}_this.setCoords();options.onComplete&&options.onComplete()}})}});(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,clone=fabric.util.object.clone,coordProps={x1:1,x2:1,y1:1,y2:1},supportsLineDash=fabric.StaticCanvas.supports("setLineDash");if(fabric.Line){fabric.warn("fabric.Line is already defined");return}var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("x1","x2","y1","y2");fabric.Line=fabric.util.createClass(fabric.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:cacheProperties,initialize:function(points,options){if(!points){points=[0,0,0,0]}this.callSuper("initialize",options);this.set("x1",points[0]);this.set("y1",points[1]);this.set("x2",points[2]);this.set("y2",points[3]);this._setWidthHeight(options)},_setWidthHeight:function(options){options||(options={});this.width=Math.abs(this.x2-this.x1);this.height=Math.abs(this.y2-this.y1);this.left="left"in options?options.left:this._getLeftToOriginX();this.top="top"in options?options.top:this._getTopToOriginY()},_set:function(key,value){this.callSuper("_set",key,value);if(typeof coordProps[key]!=="undefined"){this._setWidthHeight()}return this},_getLeftToOriginX:makeEdgeToOriginGetter({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:makeEdgeToOriginGetter({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(ctx,noTransform){ctx.beginPath();if(noTransform){var cp=this.getCenterPoint(),offset=this.strokeWidth/2;ctx.translate(cp.x-(this.strokeLineCap==="butt"&&this.height===0?0:offset),cp.y-(this.strokeLineCap==="butt"&&this.width===0?0:offset))}if(!this.strokeDashArray||this.strokeDashArray&&supportsLineDash){var p=this.calcLinePoints();ctx.moveTo(p.x1,p.y1);ctx.lineTo(p.x2,p.y2)}ctx.lineWidth=this.strokeWidth;var origStrokeStyle=ctx.strokeStyle;ctx.strokeStyle=this.stroke||ctx.fillStyle;this.stroke&&this._renderStroke(ctx);ctx.strokeStyle=origStrokeStyle},_renderDashedStroke:function(ctx){var p=this.calcLinePoints();ctx.beginPath();fabric.util.drawDashedLine(ctx,p.x1,p.y1,p.x2,p.y2,this.strokeDashArray);ctx.closePath()},toObject:function(propertiesToInclude){return extend(this.callSuper("toObject",propertiesToInclude),this.calcLinePoints())},_getNonTransformedDimensions:function(){var dim=this.callSuper("_getNonTransformedDimensions");if(this.strokeLineCap==="butt"){if(this.width===0){dim.y-=this.strokeWidth}if(this.height===0){dim.x-=this.strokeWidth}}return dim},calcLinePoints:function(){var xMult=this.x1<=this.x2?-1:1,yMult=this.y1<=this.y2?-1:1,x1=xMult*this.width*.5,y1=yMult*this.height*.5,x2=xMult*this.width*-.5,y2=yMult*this.height*-.5;return{x1:x1,x2:x2,y1:y1,y2:y2}},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),p={x1:this.x1,x2:this.x2,y1:this.y1,y2:this.y2};if(!(this.group&&this.group.type==="path-group")){p=this.calcLinePoints()}markup.push("<line ",this.getSvgId(),'x1="',p.x1,'" y1="',p.y1,'" x2="',p.x2,'" y2="',p.y2,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n');return reviver?reviver(markup.join("")):markup.join("")}});fabric.Line.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" "));fabric.Line.fromElement=function(element,options){options=options||{};var parsedAttributes=fabric.parseAttributes(element,fabric.Line.ATTRIBUTE_NAMES),points=[parsedAttributes.x1||0,parsedAttributes.y1||0,parsedAttributes.x2||0,parsedAttributes.y2||0];options.originX="left";options.originY="top";return new fabric.Line(points,extend(parsedAttributes,options))};fabric.Line.fromObject=function(object,callback,forceAsync){function _callback(instance){delete instance.points;callback&&callback(instance)}var options=clone(object,true);options.points=[object.x1,object.y1,object.x2,object.y2];var line=fabric.Object._fromObject("Line",options,_callback,forceAsync,"points");if(line){delete line.points}return line};function makeEdgeToOriginGetter(propertyNames,originValues){var origin=propertyNames.origin,axis1=propertyNames.axis1,axis2=propertyNames.axis2,dimension=propertyNames.dimension,nearest=originValues.nearest,center=originValues.center,farthest=originValues.farthest;return function(){switch(this.get(origin)){case nearest:return Math.min(this.get(axis1),this.get(axis2));case center:return Math.min(this.get(axis1),this.get(axis2))+.5*this.get(dimension);case farthest:return Math.max(this.get(axis1),this.get(axis2))}}}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),pi=Math.PI,extend=fabric.util.object.extend;if(fabric.Circle){fabric.warn("fabric.Circle is already defined.");return}var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("radius");fabric.Circle=fabric.util.createClass(fabric.Object,{type:"circle",radius:0,startAngle:0,endAngle:pi*2,cacheProperties:cacheProperties,initialize:function(options){this.callSuper("initialize",options);this.set("radius",options&&options.radius||0)},_set:function(key,value){this.callSuper("_set",key,value);if(key==="radius"){this.setRadius(value)}return this},toObject:function(propertiesToInclude){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(propertiesToInclude))},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),x=0,y=0,angle=(this.endAngle-this.startAngle)%(2*pi);if(angle===0){if(this.group&&this.group.type==="path-group"){x=this.left+this.radius;y=this.top+this.radius;
}markup.push("<circle ",this.getSvgId(),'cx="'+x+'" cy="'+y+'" ','r="',this.radius,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n')}else{var startX=Math.cos(this.startAngle)*this.radius,startY=Math.sin(this.startAngle)*this.radius,endX=Math.cos(this.endAngle)*this.radius,endY=Math.sin(this.endAngle)*this.radius,largeFlag=angle>pi?"1":"0";markup.push('<path d="M '+startX+" "+startY," A "+this.radius+" "+this.radius," 0 ",+largeFlag+" 1"," "+endX+" "+endY,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n')}return reviver?reviver(markup.join("")):markup.join("")},_render:function(ctx,noTransform){ctx.beginPath();ctx.arc(noTransform?this.left+this.radius:0,noTransform?this.top+this.radius:0,this.radius,this.startAngle,this.endAngle,false);this._renderFill(ctx);this._renderStroke(ctx)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(value){this.radius=value;return this.set("width",value*2).set("height",value*2)}});fabric.Circle.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("cx cy r".split(" "));fabric.Circle.fromElement=function(element,options){options||(options={});var parsedAttributes=fabric.parseAttributes(element,fabric.Circle.ATTRIBUTE_NAMES);if(!isValidRadius(parsedAttributes)){throw new Error("value of `r` attribute is required and can not be negative")}parsedAttributes.left=parsedAttributes.left||0;parsedAttributes.top=parsedAttributes.top||0;var obj=new fabric.Circle(extend(parsedAttributes,options));obj.left-=obj.radius;obj.top-=obj.radius;return obj};function isValidRadius(attributes){return"radius"in attributes&&attributes.radius>=0}fabric.Circle.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Circle",object,callback,forceAsync)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={});if(fabric.Triangle){fabric.warn("fabric.Triangle is already defined");return}fabric.Triangle=fabric.util.createClass(fabric.Object,{type:"triangle",initialize:function(options){this.callSuper("initialize",options);this.set("width",options&&options.width||100).set("height",options&&options.height||100)},_render:function(ctx){var widthBy2=this.width/2,heightBy2=this.height/2;ctx.beginPath();ctx.moveTo(-widthBy2,heightBy2);ctx.lineTo(0,-heightBy2);ctx.lineTo(widthBy2,heightBy2);ctx.closePath();this._renderFill(ctx);this._renderStroke(ctx)},_renderDashedStroke:function(ctx){var widthBy2=this.width/2,heightBy2=this.height/2;ctx.beginPath();fabric.util.drawDashedLine(ctx,-widthBy2,heightBy2,0,-heightBy2,this.strokeDashArray);fabric.util.drawDashedLine(ctx,0,-heightBy2,widthBy2,heightBy2,this.strokeDashArray);fabric.util.drawDashedLine(ctx,widthBy2,heightBy2,-widthBy2,heightBy2,this.strokeDashArray);ctx.closePath()},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),widthBy2=this.width/2,heightBy2=this.height/2,points=[-widthBy2+" "+heightBy2,"0 "+-heightBy2,widthBy2+" "+heightBy2].join(",");markup.push("<polygon ",this.getSvgId(),'points="',points,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),'"/>');return reviver?reviver(markup.join("")):markup.join("")}});fabric.Triangle.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Triangle",object,callback,forceAsync)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),piBy2=Math.PI*2,extend=fabric.util.object.extend;if(fabric.Ellipse){fabric.warn("fabric.Ellipse is already defined.");return}var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("rx","ry");fabric.Ellipse=fabric.util.createClass(fabric.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:cacheProperties,initialize:function(options){this.callSuper("initialize",options);this.set("rx",options&&options.rx||0);this.set("ry",options&&options.ry||0)},_set:function(key,value){this.callSuper("_set",key,value);switch(key){case"rx":this.rx=value;this.set("width",value*2);break;case"ry":this.ry=value;this.set("height",value*2);break}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(propertiesToInclude){return this.callSuper("toObject",["rx","ry"].concat(propertiesToInclude))},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),x=0,y=0;if(this.group&&this.group.type==="path-group"){x=this.left+this.rx;y=this.top+this.ry}markup.push("<ellipse ",this.getSvgId(),'cx="',x,'" cy="',y,'" ','rx="',this.rx,'" ry="',this.ry,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n');return reviver?reviver(markup.join("")):markup.join("")},_render:function(ctx,noTransform){ctx.beginPath();ctx.save();ctx.transform(1,0,0,this.ry/this.rx,0,0);ctx.arc(noTransform?this.left+this.rx:0,noTransform?(this.top+this.ry)*this.rx/this.ry:0,this.rx,0,piBy2,false);ctx.restore();this._renderFill(ctx);this._renderStroke(ctx)}});fabric.Ellipse.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" "));fabric.Ellipse.fromElement=function(element,options){options||(options={});var parsedAttributes=fabric.parseAttributes(element,fabric.Ellipse.ATTRIBUTE_NAMES);parsedAttributes.left=parsedAttributes.left||0;parsedAttributes.top=parsedAttributes.top||0;var ellipse=new fabric.Ellipse(extend(parsedAttributes,options));ellipse.top-=ellipse.ry;ellipse.left-=ellipse.rx;return ellipse};fabric.Ellipse.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Ellipse",object,callback,forceAsync)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend;if(fabric.Rect){fabric.warn("fabric.Rect is already defined");return}var stateProperties=fabric.Object.prototype.stateProperties.concat();stateProperties.push("rx","ry");var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("rx","ry");fabric.Rect=fabric.util.createClass(fabric.Object,{stateProperties:stateProperties,type:"rect",rx:0,ry:0,cacheProperties:cacheProperties,initialize:function(options){this.callSuper("initialize",options);this._initRxRy()},_initRxRy:function(){if(this.rx&&!this.ry){this.ry=this.rx}else if(this.ry&&!this.rx){this.rx=this.ry}},_render:function(ctx,noTransform){if(this.width===1&&this.height===1){ctx.fillRect(-.5,-.5,1,1);return}var rx=this.rx?Math.min(this.rx,this.width/2):0,ry=this.ry?Math.min(this.ry,this.height/2):0,w=this.width,h=this.height,x=noTransform?this.left:-this.width/2,y=noTransform?this.top:-this.height/2,isRounded=rx!==0||ry!==0,k=1-.5522847498;ctx.beginPath();ctx.moveTo(x+rx,y);ctx.lineTo(x+w-rx,y);isRounded&&ctx.bezierCurveTo(x+w-k*rx,y,x+w,y+k*ry,x+w,y+ry);ctx.lineTo(x+w,y+h-ry);isRounded&&ctx.bezierCurveTo(x+w,y+h-k*ry,x+w-k*rx,y+h,x+w-rx,y+h);ctx.lineTo(x+rx,y+h);isRounded&&ctx.bezierCurveTo(x+k*rx,y+h,x,y+h-k*ry,x,y+h-ry);ctx.lineTo(x,y+ry);isRounded&&ctx.bezierCurveTo(x,y+k*ry,x+k*rx,y,x+rx,y);ctx.closePath();this._renderFill(ctx);this._renderStroke(ctx)},_renderDashedStroke:function(ctx){var x=-this.width/2,y=-this.height/2,w=this.width,h=this.height;ctx.beginPath();fabric.util.drawDashedLine(ctx,x,y,x+w,y,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x+w,y,x+w,y+h,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x+w,y+h,x,y+h,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x,y+h,x,y,this.strokeDashArray);ctx.closePath()},toObject:function(propertiesToInclude){return this.callSuper("toObject",["rx","ry"].concat(propertiesToInclude))},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),x=this.left,y=this.top;if(!(this.group&&this.group.type==="path-group")){x=-this.width/2;y=-this.height/2}markup.push("<rect ",this.getSvgId(),'x="',x,'" y="',y,'" rx="',this.get("rx"),'" ry="',this.get("ry"),'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n');return reviver?reviver(markup.join("")):markup.join("")}});fabric.Rect.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" "));fabric.Rect.fromElement=function(element,options){if(!element){return null}options=options||{};var parsedAttributes=fabric.parseAttributes(element,fabric.Rect.ATTRIBUTE_NAMES);parsedAttributes.left=parsedAttributes.left||0;parsedAttributes.top=parsedAttributes.top||0;var rect=new fabric.Rect(extend(options?fabric.util.object.clone(options):{},parsedAttributes));rect.visible=rect.visible&&rect.width>0&&rect.height>0;return rect};fabric.Rect.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Rect",object,callback,forceAsync)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,min=fabric.util.array.min,max=fabric.util.array.max,toFixed=fabric.util.toFixed,NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS;if(fabric.Polyline){fabric.warn("fabric.Polyline is already defined");return}var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("points");fabric.Polyline=fabric.util.createClass(fabric.Object,{type:"polyline",points:null,minX:0,minY:0,cacheProperties:cacheProperties,initialize:function(points,options){options=options||{};this.points=points||[];this.callSuper("initialize",options);this._calcDimensions();if(!("top"in options)){this.top=this.minY}if(!("left"in options)){this.left=this.minX}this.pathOffset={x:this.minX+this.width/2,y:this.minY+this.height/2}},_calcDimensions:function(){var points=this.points,minX=min(points,"x"),minY=min(points,"y"),maxX=max(points,"x"),maxY=max(points,"y");this.width=maxX-minX||0;this.height=maxY-minY||0;this.minX=minX||0;this.minY=minY||0},toObject:function(propertiesToInclude){return extend(this.callSuper("toObject",propertiesToInclude),{points:this.points.concat()})},toSVG:function(reviver){var points=[],diffX,diffY,markup=this._createBaseSVGMarkup();if(!(this.group&&this.group.type==="path-group")){diffX=this.pathOffset.x;diffY=this.pathOffset.y}for(var i=0,len=this.points.length;i<len;i++){points.push(toFixed(this.points[i].x-diffX,NUM_FRACTION_DIGITS),",",toFixed(this.points[i].y-diffY,NUM_FRACTION_DIGITS)," ")}markup.push("<",this.type," ",this.getSvgId(),'points="',points.join(""),'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n');return reviver?reviver(markup.join("")):markup.join("")},commonRender:function(ctx,noTransform){var point,len=this.points.length,x=noTransform?0:this.pathOffset.x,y=noTransform?0:this.pathOffset.y;if(!len||isNaN(this.points[len-1].y)){return false}ctx.beginPath();ctx.moveTo(this.points[0].x-x,this.points[0].y-y);for(var i=0;i<len;i++){point=this.points[i];ctx.lineTo(point.x-x,point.y-y)}return true},_render:function(ctx,noTransform){if(!this.commonRender(ctx,noTransform)){return}this._renderFill(ctx);this._renderStroke(ctx)},_renderDashedStroke:function(ctx){var p1,p2;ctx.beginPath();for(var i=0,len=this.points.length;i<len;i++){p1=this.points[i];p2=this.points[i+1]||p1;fabric.util.drawDashedLine(ctx,p1.x,p1.y,p2.x,p2.y,this.strokeDashArray)}},complexity:function(){return this.get("points").length}});fabric.Polyline.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat();fabric.Polyline.fromElement=function(element,options){if(!element){return null}options||(options={});var points=fabric.parsePointsAttribute(element.getAttribute("points")),parsedAttributes=fabric.parseAttributes(element,fabric.Polyline.ATTRIBUTE_NAMES);return new fabric.Polyline(points,fabric.util.object.extend(parsedAttributes,options))};fabric.Polyline.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Polyline",object,callback,forceAsync,"points")}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend;if(fabric.Polygon){fabric.warn("fabric.Polygon is already defined");return}fabric.Polygon=fabric.util.createClass(fabric.Polyline,{type:"polygon",_render:function(ctx,noTransform){if(!this.commonRender(ctx,noTransform)){return}ctx.closePath();this._renderFill(ctx);this._renderStroke(ctx)},_renderDashedStroke:function(ctx){this.callSuper("_renderDashedStroke",ctx);ctx.closePath()}});fabric.Polygon.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat();fabric.Polygon.fromElement=function(element,options){if(!element){return null}options||(options={});var points=fabric.parsePointsAttribute(element.getAttribute("points")),parsedAttributes=fabric.parseAttributes(element,fabric.Polygon.ATTRIBUTE_NAMES);return new fabric.Polygon(points,extend(parsedAttributes,options))};fabric.Polygon.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Polygon",object,callback,forceAsync,"points")}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),min=fabric.util.array.min,max=fabric.util.array.max,extend=fabric.util.object.extend,_toString=Object.prototype.toString,drawArc=fabric.util.drawArc,commandLengths={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},repeatedCommands={m:"l",M:"L"};if(fabric.Path){fabric.warn("fabric.Path is already defined");return}var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("path");fabric.Path=fabric.util.createClass(fabric.Object,{type:"path",path:null,minX:0,minY:0,cacheProperties:cacheProperties,initialize:function(path,options){options=options||{};if(options){this.setOptions(options)}if(!path){path=[]}var fromArray=_toString.call(path)==="[object Array]";this.path=fromArray?path:path.match&&path.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);if(!this.path){return}if(!fromArray){this.path=this._parsePath()}this._setPositionDimensions(options);if(this.objectCaching){this._createCacheCanvas()}},_setPositionDimensions:function(options){var calcDim=this._parseDimensions();this.minX=calcDim.left;this.minY=calcDim.top;this.width=calcDim.width;this.height=calcDim.height;if(typeof options.left==="undefined"){this.left=calcDim.left+(this.originX==="center"?this.width/2:this.originX==="right"?this.width:0)}if(typeof options.top==="undefined"){this.top=calcDim.top+(this.originY==="center"?this.height/2:this.originY==="bottom"?this.height:0)}this.pathOffset=this.pathOffset||{x:this.minX+this.width/2,y:this.minY+this.height/2}},_renderPathCommands:function(ctx){var current,previous=null,subpathStartX=0,subpathStartY=0,x=0,y=0,controlX=0,controlY=0,tempX,tempY,l=-this.pathOffset.x,t=-this.pathOffset.y;if(this.group&&this.group.type==="path-group"){l=0;t=0}ctx.beginPath();for(var i=0,len=this.path.length;i<len;++i){current=this.path[i];switch(current[0]){case"l":x+=current[1];y+=current[2];ctx.lineTo(x+l,y+t);break;case"L":x=current[1];y=current[2];ctx.lineTo(x+l,y+t);break;case"h":x+=current[1];ctx.lineTo(x+l,y+t);break;case"H":x=current[1];ctx.lineTo(x+l,y+t);break;case"v":y+=current[1];ctx.lineTo(x+l,y+t);break;case"V":y=current[1];ctx.lineTo(x+l,y+t);break;case"m":x+=current[1];y+=current[2];subpathStartX=x;subpathStartY=y;ctx.moveTo(x+l,y+t);break;case"M":x=current[1];y=current[2];subpathStartX=x;subpathStartY=y;ctx.moveTo(x+l,y+t);break;case"c":tempX=x+current[5];tempY=y+current[6];controlX=x+current[3];controlY=y+current[4];ctx.bezierCurveTo(x+current[1]+l,y+current[2]+t,controlX+l,controlY+t,tempX+l,tempY+t);x=tempX;y=tempY;break;case"C":x=current[5];y=current[6];controlX=current[3];controlY=current[4];ctx.bezierCurveTo(current[1]+l,current[2]+t,controlX+l,controlY+t,x+l,y+t);break;case"s":tempX=x+current[3];tempY=y+current[4];if(previous[0].match(/[CcSs]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}ctx.bezierCurveTo(controlX+l,controlY+t,x+current[1]+l,y+current[2]+t,tempX+l,tempY+t);controlX=x+current[1];controlY=y+current[2];x=tempX;y=tempY;break;case"S":tempX=current[3];tempY=current[4];if(previous[0].match(/[CcSs]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}ctx.bezierCurveTo(controlX+l,controlY+t,current[1]+l,current[2]+t,tempX+l,tempY+t);x=tempX;y=tempY;controlX=current[1];controlY=current[2];break;case"q":tempX=x+current[3];tempY=y+current[4];controlX=x+current[1];controlY=y+current[2];ctx.quadraticCurveTo(controlX+l,controlY+t,tempX+l,tempY+t);x=tempX;y=tempY;break;case"Q":tempX=current[3];tempY=current[4];ctx.quadraticCurveTo(current[1]+l,current[2]+t,tempX+l,tempY+t);x=tempX;y=tempY;controlX=current[1];controlY=current[2];break;case"t":tempX=x+current[1];tempY=y+current[2];if(previous[0].match(/[QqTt]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}ctx.quadraticCurveTo(controlX+l,controlY+t,tempX+l,tempY+t);x=tempX;y=tempY;break;case"T":tempX=current[1];tempY=current[2];if(previous[0].match(/[QqTt]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}ctx.quadraticCurveTo(controlX+l,controlY+t,tempX+l,tempY+t);x=tempX;y=tempY;break;case"a":drawArc(ctx,x+l,y+t,[current[1],current[2],current[3],current[4],current[5],current[6]+x+l,current[7]+y+t]);x+=current[6];y+=current[7];break;case"A":drawArc(ctx,x+l,y+t,[current[1],current[2],current[3],current[4],current[5],current[6]+l,current[7]+t]);x=current[6];y=current[7];break;case"z":case"Z":x=subpathStartX;y=subpathStartY;ctx.closePath();break}previous=current}},_render:function(ctx){this._renderPathCommands(ctx);this._renderFill(ctx);this._renderStroke(ctx)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},toObject:function(propertiesToInclude){var o=extend(this.callSuper("toObject",["sourcePath","pathOffset"].concat(propertiesToInclude)),{path:this.path.map(function(item){return item.slice()}),top:this.top,left:this.left});return o},toDatalessObject:function(propertiesToInclude){var o=this.toObject(propertiesToInclude);if(this.sourcePath){o.path=this.sourcePath}delete o.sourcePath;return o},toSVG:function(reviver){var chunks=[],markup=this._createBaseSVGMarkup(),addTransform="";for(var i=0,len=this.path.length;i<len;i++){chunks.push(this.path[i].join(" "))}var path=chunks.join(" ");if(!(this.group&&this.group.type==="path-group")){addTransform=" translate("+-this.pathOffset.x+", "+-this.pathOffset.y+") "}markup.push("<path ",this.getSvgId(),'d="',path,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),addTransform,this.getSvgTransformMatrix(),'" stroke-linecap="round" ',"/>\n");return reviver?reviver(markup.join("")):markup.join("")},complexity:function(){return this.path.length},_parsePath:function(){var result=[],coords=[],currentPath,parsed,re=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi,match,coordsStr;for(var i=0,coordsParsed,len=this.path.length;i<len;i++){currentPath=this.path[i];coordsStr=currentPath.slice(1).trim();coords.length=0;while(match=re.exec(coordsStr)){coords.push(match[0])}coordsParsed=[currentPath.charAt(0)];for(var j=0,jlen=coords.length;j<jlen;j++){parsed=parseFloat(coords[j]);if(!isNaN(parsed)){coordsParsed.push(parsed)}}var command=coordsParsed[0],commandLength=commandLengths[command.toLowerCase()],repeatedCommand=repeatedCommands[command]||command;if(coordsParsed.length-1>commandLength){for(var k=1,klen=coordsParsed.length;k<klen;k+=commandLength){result.push([command].concat(coordsParsed.slice(k,k+commandLength)));command=repeatedCommand}}else{result.push(coordsParsed)}}return result},_parseDimensions:function(){var aX=[],aY=[],current,previous=null,subpathStartX=0,subpathStartY=0,x=0,y=0,controlX=0,controlY=0,tempX,tempY,bounds;for(var i=0,len=this.path.length;i<len;++i){current=this.path[i];switch(current[0]){case"l":x+=current[1];y+=current[2];bounds=[];break;case"L":x=current[1];y=current[2];bounds=[];break;case"h":x+=current[1];bounds=[];break;case"H":x=current[1];bounds=[];break;case"v":y+=current[1];bounds=[];break;case"V":y=current[1];bounds=[];break;case"m":x+=current[1];y+=current[2];subpathStartX=x;subpathStartY=y;bounds=[];break;case"M":x=current[1];y=current[2];subpathStartX=x;subpathStartY=y;bounds=[];break;case"c":tempX=x+current[5];tempY=y+current[6];controlX=x+current[3];controlY=y+current[4];bounds=fabric.util.getBoundsOfCurve(x,y,x+current[1],y+current[2],controlX,controlY,tempX,tempY);x=tempX;y=tempY;break;case"C":controlX=current[3];controlY=current[4];bounds=fabric.util.getBoundsOfCurve(x,y,current[1],current[2],controlX,controlY,current[5],current[6]);x=current[5];y=current[6];break;case"s":tempX=x+current[3];tempY=y+current[4];if(previous[0].match(/[CcSs]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,x+current[1],y+current[2],tempX,tempY);controlX=x+current[1];controlY=y+current[2];x=tempX;y=tempY;break;case"S":tempX=current[3];tempY=current[4];if(previous[0].match(/[CcSs]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,current[1],current[2],tempX,tempY);x=tempX;y=tempY;controlX=current[1];controlY=current[2];break;case"q":tempX=x+current[3];tempY=y+current[4];controlX=x+current[1];controlY=y+current[2];bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,controlX,controlY,tempX,tempY);x=tempX;y=tempY;break;case"Q":controlX=current[1];controlY=current[2];bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,controlX,controlY,current[3],current[4]);x=current[3];y=current[4];break;case"t":tempX=x+current[1];tempY=y+current[2];if(previous[0].match(/[QqTt]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,controlX,controlY,tempX,tempY);x=tempX;y=tempY;break;case"T":tempX=current[1];tempY=current[2];if(previous[0].match(/[QqTt]/)===null){controlX=x;controlY=y}else{controlX=2*x-controlX;controlY=2*y-controlY}bounds=fabric.util.getBoundsOfCurve(x,y,controlX,controlY,controlX,controlY,tempX,tempY);x=tempX;y=tempY;break;case"a":bounds=fabric.util.getBoundsOfArc(x,y,current[1],current[2],current[3],current[4],current[5],current[6]+x,current[7]+y);x+=current[6];y+=current[7];break;case"A":bounds=fabric.util.getBoundsOfArc(x,y,current[1],current[2],current[3],current[4],current[5],current[6],current[7]);x=current[6];y=current[7];break;case"z":case"Z":x=subpathStartX;y=subpathStartY;break}previous=current;bounds.forEach(function(point){aX.push(point.x);aY.push(point.y)});aX.push(x);aY.push(y)}var minX=min(aX)||0,minY=min(aY)||0,maxX=max(aX)||0,maxY=max(aY)||0,deltaX=maxX-minX,deltaY=maxY-minY,o={left:minX,top:minY,width:deltaX,height:deltaY};return o}});fabric.Path.fromObject=function(object,callback,forceAsync){var path;if(typeof object.path==="string"){fabric.loadSVGFromURL(object.path,function(elements){var pathUrl=object.path;path=elements[0];delete object.path;fabric.util.object.extend(path,object);path.setSourcePath(pathUrl);callback&&callback(path)})}else{return fabric.Object._fromObject("Path",object,callback,forceAsync,"path")}};fabric.Path.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat(["d"]);fabric.Path.fromElement=function(element,callback,options){var parsedAttributes=fabric.parseAttributes(element,fabric.Path.ATTRIBUTE_NAMES);callback&&callback(new fabric.Path(parsedAttributes.d,extend(parsedAttributes,options)))};fabric.Path.async=true})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend;if(fabric.PathGroup){fabric.warn("fabric.PathGroup is already defined");return}fabric.PathGroup=fabric.util.createClass(fabric.Object,{type:"path-group",fill:"",initialize:function(paths,options){options=options||{};this.paths=paths||[];for(var i=this.paths.length;i--;){this.paths[i].group=this}if(options.toBeParsed){this.parseDimensionsFromPaths(options);delete options.toBeParsed}this.setOptions(options);this.setCoords();if(this.objectCaching){this._createCacheCanvas()}},parseDimensionsFromPaths:function(options){var points,p,xC=[],yC=[],path,height,width,m;for(var j=this.paths.length;j--;){path=this.paths[j];height=path.height+path.strokeWidth;width=path.width+path.strokeWidth;points=[{x:path.left,y:path.top},{x:path.left+width,y:path.top},{x:path.left,y:path.top+height},{x:path.left+width,y:path.top+height}];m=this.paths[j].transformMatrix;for(var i=0;i<points.length;i++){p=points[i];if(m){p=fabric.util.transformPoint(p,m,false)}xC.push(p.x);yC.push(p.y)}}options.width=Math.max.apply(null,xC);options.height=Math.max.apply(null,yC)},drawObject:function(ctx){ctx.save();ctx.translate(-this.width/2,-this.height/2);for(var i=0,l=this.paths.length;i<l;++i){this.paths[i].render(ctx,true)}ctx.restore()},shouldCache:function(){var parentCache=this.objectCaching&&(!this.group||this.needsItsOwnCache||!this.group.isCaching());this.caching=parentCache;if(parentCache){for(var i=0,len=this.paths.length;i<len;i++){if(this.paths[i].willDrawShadow()){this.caching=false;return false}}}return parentCache},willDrawShadow:function(){if(this.shadow){return true}for(var i=0,len=this.paths.length;i<len;i++){if(this.paths[i].willDrawShadow()){return true}}return false},isCaching:function(){return this.caching||this.group&&this.group.isCaching()},isCacheDirty:function(){if(this.callSuper("isCacheDirty")){return true}if(!this.statefullCache){return false}for(var i=0,len=this.paths.length;i<len;i++){if(this.paths[i].isCacheDirty(true)){var dim=this._getNonTransformedDimensions();this._cacheContext.clearRect(-dim.x/2,-dim.y/2,dim.x,dim.y);return true}}return false},_set:function(prop,value){if(prop==="fill"&&value&&this.isSameColor()){var i=this.paths.length;while(i--){this.paths[i]._set(prop,value)}}return this.callSuper("_set",prop,value)},toObject:function(propertiesToInclude){var pathsToObject=this.paths.map(function(path){var originalDefaults=path.includeDefaultValues;path.includeDefaultValues=path.group.includeDefaultValues;var obj=path.toObject(propertiesToInclude);path.includeDefaultValues=originalDefaults;return obj});var o=extend(this.callSuper("toObject",["sourcePath"].concat(propertiesToInclude)),{paths:pathsToObject});return o},toDatalessObject:function(propertiesToInclude){var o=this.toObject(propertiesToInclude);if(this.sourcePath){o.paths=this.sourcePath}return o},toSVG:function(reviver){var objects=this.getObjects(),p=this.getPointByOrigin("left","top"),translatePart="translate("+p.x+" "+p.y+")",markup=this._createBaseSVGMarkup();markup.push("<g ",this.getSvgId(),'style="',this.getSvgStyles(),'" ','transform="',this.getSvgTransformMatrix(),translatePart,this.getSvgTransform(),'" ',">\n");for(var i=0,len=objects.length;i<len;i++){markup.push(" ",objects[i].toSVG(reviver))}markup.push("</g>\n");return reviver?reviver(markup.join("")):markup.join("")},toString:function(){return"#<fabric.PathGroup ("+this.complexity()+"): { top: "+this.top+", left: "+this.left+" }>"},isSameColor:function(){var firstPathFill=this.getObjects()[0].get("fill")||"";if(typeof firstPathFill!=="string"){return false}firstPathFill=firstPathFill.toLowerCase();return this.getObjects().every(function(path){var pathFill=path.get("fill")||"";return typeof pathFill==="string"&&pathFill.toLowerCase()===firstPathFill})},complexity:function(){return this.paths.reduce(function(total,path){return total+(path&&path.complexity?path.complexity():0)},0)},getObjects:function(){return this.paths}});fabric.PathGroup.fromObject=function(object,callback){var originalPaths=object.paths;delete object.paths;if(typeof originalPaths==="string"){fabric.loadSVGFromURL(originalPaths,function(elements){var pathUrl=originalPaths;var pathGroup=fabric.util.groupSVGElements(elements,object,pathUrl);object.paths=originalPaths;callback(pathGroup)})}else{fabric.util.enlivenObjects(originalPaths,function(enlivenedObjects){var pathGroup=new fabric.PathGroup(enlivenedObjects,object);object.paths=originalPaths;callback(pathGroup)})}};fabric.PathGroup.async=true})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,min=fabric.util.array.min,max=fabric.util.array.max;if(fabric.Group){return}var _lockProperties={lockMovementX:true,lockMovementY:true,lockRotation:true,lockScalingX:true,lockScalingY:true,lockUniScaling:true};fabric.Group=fabric.util.createClass(fabric.Object,fabric.Collection,{type:"group",strokeWidth:0,subTargetCheck:false,initialize:function(objects,options,isAlreadyGrouped){options=options||{};this._objects=[];isAlreadyGrouped&&this.callSuper("initialize",options);this._objects=objects||[];for(var i=this._objects.length;i--;){this._objects[i].group=this}if(options.originX){this.originX=options.originX}if(options.originY){this.originY=options.originY}if(isAlreadyGrouped){this._updateObjectsCoords(true)}else{this._calcBounds();this._updateObjectsCoords();this.callSuper("initialize",options)}this.setCoords();this.saveCoords()},_updateObjectsCoords:function(skipCoordsChange){var center=this.getCenterPoint();for(var i=this._objects.length;i--;){this._updateObjectCoords(this._objects[i],center,skipCoordsChange)}},_updateObjectCoords:function(object,center,skipCoordsChange){object.__origHasControls=object.hasControls;object.hasControls=false;if(skipCoordsChange){return}var objectLeft=object.getLeft(),objectTop=object.getTop(),ignoreZoom=true,skipAbsolute=true;object.set({left:objectLeft-center.x,top:objectTop-center.y});object.setCoords(ignoreZoom,skipAbsolute)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},addWithUpdate:function(object){this._restoreObjectsState();fabric.util.resetObjectTransform(this);if(object){this._objects.push(object);object.group=this;object._set("canvas",this.canvas)}this.forEachObject(this._setObjectActive,this);this._calcBounds();this._updateObjectsCoords();this.dirty=true;return this},_setObjectActive:function(object){object.set("active",true);object.group=this},removeWithUpdate:function(object){this._restoreObjectsState();fabric.util.resetObjectTransform(this);this.forEachObject(this._setObjectActive,this);this.remove(object);this._calcBounds();this._updateObjectsCoords();this.dirty=true;return this},_onObjectAdded:function(object){this.dirty=true;object.group=this;object._set("canvas",this.canvas)},_onObjectRemoved:function(object){this.dirty=true;delete object.group;object.set("active",false)},delegatedProperties:{fill:true,stroke:true,strokeWidth:true,fontFamily:true,fontWeight:true,fontSize:true,fontStyle:true,lineHeight:true,textDecoration:true,textAlign:true,backgroundColor:true},_set:function(key,value){var i=this._objects.length;if(this.delegatedProperties[key]||key==="canvas"){while(i--){this._objects[i].set(key,value)}}else{while(i--){this._objects[i].setOnGroup(key,value)}}this.callSuper("_set",key,value)},toObject:function(propertiesToInclude){var objsToObject=this.getObjects().map(function(obj){var originalDefaults=obj.includeDefaultValues;obj.includeDefaultValues=obj.group.includeDefaultValues;var _obj=obj.toObject(propertiesToInclude);obj.includeDefaultValues=originalDefaults;return _obj});return extend(this.callSuper("toObject",propertiesToInclude),{objects:objsToObject})},toDatalessObject:function(propertiesToInclude){var objsToObject=this.getObjects().map(function(obj){var originalDefaults=obj.includeDefaultValues;obj.includeDefaultValues=obj.group.includeDefaultValues;var _obj=obj.toDatalessObject(propertiesToInclude);obj.includeDefaultValues=originalDefaults;return _obj});return extend(this.callSuper("toDatalessObject",propertiesToInclude),{
objects:objsToObject})},render:function(ctx){this._transformDone=true;this.callSuper("render",ctx);this._transformDone=false},shouldCache:function(){var parentCache=this.objectCaching&&(!this.group||this.needsItsOwnCache||!this.group.isCaching());this.caching=parentCache;if(parentCache){for(var i=0,len=this._objects.length;i<len;i++){if(this._objects[i].willDrawShadow()){this.caching=false;return false}}}return parentCache},willDrawShadow:function(){if(this.shadow){return true}for(var i=0,len=this._objects.length;i<len;i++){if(this._objects[i].willDrawShadow()){return true}}return false},isCaching:function(){return this.caching||this.group&&this.group.isCaching()},drawObject:function(ctx){for(var i=0,len=this._objects.length;i<len;i++){this._renderObject(this._objects[i],ctx)}},isCacheDirty:function(){if(this.callSuper("isCacheDirty")){return true}if(!this.statefullCache){return false}for(var i=0,len=this._objects.length;i<len;i++){if(this._objects[i].isCacheDirty(true)){var dim=this._getNonTransformedDimensions();this._cacheContext.clearRect(-dim.x/2,-dim.y/2,dim.x,dim.y);return true}}return false},_renderControls:function(ctx,noTransform){ctx.save();ctx.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;this.callSuper("_renderControls",ctx,noTransform);for(var i=0,len=this._objects.length;i<len;i++){this._objects[i]._renderControls(ctx)}ctx.restore()},_renderObject:function(object,ctx){if(!object.visible){return}var originalHasRotatingPoint=object.hasRotatingPoint;object.hasRotatingPoint=false;object.render(ctx);object.hasRotatingPoint=originalHasRotatingPoint},_restoreObjectsState:function(){this._objects.forEach(this._restoreObjectState,this);return this},realizeTransform:function(object){var matrix=object.calcTransformMatrix(),options=fabric.util.qrDecompose(matrix),center=new fabric.Point(options.translateX,options.translateY);object.flipX=false;object.flipY=false;object.set("scaleX",options.scaleX);object.set("scaleY",options.scaleY);object.skewX=options.skewX;object.skewY=options.skewY;object.angle=options.angle;object.setPositionByOrigin(center,"center","center");return object},_restoreObjectState:function(object){this.realizeTransform(object);object.setCoords();object.hasControls=object.__origHasControls;delete object.__origHasControls;object.set("active",false);delete object.group;return this},destroy:function(){return this._restoreObjectsState()},saveCoords:function(){this._originalLeft=this.get("left");this._originalTop=this.get("top");return this},hasMoved:function(){return this._originalLeft!==this.get("left")||this._originalTop!==this.get("top")},setObjectsCoords:function(){var ignoreZoom=true,skipAbsolute=true;this.forEachObject(function(object){object.setCoords(ignoreZoom,skipAbsolute)});return this},_calcBounds:function(onlyWidthHeight){var aX=[],aY=[],o,prop,props=["tr","br","bl","tl"],i=0,iLen=this._objects.length,j,jLen=props.length,ignoreZoom=true;for(;i<iLen;++i){o=this._objects[i];o.setCoords(ignoreZoom);for(j=0;j<jLen;j++){prop=props[j];aX.push(o.oCoords[prop].x);aY.push(o.oCoords[prop].y)}}this.set(this._getBounds(aX,aY,onlyWidthHeight))},_getBounds:function(aX,aY,onlyWidthHeight){var minXY=new fabric.Point(min(aX),min(aY)),maxXY=new fabric.Point(max(aX),max(aY)),obj={width:maxXY.x-minXY.x||0,height:maxXY.y-minXY.y||0};if(!onlyWidthHeight){obj.left=minXY.x||0;obj.top=minXY.y||0;if(this.originX==="center"){obj.left+=obj.width/2}if(this.originX==="right"){obj.left+=obj.width}if(this.originY==="center"){obj.top+=obj.height/2}if(this.originY==="bottom"){obj.top+=obj.height}}return obj},toSVG:function(reviver){var markup=this._createBaseSVGMarkup();markup.push("<g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'" style="',this.getSvgFilter(),'">\n');for(var i=0,len=this._objects.length;i<len;i++){markup.push(" ",this._objects[i].toSVG(reviver))}markup.push("</g>\n");return reviver?reviver(markup.join("")):markup.join("")},get:function(prop){if(prop in _lockProperties){if(this[prop]){return this[prop]}else{for(var i=0,len=this._objects.length;i<len;i++){if(this._objects[i][prop]){return true}}return false}}else{if(prop in this.delegatedProperties){return this._objects[0]&&this._objects[0].get(prop)}return this[prop]}}});fabric.Group.fromObject=function(object,callback){fabric.util.enlivenObjects(object.objects,function(enlivenedObjects){delete object.objects;callback&&callback(new fabric.Group(enlivenedObjects,object,true))})};fabric.Group.async=true})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var extend=fabric.util.object.extend;if(!global.fabric){global.fabric={}}if(global.fabric.Image){fabric.warn("fabric.Image is already defined.");return}var stateProperties=fabric.Object.prototype.stateProperties.concat();stateProperties.push("alignX","alignY","meetOrSlice");fabric.Image=fabric.util.createClass(fabric.Object,{type:"image",crossOrigin:"",alignX:"none",alignY:"none",meetOrSlice:"meet",strokeWidth:0,_lastScaleX:1,_lastScaleY:1,minimumScaleTrigger:.5,stateProperties:stateProperties,objectCaching:false,initialize:function(element,options,callback){options||(options={});this.filters=[];this.resizeFilters=[];this.callSuper("initialize",options);this._initElement(element,options,callback)},getElement:function(){return this._element},setElement:function(element,callback,options){var _callback,_this;this._element=element;this._originalElement=element;this._initConfig(options);if(this.resizeFilters.length===0){_callback=callback}else{_this=this;_callback=function(){_this.applyFilters(callback,_this.resizeFilters,_this._filteredEl||_this._originalElement,true)}}if(this.filters.length!==0){this.applyFilters(_callback)}else if(_callback){_callback(this)}return this},setCrossOrigin:function(value){this.crossOrigin=value;this._element.crossOrigin=value;return this},getOriginalSize:function(){var element=this.getElement();return{width:element.width,height:element.height}},_stroke:function(ctx){if(!this.stroke||this.strokeWidth===0){return}var w=this.width/2,h=this.height/2;ctx.beginPath();ctx.moveTo(-w,-h);ctx.lineTo(w,-h);ctx.lineTo(w,h);ctx.lineTo(-w,h);ctx.lineTo(-w,-h);ctx.closePath()},_renderDashedStroke:function(ctx){var x=-this.width/2,y=-this.height/2,w=this.width,h=this.height;ctx.save();this._setStrokeStyles(ctx);ctx.beginPath();fabric.util.drawDashedLine(ctx,x,y,x+w,y,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x+w,y,x+w,y+h,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x+w,y+h,x,y+h,this.strokeDashArray);fabric.util.drawDashedLine(ctx,x,y+h,x,y,this.strokeDashArray);ctx.closePath();ctx.restore()},toObject:function(propertiesToInclude){var filters=[],resizeFilters=[],scaleX=1,scaleY=1;this.filters.forEach(function(filterObj){if(filterObj){if(filterObj.type==="Resize"){scaleX*=filterObj.scaleX;scaleY*=filterObj.scaleY}filters.push(filterObj.toObject())}});this.resizeFilters.forEach(function(filterObj){filterObj&&resizeFilters.push(filterObj.toObject())});var object=extend(this.callSuper("toObject",["crossOrigin","alignX","alignY","meetOrSlice"].concat(propertiesToInclude)),{src:this.getSrc(),filters:filters,resizeFilters:resizeFilters});object.width/=scaleX;object.height/=scaleY;return object},toSVG:function(reviver){var markup=this._createBaseSVGMarkup(),x=-this.width/2,y=-this.height/2,preserveAspectRatio="none",filtered=true;if(this.group&&this.group.type==="path-group"){x=this.left;y=this.top}if(this.alignX!=="none"&&this.alignY!=="none"){preserveAspectRatio="x"+this.alignX+"Y"+this.alignY+" "+this.meetOrSlice}markup.push('<g transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'">\n',"<image ",this.getSvgId(),'xlink:href="',this.getSvgSrc(filtered),'" x="',x,'" y="',y,'" style="',this.getSvgStyles(),'" width="',this.width,'" height="',this.height,'" preserveAspectRatio="',preserveAspectRatio,'"',"></image>\n");if(this.stroke||this.strokeDashArray){var origFill=this.fill;this.fill=null;markup.push("<rect ",'x="',x,'" y="',y,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n');this.fill=origFill}markup.push("</g>\n");return reviver?reviver(markup.join("")):markup.join("")},getSrc:function(filtered){var element=filtered?this._element:this._originalElement;if(element){return fabric.isLikelyNode?element._src:element.src}else{return this.src||""}},setSrc:function(src,callback,options){fabric.util.loadImage(src,function(img){return this.setElement(img,callback,options)},this,options&&options.crossOrigin)},toString:function(){return'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},applyFilters:function(callback,filters,imgElement,forResizing){filters=filters||this.filters;imgElement=imgElement||this._originalElement;if(!imgElement){return}var replacement=fabric.util.createImage(),retinaScaling=this.canvas?this.canvas.getRetinaScaling():fabric.devicePixelRatio,minimumScale=this.minimumScaleTrigger/retinaScaling,_this=this,scaleX,scaleY;if(filters.length===0){this._element=imgElement;callback&&callback(this);return imgElement}var canvasEl=fabric.util.createCanvasElement();canvasEl.width=imgElement.width;canvasEl.height=imgElement.height;canvasEl.getContext("2d").drawImage(imgElement,0,0,imgElement.width,imgElement.height);filters.forEach(function(filter){if(!filter){return}if(forResizing){scaleX=_this.scaleX<minimumScale?_this.scaleX:1;scaleY=_this.scaleY<minimumScale?_this.scaleY:1;if(scaleX*retinaScaling<1){scaleX*=retinaScaling}if(scaleY*retinaScaling<1){scaleY*=retinaScaling}}else{scaleX=filter.scaleX;scaleY=filter.scaleY}filter.applyTo(canvasEl,scaleX,scaleY);if(!forResizing&&filter.type==="Resize"){_this.width*=filter.scaleX;_this.height*=filter.scaleY}});replacement.width=canvasEl.width;replacement.height=canvasEl.height;if(fabric.isLikelyNode){replacement.src=canvasEl.toBuffer(undefined,fabric.Image.pngCompression);_this._element=replacement;!forResizing&&(_this._filteredEl=replacement);callback&&callback(_this)}else{replacement.onload=function(){_this._element=replacement;!forResizing&&(_this._filteredEl=replacement);callback&&callback(_this);replacement.onload=canvasEl=null};replacement.src=canvasEl.toDataURL("image/png")}return canvasEl},_render:function(ctx,noTransform){var x,y,imageMargins=this._findMargins(),elementToDraw;x=noTransform?this.left:-this.width/2;y=noTransform?this.top:-this.height/2;if(this.meetOrSlice==="slice"){ctx.beginPath();ctx.rect(x,y,this.width,this.height);ctx.clip()}if(this.isMoving===false&&this.resizeFilters.length&&this._needsResize()){this._lastScaleX=this.scaleX;this._lastScaleY=this.scaleY;elementToDraw=this.applyFilters(null,this.resizeFilters,this._filteredEl||this._originalElement,true)}else{elementToDraw=this._element}elementToDraw&&ctx.drawImage(elementToDraw,x+imageMargins.marginX,y+imageMargins.marginY,imageMargins.width,imageMargins.height);this._stroke(ctx);this._renderStroke(ctx)},_needsResize:function(){return this.scaleX!==this._lastScaleX||this.scaleY!==this._lastScaleY},_findMargins:function(){var width=this.width,height=this.height,scales,scale,marginX=0,marginY=0;if(this.alignX!=="none"||this.alignY!=="none"){scales=[this.width/this._element.width,this.height/this._element.height];scale=this.meetOrSlice==="meet"?Math.min.apply(null,scales):Math.max.apply(null,scales);width=this._element.width*scale;height=this._element.height*scale;if(this.alignX==="Mid"){marginX=(this.width-width)/2}if(this.alignX==="Max"){marginX=this.width-width}if(this.alignY==="Mid"){marginY=(this.height-height)/2}if(this.alignY==="Max"){marginY=this.height-height}}return{width:width,height:height,marginX:marginX,marginY:marginY}},_resetWidthHeight:function(){var element=this.getElement();this.set("width",element.width);this.set("height",element.height)},_initElement:function(element,options,callback){this.setElement(fabric.util.getById(element),callback,options);fabric.util.addClass(this.getElement(),fabric.Image.CSS_CANVAS)},_initConfig:function(options){options||(options={});this.setOptions(options);this._setWidthHeight(options);if(this._element&&this.crossOrigin){this._element.crossOrigin=this.crossOrigin}},_initFilters:function(filters,callback){if(filters&&filters.length){fabric.util.enlivenObjects(filters,function(enlivenedObjects){callback&&callback(enlivenedObjects)},"fabric.Image.filters")}else{callback&&callback()}},_setWidthHeight:function(options){this.width="width"in options?options.width:this.getElement()?this.getElement().width||0:0;this.height="height"in options?options.height:this.getElement()?this.getElement().height||0:0}});fabric.Image.CSS_CANVAS="canvas-img";fabric.Image.prototype.getSvgSrc=fabric.Image.prototype.getSrc;fabric.Image.fromObject=function(object,callback){fabric.util.loadImage(object.src,function(img,error){if(error){callback&&callback(null,error);return}fabric.Image.prototype._initFilters.call(object,object.filters,function(filters){object.filters=filters||[];fabric.Image.prototype._initFilters.call(object,object.resizeFilters,function(resizeFilters){object.resizeFilters=resizeFilters||[];return new fabric.Image(img,object,callback)})})},null,object.crossOrigin)};fabric.Image.fromURL=function(url,callback,imgOptions){fabric.util.loadImage(url,function(img){callback&&callback(new fabric.Image(img,imgOptions))},null,imgOptions&&imgOptions.crossOrigin)};fabric.Image.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin".split(" "));fabric.Image.fromElement=function(element,callback,options){var parsedAttributes=fabric.parseAttributes(element,fabric.Image.ATTRIBUTE_NAMES),preserveAR;if(parsedAttributes.preserveAspectRatio){preserveAR=fabric.util.parsePreserveAspectRatioAttribute(parsedAttributes.preserveAspectRatio);extend(parsedAttributes,preserveAR)}fabric.Image.fromURL(parsedAttributes["xlink:href"],callback,extend(options?fabric.util.object.clone(options):{},parsedAttributes))};fabric.Image.async=true;fabric.Image.pngCompression=1})(typeof exports!=="undefined"?exports:this);fabric.util.object.extend(fabric.Object.prototype,{_getAngleValueForStraighten:function(){var angle=this.getAngle()%360;if(angle>0){return Math.round((angle-1)/90)*90}return Math.round(angle/90)*90},straighten:function(){this.setAngle(this._getAngleValueForStraighten());return this},fxStraighten:function(callbacks){callbacks=callbacks||{};var empty=function(){},onComplete=callbacks.onComplete||empty,onChange=callbacks.onChange||empty,_this=this;fabric.util.animate({startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(value){_this.setAngle(value);onChange()},onComplete:function(){_this.setCoords();onComplete()},onStart:function(){_this.set("active",false)}});return this}});fabric.util.object.extend(fabric.StaticCanvas.prototype,{straightenObject:function(object){object.straighten();this.renderAll();return this},fxStraightenObject:function(object){object.fxStraighten({onChange:this.renderAll.bind(this)});return this}});fabric.Image.filters=fabric.Image.filters||{};fabric.Image.filters.BaseFilter=fabric.util.createClass({type:"BaseFilter",initialize:function(options){if(options){this.setOptions(options)}},setOptions:function(options){for(var prop in options){this[prop]=options[prop]}},toObject:function(){return{type:this.type}},toJSON:function(){return this.toObject()}});fabric.Image.filters.BaseFilter.fromObject=function(object,callback){var filter=new fabric.Image.filters[object.type](object);callback&&callback(filter);return filter};(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Brightness=createClass(filters.BaseFilter,{type:"Brightness",initialize:function(options){options=options||{};this.brightness=options.brightness||0},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,brightness=this.brightness;for(var i=0,len=data.length;i<len;i+=4){data[i]+=brightness;data[i+1]+=brightness;data[i+2]+=brightness}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{brightness:this.brightness})}});fabric.Image.filters.Brightness.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Convolute=createClass(filters.BaseFilter,{type:"Convolute",initialize:function(options){options=options||{};this.opaque=options.opaque;this.matrix=options.matrix||[0,0,0,0,1,0,0,0,0]},applyTo:function(canvasEl){var weights=this.matrix,context=canvasEl.getContext("2d"),pixels=context.getImageData(0,0,canvasEl.width,canvasEl.height),side=Math.round(Math.sqrt(weights.length)),halfSide=Math.floor(side/2),src=pixels.data,sw=pixels.width,sh=pixels.height,output=context.createImageData(sw,sh),dst=output.data,alphaFac=this.opaque?1:0,r,g,b,a,dstOff,scx,scy,srcOff,wt;for(var y=0;y<sh;y++){for(var x=0;x<sw;x++){dstOff=(y*sw+x)*4;r=0;g=0;b=0;a=0;for(var cy=0;cy<side;cy++){for(var cx=0;cx<side;cx++){scy=y+cy-halfSide;scx=x+cx-halfSide;if(scy<0||scy>sh||scx<0||scx>sw){continue}srcOff=(scy*sw+scx)*4;wt=weights[cy*side+cx];r+=src[srcOff]*wt;g+=src[srcOff+1]*wt;b+=src[srcOff+2]*wt;a+=src[srcOff+3]*wt}}dst[dstOff]=r;dst[dstOff+1]=g;dst[dstOff+2]=b;dst[dstOff+3]=a+alphaFac*(255-a)}}context.putImageData(output,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}});fabric.Image.filters.Convolute.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.GradientTransparency=createClass(filters.BaseFilter,{type:"GradientTransparency",initialize:function(options){options=options||{};this.threshold=options.threshold||100},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,threshold=this.threshold,total=data.length;for(var i=0,len=data.length;i<len;i+=4){data[i+3]=threshold+255*(total-i)/total}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{threshold:this.threshold})}});fabric.Image.filters.GradientTransparency.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Grayscale=createClass(filters.BaseFilter,{type:"Grayscale",applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,len=imageData.width*imageData.height*4,index=0,average;while(index<len){average=(data[index]+data[index+1]+data[index+2])/3;data[index]=average;data[index+1]=average;data[index+2]=average;index+=4}context.putImageData(imageData,0,0)}});fabric.Image.filters.Grayscale.fromObject=function(object,callback){object=object||{};object.type="Grayscale";return fabric.Image.filters.BaseFilter.fromObject(object,callback)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Invert=createClass(filters.BaseFilter,{type:"Invert",applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i;for(i=0;i<iLen;i+=4){data[i]=255-data[i];data[i+1]=255-data[i+1];data[i+2]=255-data[i+2]}context.putImageData(imageData,0,0)}});fabric.Image.filters.Invert.fromObject=function(object,callback){object=object||{};object.type="Invert";return fabric.Image.filters.BaseFilter.fromObject(object,callback)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Mask=createClass(filters.BaseFilter,{type:"Mask",initialize:function(options){options=options||{};this.mask=options.mask;this.channel=[0,1,2,3].indexOf(options.channel)>-1?options.channel:0},applyTo:function(canvasEl){if(!this.mask){return}var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,maskEl=this.mask.getElement(),maskCanvasEl=fabric.util.createCanvasElement(),channel=this.channel,i,iLen=imageData.width*imageData.height*4;maskCanvasEl.width=canvasEl.width;maskCanvasEl.height=canvasEl.height;maskCanvasEl.getContext("2d").drawImage(maskEl,0,0,canvasEl.width,canvasEl.height);var maskImageData=maskCanvasEl.getContext("2d").getImageData(0,0,canvasEl.width,canvasEl.height),maskData=maskImageData.data;for(i=0;i<iLen;i+=4){data[i+3]=maskData[i+channel]}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{mask:this.mask.toObject(),channel:this.channel})}});fabric.Image.filters.Mask.fromObject=function(object,callback){fabric.util.loadImage(object.mask.src,function(img){object.mask=new fabric.Image(img,object.mask);return fabric.Image.filters.BaseFilter.fromObject(object,callback)})};fabric.Image.filters.Mask.async=true})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Noise=createClass(filters.BaseFilter,{type:"Noise",initialize:function(options){options=options||{};this.noise=options.noise||0},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,noise=this.noise,rand;for(var i=0,len=data.length;i<len;i+=4){rand=(.5-Math.random())*noise;data[i]+=rand;data[i+1]+=rand;data[i+2]+=rand}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{noise:this.noise})}});fabric.Image.filters.Noise.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Pixelate=createClass(filters.BaseFilter,{type:"Pixelate",initialize:function(options){options=options||{};this.blocksize=options.blocksize||4},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=imageData.height,jLen=imageData.width,index,i,j,r,g,b,a;for(i=0;i<iLen;i+=this.blocksize){for(j=0;j<jLen;j+=this.blocksize){index=i*4*jLen+j*4;r=data[index];g=data[index+1];b=data[index+2];a=data[index+3];for(var _i=i,_ilen=i+this.blocksize;_i<_ilen;_i++){for(var _j=j,_jlen=j+this.blocksize;_j<_jlen;_j++){index=_i*4*jLen+_j*4;data[index]=r;data[index+1]=g;data[index+2]=b;data[index+3]=a}}}}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{blocksize:this.blocksize})}});fabric.Image.filters.Pixelate.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.RemoveWhite=createClass(filters.BaseFilter,{type:"RemoveWhite",initialize:function(options){options=options||{};this.threshold=options.threshold||30;this.distance=options.distance||20},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,threshold=this.threshold,distance=this.distance,limit=255-threshold,abs=Math.abs,r,g,b;for(var i=0,len=data.length;i<len;i+=4){r=data[i];g=data[i+1];b=data[i+2];if(r>limit&&g>limit&&b>limit&&abs(r-g)<distance&&abs(r-b)<distance&&abs(g-b)<distance){data[i+3]=0}}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{threshold:this.threshold,distance:this.distance})}});fabric.Image.filters.RemoveWhite.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Sepia=createClass(filters.BaseFilter,{type:"Sepia",applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i,avg;for(i=0;i<iLen;i+=4){avg=.3*data[i]+.59*data[i+1]+.11*data[i+2];data[i]=avg+100;data[i+1]=avg+50;data[i+2]=avg+255}context.putImageData(imageData,0,0)}});fabric.Image.filters.Sepia.fromObject=function(object,callback){object=object||{};object.type="Sepia";return new fabric.Image.filters.BaseFilter.fromObject(object,callback)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Sepia2=createClass(filters.BaseFilter,{type:"Sepia2",applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i,r,g,b;for(i=0;i<iLen;i+=4){r=data[i];g=data[i+1];b=data[i+2];data[i]=(r*.393+g*.769+b*.189)/1.351;data[i+1]=(r*.349+g*.686+b*.168)/1.203;data[i+2]=(r*.272+g*.534+b*.131)/2.14}context.putImageData(imageData,0,0)}});fabric.Image.filters.Sepia2.fromObject=function(object,callback){object=object||{};object.type="Sepia2";return new fabric.Image.filters.BaseFilter.fromObject(object,callback)}})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Tint=createClass(filters.BaseFilter,{type:"Tint",initialize:function(options){options=options||{};this.color=options.color||"#000000";this.opacity=typeof options.opacity!=="undefined"?options.opacity:new fabric.Color(this.color).getAlpha()},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i,tintR,tintG,tintB,r,g,b,alpha1,source;source=new fabric.Color(this.color).getSource();tintR=source[0]*this.opacity;tintG=source[1]*this.opacity;tintB=source[2]*this.opacity;alpha1=1-this.opacity;for(i=0;i<iLen;i+=4){r=data[i];g=data[i+1];b=data[i+2];data[i]=tintR+r*alpha1;data[i+1]=tintG+g*alpha1;data[i+2]=tintB+b*alpha1}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{color:this.color,opacity:this.opacity})}});fabric.Image.filters.Tint.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Multiply=createClass(filters.BaseFilter,{type:"Multiply",initialize:function(options){options=options||{};this.color=options.color||"#000000"},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i,source;source=new fabric.Color(this.color).getSource();for(i=0;i<iLen;i+=4){data[i]*=source[0]/255;data[i+1]*=source[1]/255;data[i+2]*=source[2]/255}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{color:this.color})}});fabric.Image.filters.Multiply.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Blend=createClass(filters.BaseFilter,{type:"Blend",initialize:function(options){options=options||{};this.color=options.color||"#000";this.image=options.image||false;this.mode=options.mode||"multiply";this.alpha=options.alpha||1},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,tr,tg,tb,r,g,b,_r,_g,_b,source,isImage=false;if(this.image){isImage=true;var _el=fabric.util.createCanvasElement();_el.width=this.image.width;_el.height=this.image.height;var tmpCanvas=new fabric.StaticCanvas(_el);tmpCanvas.add(this.image);var context2=tmpCanvas.getContext("2d");source=context2.getImageData(0,0,tmpCanvas.width,tmpCanvas.height).data}else{source=new fabric.Color(this.color).getSource();tr=source[0]*this.alpha;tg=source[1]*this.alpha;tb=source[2]*this.alpha}for(var i=0,len=data.length;i<len;i+=4){r=data[i];g=data[i+1];b=data[i+2];if(isImage){tr=source[i]*this.alpha;tg=source[i+1]*this.alpha;tb=source[i+2]*this.alpha}switch(this.mode){case"multiply":data[i]=r*tr/255;data[i+1]=g*tg/255;data[i+2]=b*tb/255;break;case"screen":data[i]=1-(1-r)*(1-tr);data[i+1]=1-(1-g)*(1-tg);data[i+2]=1-(1-b)*(1-tb);break;case"add":data[i]=Math.min(255,r+tr);data[i+1]=Math.min(255,g+tg);data[i+2]=Math.min(255,b+tb);break;case"diff":case"difference":data[i]=Math.abs(r-tr);data[i+1]=Math.abs(g-tg);data[i+2]=Math.abs(b-tb);break;case"subtract":_r=r-tr;_g=g-tg;_b=b-tb;data[i]=_r<0?0:_r;data[i+1]=_g<0?0:_g;data[i+2]=_b<0?0:_b;break;case"darken":data[i]=Math.min(r,tr);data[i+1]=Math.min(g,tg);data[i+2]=Math.min(b,tb);break;case"lighten":data[i]=Math.max(r,tr);data[i+1]=Math.max(g,tg);data[i+2]=Math.max(b,tb);break}}context.putImageData(imageData,0,0)},toObject:function(){return{color:this.color,image:this.image,mode:this.mode,alpha:this.alpha}}});fabric.Image.filters.Blend.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),pow=Math.pow,floor=Math.floor,sqrt=Math.sqrt,abs=Math.abs,max=Math.max,round=Math.round,sin=Math.sin,ceil=Math.ceil,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Resize=createClass(filters.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:0,scaleY:0,lanczosLobes:3,applyTo:function(canvasEl,scaleX,scaleY){if(scaleX===1&&scaleY===1){return}this.rcpScaleX=1/scaleX;this.rcpScaleY=1/scaleY;var oW=canvasEl.width,oH=canvasEl.height,dW=round(oW*scaleX),dH=round(oH*scaleY),imageData;if(this.resizeType==="sliceHack"){imageData=this.sliceByTwo(canvasEl,oW,oH,dW,dH)}if(this.resizeType==="hermite"){imageData=this.hermiteFastResize(canvasEl,oW,oH,dW,dH)}if(this.resizeType==="bilinear"){imageData=this.bilinearFiltering(canvasEl,oW,oH,dW,dH)}if(this.resizeType==="lanczos"){imageData=this.lanczosResize(canvasEl,oW,oH,dW,dH)}canvasEl.width=dW;canvasEl.height=dH;canvasEl.getContext("2d").putImageData(imageData,0,0)},sliceByTwo:function(canvasEl,oW,oH,dW,dH){var context=canvasEl.getContext("2d"),imageData,multW=.5,multH=.5,signW=1,signH=1,doneW=false,doneH=false,stepW=oW,stepH=oH,tmpCanvas=fabric.util.createCanvasElement(),tmpCtx=tmpCanvas.getContext("2d");dW=floor(dW);dH=floor(dH);tmpCanvas.width=max(dW,oW);tmpCanvas.height=max(dH,oH);if(dW>oW){multW=2;signW=-1}if(dH>oH){multH=2;signH=-1}imageData=context.getImageData(0,0,oW,oH);canvasEl.width=max(dW,oW);canvasEl.height=max(dH,oH);
context.putImageData(imageData,0,0);while(!doneW||!doneH){oW=stepW;oH=stepH;if(dW*signW<floor(stepW*multW*signW)){stepW=floor(stepW*multW)}else{stepW=dW;doneW=true}if(dH*signH<floor(stepH*multH*signH)){stepH=floor(stepH*multH)}else{stepH=dH;doneH=true}imageData=context.getImageData(0,0,oW,oH);tmpCtx.putImageData(imageData,0,0);context.clearRect(0,0,stepW,stepH);context.drawImage(tmpCanvas,0,0,oW,oH,0,0,stepW,stepH)}return context.getImageData(0,0,dW,dH)},lanczosResize:function(canvasEl,oW,oH,dW,dH){function lanczosCreate(lobes){return function(x){if(x>lobes){return 0}x*=Math.PI;if(abs(x)<1e-16){return 1}var xx=x/lobes;return sin(x)*sin(xx)/x/xx}}function process(u){var v,i,weight,idx,a,red,green,blue,alpha,fX,fY;center.x=(u+.5)*ratioX;icenter.x=floor(center.x);for(v=0;v<dH;v++){center.y=(v+.5)*ratioY;icenter.y=floor(center.y);a=0;red=0;green=0;blue=0;alpha=0;for(i=icenter.x-range2X;i<=icenter.x+range2X;i++){if(i<0||i>=oW){continue}fX=floor(1e3*abs(i-center.x));if(!cacheLanc[fX]){cacheLanc[fX]={}}for(var j=icenter.y-range2Y;j<=icenter.y+range2Y;j++){if(j<0||j>=oH){continue}fY=floor(1e3*abs(j-center.y));if(!cacheLanc[fX][fY]){cacheLanc[fX][fY]=lanczos(sqrt(pow(fX*rcpRatioX,2)+pow(fY*rcpRatioY,2))/1e3)}weight=cacheLanc[fX][fY];if(weight>0){idx=(j*oW+i)*4;a+=weight;red+=weight*srcData[idx];green+=weight*srcData[idx+1];blue+=weight*srcData[idx+2];alpha+=weight*srcData[idx+3]}}}idx=(v*dW+u)*4;destData[idx]=red/a;destData[idx+1]=green/a;destData[idx+2]=blue/a;destData[idx+3]=alpha/a}if(++u<dW){return process(u)}else{return destImg}}var context=canvasEl.getContext("2d"),srcImg=context.getImageData(0,0,oW,oH),destImg=context.getImageData(0,0,dW,dH),srcData=srcImg.data,destData=destImg.data,lanczos=lanczosCreate(this.lanczosLobes),ratioX=this.rcpScaleX,ratioY=this.rcpScaleY,rcpRatioX=2/this.rcpScaleX,rcpRatioY=2/this.rcpScaleY,range2X=ceil(ratioX*this.lanczosLobes/2),range2Y=ceil(ratioY*this.lanczosLobes/2),cacheLanc={},center={},icenter={};return process(0)},bilinearFiltering:function(canvasEl,oW,oH,dW,dH){var a,b,c,d,x,y,i,j,xDiff,yDiff,chnl,color,offset=0,origPix,ratioX=this.rcpScaleX,ratioY=this.rcpScaleY,context=canvasEl.getContext("2d"),w4=4*(oW-1),img=context.getImageData(0,0,oW,oH),pixels=img.data,destImage=context.getImageData(0,0,dW,dH),destPixels=destImage.data;for(i=0;i<dH;i++){for(j=0;j<dW;j++){x=floor(ratioX*j);y=floor(ratioY*i);xDiff=ratioX*j-x;yDiff=ratioY*i-y;origPix=4*(y*oW+x);for(chnl=0;chnl<4;chnl++){a=pixels[origPix+chnl];b=pixels[origPix+4+chnl];c=pixels[origPix+w4+chnl];d=pixels[origPix+w4+4+chnl];color=a*(1-xDiff)*(1-yDiff)+b*xDiff*(1-yDiff)+c*yDiff*(1-xDiff)+d*xDiff*yDiff;destPixels[offset++]=color}}}return destImage},hermiteFastResize:function(canvasEl,oW,oH,dW,dH){var ratioW=this.rcpScaleX,ratioH=this.rcpScaleY,ratioWHalf=ceil(ratioW/2),ratioHHalf=ceil(ratioH/2),context=canvasEl.getContext("2d"),img=context.getImageData(0,0,oW,oH),data=img.data,img2=context.getImageData(0,0,dW,dH),data2=img2.data;for(var j=0;j<dH;j++){for(var i=0;i<dW;i++){var x2=(i+j*dW)*4,weight=0,weights=0,weightsAlpha=0,gxR=0,gxG=0,gxB=0,gxA=0,centerY=(j+.5)*ratioH;for(var yy=floor(j*ratioH);yy<(j+1)*ratioH;yy++){var dy=abs(centerY-(yy+.5))/ratioHHalf,centerX=(i+.5)*ratioW,w0=dy*dy;for(var xx=floor(i*ratioW);xx<(i+1)*ratioW;xx++){var dx=abs(centerX-(xx+.5))/ratioWHalf,w=sqrt(w0+dx*dx);if(w>1&&w<-1){continue}weight=2*w*w*w-3*w*w+1;if(weight>0){dx=4*(xx+yy*oW);gxA+=weight*data[dx+3];weightsAlpha+=weight;if(data[dx+3]<255){weight=weight*data[dx+3]/250}gxR+=weight*data[dx];gxG+=weight*data[dx+1];gxB+=weight*data[dx+2];weights+=weight}}}data2[x2]=gxR/weights;data2[x2+1]=gxG/weights;data2[x2+2]=gxB/weights;data2[x2+3]=gxA/weightsAlpha}}return img2},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}});fabric.Image.filters.Resize.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.ColorMatrix=createClass(filters.BaseFilter,{type:"ColorMatrix",initialize:function(options){options||(options={});this.matrix=options.matrix||[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,iLen=data.length,i,r,g,b,a,m=this.matrix;for(i=0;i<iLen;i+=4){r=data[i];g=data[i+1];b=data[i+2];a=data[i+3];data[i]=r*m[0]+g*m[1]+b*m[2]+a*m[3]+m[4];data[i+1]=r*m[5]+g*m[6]+b*m[7]+a*m[8]+m[9];data[i+2]=r*m[10]+g*m[11]+b*m[12]+a*m[13]+m[14];data[i+3]=r*m[15]+g*m[16]+b*m[17]+a*m[18]+m[19]}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{type:this.type,matrix:this.matrix})}});fabric.Image.filters.ColorMatrix.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Contrast=createClass(filters.BaseFilter,{type:"Contrast",initialize:function(options){options=options||{};this.contrast=options.contrast||0},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,contrastF=259*(this.contrast+255)/(255*(259-this.contrast));for(var i=0,len=data.length;i<len;i+=4){data[i]=contrastF*(data[i]-128)+128;data[i+1]=contrastF*(data[i+1]-128)+128;data[i+2]=contrastF*(data[i+2]-128)+128}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{contrast:this.contrast})}});fabric.Image.filters.Contrast.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),extend=fabric.util.object.extend,filters=fabric.Image.filters,createClass=fabric.util.createClass;filters.Saturate=createClass(filters.BaseFilter,{type:"Saturate",initialize:function(options){options=options||{};this.saturate=options.saturate||0},applyTo:function(canvasEl){var context=canvasEl.getContext("2d"),imageData=context.getImageData(0,0,canvasEl.width,canvasEl.height),data=imageData.data,max,adjust=-this.saturate*.01;for(var i=0,len=data.length;i<len;i+=4){max=Math.max(data[i],data[i+1],data[i+2]);data[i]+=max!==data[i]?(max-data[i])*adjust:0;data[i+1]+=max!==data[i+1]?(max-data[i+1])*adjust:0;data[i+2]+=max!==data[i+2]?(max-data[i+2])*adjust:0}context.putImageData(imageData,0,0)},toObject:function(){return extend(this.callSuper("toObject"),{saturate:this.saturate})}});fabric.Image.filters.Saturate.fromObject=fabric.Image.filters.BaseFilter.fromObject})(typeof exports!=="undefined"?exports:this);(function(global){"use strict";var fabric=global.fabric||(global.fabric={}),toFixed=fabric.util.toFixed,NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS,MIN_TEXT_WIDTH=2;if(fabric.Text){fabric.warn("fabric.Text is already defined");return}var stateProperties=fabric.Object.prototype.stateProperties.concat();stateProperties.push("fontFamily","fontWeight","fontSize","text","textDecoration","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing");var cacheProperties=fabric.Object.prototype.cacheProperties.concat();cacheProperties.push("fontFamily","fontWeight","fontSize","text","textDecoration","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing","styles");fabric.Text=fabric.util.createClass(fabric.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",textDecoration:"",textAlign:"left",fontStyle:"",lineHeight:1.16,textBackgroundColor:"",stateProperties:stateProperties,cacheProperties:cacheProperties,stroke:null,shadow:null,_fontSizeFraction:.25,_fontSizeMult:1.13,charSpacing:0,initialize:function(text,options){options=options||{};this.text=text;this.__skipDimension=true;this.callSuper("initialize",options);this.__skipDimension=false;this._initDimensions();this.setCoords();this.setupState({propertySet:"_dimensionAffectingProps"})},_initDimensions:function(ctx){if(this.__skipDimension){return}if(!ctx){ctx=fabric.util.createCanvasElement().getContext("2d");this._setTextStyles(ctx)}this._textLines=this._splitTextIntoLines();this._clearCache();this.width=this._getTextWidth(ctx)||this.cursorWidth||MIN_TEXT_WIDTH;this.height=this._getTextHeight(ctx)},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_getCacheCanvasDimensions:function(){var dim=this.callSuper("_getCacheCanvasDimensions");var fontSize=this.fontSize*2;dim.width+=fontSize*dim.zoomX;dim.height+=fontSize*dim.zoomY;return dim},_render:function(ctx){this._setTextStyles(ctx);if(this.group&&this.group.type==="path-group"){ctx.translate(this.left,this.top)}this._renderTextLinesBackground(ctx);this._renderText(ctx);this._renderTextDecoration(ctx)},_renderText:function(ctx){this._renderTextFill(ctx);this._renderTextStroke(ctx)},_setTextStyles:function(ctx){ctx.textBaseline="alphabetic";ctx.font=this._getFontDeclaration()},_getTextHeight:function(){return this._getHeightOfSingleLine()+(this._textLines.length-1)*this._getHeightOfLine()},_getTextWidth:function(ctx){var maxWidth=this._getLineWidth(ctx,0);for(var i=1,len=this._textLines.length;i<len;i++){var currentLineWidth=this._getLineWidth(ctx,i);if(currentLineWidth>maxWidth){maxWidth=currentLineWidth}}return maxWidth},_renderChars:function(method,ctx,chars,left,top){var shortM=method.slice(0,-4),_char,width;if(this[shortM].toLive){var offsetX=-this.width/2+this[shortM].offsetX||0,offsetY=-this.height/2+this[shortM].offsetY||0;ctx.save();ctx.translate(offsetX,offsetY);left-=offsetX;top-=offsetY}if(this.charSpacing!==0){var additionalSpace=this._getWidthOfCharSpacing();chars=chars.split("");for(var i=0,len=chars.length;i<len;i++){_char=chars[i];width=ctx.measureText(_char).width+additionalSpace;ctx[method](_char,left,top);left+=width>0?width:0}}else{ctx[method](chars,left,top)}this[shortM].toLive&&ctx.restore()},_renderTextLine:function(method,ctx,line,left,top,lineIndex){top-=this.fontSize*this._fontSizeFraction;var lineWidth=this._getLineWidth(ctx,lineIndex);if(this.textAlign!=="justify"||this.width<lineWidth){this._renderChars(method,ctx,line,left,top,lineIndex);return}var words=line.split(/\s+/),charOffset=0,wordsWidth=this._getWidthOfWords(ctx,words.join(" "),lineIndex,0),widthDiff=this.width-wordsWidth,numSpaces=words.length-1,spaceWidth=numSpaces>0?widthDiff/numSpaces:0,leftOffset=0,word;for(var i=0,len=words.length;i<len;i++){while(line[charOffset]===" "&&charOffset<line.length){charOffset++}word=words[i];this._renderChars(method,ctx,word,left+leftOffset,top,lineIndex,charOffset);leftOffset+=this._getWidthOfWords(ctx,word,lineIndex,charOffset)+spaceWidth;charOffset+=word.length}},_getWidthOfWords:function(ctx,word){var width=ctx.measureText(word).width,charCount,additionalSpace;if(this.charSpacing!==0){charCount=word.split("").length;additionalSpace=charCount*this._getWidthOfCharSpacing();width+=additionalSpace}return width>0?width:0},_getLeftOffset:function(){return-this.width/2},_getTopOffset:function(){return-this.height/2},isEmptyStyles:function(){return true},_renderTextCommon:function(ctx,method){var lineHeights=0,left=this._getLeftOffset(),top=this._getTopOffset();for(var i=0,len=this._textLines.length;i<len;i++){var heightOfLine=this._getHeightOfLine(ctx,i),maxHeight=heightOfLine/this.lineHeight,lineWidth=this._getLineWidth(ctx,i),leftOffset=this._getLineLeftOffset(lineWidth);this._renderTextLine(method,ctx,this._textLines[i],left+leftOffset,top+lineHeights+maxHeight,i);lineHeights+=heightOfLine}},_renderTextFill:function(ctx){if(!this.fill&&this.isEmptyStyles()){return}this._renderTextCommon(ctx,"fillText")},_renderTextStroke:function(ctx){if((!this.stroke||this.strokeWidth===0)&&this.isEmptyStyles()){return}if(this.shadow&&!this.shadow.affectStroke){this._removeShadow(ctx)}ctx.save();this._setLineDash(ctx,this.strokeDashArray);ctx.beginPath();this._renderTextCommon(ctx,"strokeText");ctx.closePath();ctx.restore()},_getHeightOfLine:function(){return this._getHeightOfSingleLine()*this.lineHeight},_getHeightOfSingleLine:function(){return this.fontSize*this._fontSizeMult},_renderTextLinesBackground:function(ctx){if(!this.textBackgroundColor){return}var lineTopOffset=0,heightOfLine,lineWidth,lineLeftOffset,originalFill=ctx.fillStyle;ctx.fillStyle=this.textBackgroundColor;for(var i=0,len=this._textLines.length;i<len;i++){heightOfLine=this._getHeightOfLine(ctx,i);lineWidth=this._getLineWidth(ctx,i);if(lineWidth>0){lineLeftOffset=this._getLineLeftOffset(lineWidth);ctx.fillRect(this._getLeftOffset()+lineLeftOffset,this._getTopOffset()+lineTopOffset,lineWidth,heightOfLine/this.lineHeight)}lineTopOffset+=heightOfLine}ctx.fillStyle=originalFill;this._removeShadow(ctx)},_getLineLeftOffset:function(lineWidth){if(this.textAlign==="center"){return(this.width-lineWidth)/2}if(this.textAlign==="right"){return this.width-lineWidth}return 0},_clearCache:function(){this.__lineWidths=[];this.__lineHeights=[]},_shouldClearDimensionCache:function(){var shouldClear=this._forceClearCache;shouldClear||(shouldClear=this.hasStateChanged("_dimensionAffectingProps"));if(shouldClear){this.saveState({propertySet:"_dimensionAffectingProps"});this.dirty=true}return shouldClear},_getLineWidth:function(ctx,lineIndex){if(this.__lineWidths[lineIndex]){return this.__lineWidths[lineIndex]===-1?this.width:this.__lineWidths[lineIndex]}var width,wordCount,line=this._textLines[lineIndex];if(line===""){width=0}else{width=this._measureLine(ctx,lineIndex)}this.__lineWidths[lineIndex]=width;if(width&&this.textAlign==="justify"){wordCount=line.split(/\s+/);if(wordCount.length>1){this.__lineWidths[lineIndex]=-1}}return width},_getWidthOfCharSpacing:function(){if(this.charSpacing!==0){return this.fontSize*this.charSpacing/1e3}return 0},_measureLine:function(ctx,lineIndex){var line=this._textLines[lineIndex],width=ctx.measureText(line).width,additionalSpace=0,charCount,finalWidth;if(this.charSpacing!==0){charCount=line.split("").length;additionalSpace=(charCount-1)*this._getWidthOfCharSpacing()}finalWidth=width+additionalSpace;return finalWidth>0?finalWidth:0},_renderTextDecoration:function(ctx){if(!this.textDecoration){return}var halfOfVerticalBox=this.height/2,_this=this,offsets=[];function renderLinesAtOffset(offsets){var i,lineHeight=0,len,j,oLen,lineWidth,lineLeftOffset,heightOfLine;for(i=0,len=_this._textLines.length;i<len;i++){lineWidth=_this._getLineWidth(ctx,i);lineLeftOffset=_this._getLineLeftOffset(lineWidth);heightOfLine=_this._getHeightOfLine(ctx,i);for(j=0,oLen=offsets.length;j<oLen;j++){ctx.fillRect(_this._getLeftOffset()+lineLeftOffset,lineHeight+(_this._fontSizeMult-1+offsets[j])*_this.fontSize-halfOfVerticalBox,lineWidth,_this.fontSize/15)}lineHeight+=heightOfLine}}if(this.textDecoration.indexOf("underline")>-1){offsets.push(.85)}if(this.textDecoration.indexOf("line-through")>-1){offsets.push(.43)}if(this.textDecoration.indexOf("overline")>-1){offsets.push(-.12)}if(offsets.length>0){renderLinesAtOffset(offsets)}},_getFontDeclaration:function(){return[fabric.isLikelyNode?this.fontWeight:this.fontStyle,fabric.isLikelyNode?this.fontStyle:this.fontWeight,this.fontSize+"px",fabric.isLikelyNode?'"'+this.fontFamily+'"':this.fontFamily].join(" ")},render:function(ctx,noTransform){if(!this.visible){return}if(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()){return}if(this._shouldClearDimensionCache()){this._setTextStyles(ctx);this._initDimensions(ctx)}this.callSuper("render",ctx,noTransform)},_splitTextIntoLines:function(){return this.text.split(this._reNewline)},toObject:function(propertiesToInclude){var additionalProperties=["text","fontSize","fontWeight","fontFamily","fontStyle","lineHeight","textDecoration","textAlign","textBackgroundColor","charSpacing"].concat(propertiesToInclude);return this.callSuper("toObject",additionalProperties)},toSVG:function(reviver){if(!this.ctx){this.ctx=fabric.util.createCanvasElement().getContext("2d")}var markup=this._createBaseSVGMarkup(),offsets=this._getSVGLeftTopOffsets(this.ctx),textAndBg=this._getSVGTextAndBg(offsets.textTop,offsets.textLeft);this._wrapSVGTextAndBg(markup,textAndBg);return reviver?reviver(markup.join("")):markup.join("")},_getSVGLeftTopOffsets:function(ctx){var lineTop=this._getHeightOfLine(ctx,0),textLeft=-this.width/2,textTop=0;return{textLeft:textLeft+(this.group&&this.group.type==="path-group"?this.left:0),textTop:textTop+(this.group&&this.group.type==="path-group"?-this.top:0),lineTop:lineTop}},_wrapSVGTextAndBg:function(markup,textAndBg){var noShadow=true,filter=this.getSvgFilter(),style=filter===""?"":' style="'+filter+'"';markup.push(" <g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"',style,">\n",textAndBg.textBgRects.join("")," <text ",this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",this.textDecoration?'text-decoration="'+this.textDecoration+'" ':"",'style="',this.getSvgStyles(noShadow),'" >\n',textAndBg.textSpans.join("")," </text>\n"," </g>\n")},_getSVGTextAndBg:function(textTopOffset,textLeftOffset){var textSpans=[],textBgRects=[],height=0;this._setSVGBg(textBgRects);for(var i=0,len=this._textLines.length;i<len;i++){if(this.textBackgroundColor){this._setSVGTextLineBg(textBgRects,i,textLeftOffset,textTopOffset,height)}this._setSVGTextLineText(i,textSpans,height,textLeftOffset,textTopOffset,textBgRects);height+=this._getHeightOfLine(this.ctx,i)}return{textSpans:textSpans,textBgRects:textBgRects}},_setSVGTextLineText:function(i,textSpans,height,textLeftOffset,textTopOffset){var yPos=this.fontSize*(this._fontSizeMult-this._fontSizeFraction)-textTopOffset+height-this.height/2;if(this.textAlign==="justify"){this._setSVGTextLineJustifed(i,textSpans,yPos,textLeftOffset);return}textSpans.push(' <tspan x="',toFixed(textLeftOffset+this._getLineLeftOffset(this._getLineWidth(this.ctx,i)),NUM_FRACTION_DIGITS),'" ','y="',toFixed(yPos,NUM_FRACTION_DIGITS),'" ',this._getFillAttributes(this.fill),">",fabric.util.string.escapeXml(this._textLines[i]),"</tspan>\n")},_setSVGTextLineJustifed:function(i,textSpans,yPos,textLeftOffset){var ctx=fabric.util.createCanvasElement().getContext("2d");this._setTextStyles(ctx);var line=this._textLines[i],words=line.split(/\s+/),wordsWidth=this._getWidthOfWords(ctx,words.join("")),widthDiff=this.width-wordsWidth,numSpaces=words.length-1,spaceWidth=numSpaces>0?widthDiff/numSpaces:0,word,attributes=this._getFillAttributes(this.fill),len;textLeftOffset+=this._getLineLeftOffset(this._getLineWidth(ctx,i));for(i=0,len=words.length;i<len;i++){word=words[i];textSpans.push(' <tspan x="',toFixed(textLeftOffset,NUM_FRACTION_DIGITS),'" ','y="',toFixed(yPos,NUM_FRACTION_DIGITS),'" ',attributes,">",fabric.util.string.escapeXml(word),"</tspan>\n");textLeftOffset+=this._getWidthOfWords(ctx,word)+spaceWidth}},_setSVGTextLineBg:function(textBgRects,i,textLeftOffset,textTopOffset,height){textBgRects.push(" <rect ",this._getFillAttributes(this.textBackgroundColor),' x="',toFixed(textLeftOffset+this._getLineLeftOffset(this._getLineWidth(this.ctx,i)),NUM_FRACTION_DIGITS),'" y="',toFixed(height-this.height/2,NUM_FRACTION_DIGITS),'" width="',toFixed(this._getLineWidth(this.ctx,i),NUM_FRACTION_DIGITS),'" height="',toFixed(this._getHeightOfLine(this.ctx,i)/this.lineHeight,NUM_FRACTION_DIGITS),'"></rect>\n')},_setSVGBg:function(textBgRects){if(this.backgroundColor){textBgRects.push(" <rect ",this._getFillAttributes(this.backgroundColor),' x="',toFixed(-this.width/2,NUM_FRACTION_DIGITS),'" y="',toFixed(-this.height/2,NUM_FRACTION_DIGITS),'" width="',toFixed(this.width,NUM_FRACTION_DIGITS),'" height="',toFixed(this.height,NUM_FRACTION_DIGITS),'"></rect>\n')}},_getFillAttributes:function(value){var fillColor=value&&typeof value==="string"?new fabric.Color(value):"";if(!fillColor||!fillColor.getSource()||fillColor.getAlpha()===1){return'fill="'+value+'"'}return'opacity="'+fillColor.getAlpha()+'" fill="'+fillColor.setAlpha(1).toRgb()+'"'},_set:function(key,value){this.callSuper("_set",key,value);if(this._dimensionAffectingProps.indexOf(key)>-1){this._initDimensions();this.setCoords()}},complexity:function(){return 1}});fabric.Text.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size text-decoration text-anchor".split(" "));fabric.Text.DEFAULT_SVG_FONT_SIZE=16;fabric.Text.fromElement=function(element,options){if(!element){return null}var parsedAttributes=fabric.parseAttributes(element,fabric.Text.ATTRIBUTE_NAMES);options=fabric.util.object.extend(options?fabric.util.object.clone(options):{},parsedAttributes);options.top=options.top||0;options.left=options.left||0;if("dx"in parsedAttributes){options.left+=parsedAttributes.dx}if("dy"in parsedAttributes){options.top+=parsedAttributes.dy}if(!("fontSize"in options)){options.fontSize=fabric.Text.DEFAULT_SVG_FONT_SIZE}if(!options.originX){options.originX="left"}var textContent="";if(!("textContent"in element)){if("firstChild"in element&&element.firstChild!==null){if("data"in element.firstChild&&element.firstChild.data!==null){textContent=element.firstChild.data}}}else{textContent=element.textContent}textContent=textContent.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var text=new fabric.Text(textContent,options),textHeightScaleFactor=text.getHeight()/text.height,lineHeightDiff=(text.height+text.strokeWidth)*text.lineHeight-text.height,scaledDiff=lineHeightDiff*textHeightScaleFactor,textHeight=text.getHeight()+scaledDiff,offX=0;if(text.originX==="left"){offX=text.getWidth()/2}if(text.originX==="right"){offX=-text.getWidth()/2}text.set({left:text.getLeft()+offX,top:text.getTop()-textHeight/2+text.fontSize*(.18+text._fontSizeFraction)/text.lineHeight});return text};fabric.Text.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Text",object,callback,forceAsync,"text")};fabric.util.createAccessors(fabric.Text)})(typeof exports!=="undefined"?exports:this);(function(){var clone=fabric.util.object.clone;fabric.IText=fabric.util.createClass(fabric.Text,fabric.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:false,editable:true,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"#333",cursorDelay:1e3,cursorDuration:600,styles:null,caching:true,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:false,__widthOfSpace:[],initialize:function(text,options){this.styles=options?options.styles||{}:{};this.callSuper("initialize",text,options);this.initBehavior()},_clearCache:function(){this.callSuper("_clearCache");this.__widthOfSpace=[]},isEmptyStyles:function(){if(!this.styles){return true}var obj=this.styles;for(var p1 in obj){for(var p2 in obj[p1]){for(var p3 in obj[p1][p2]){return false}}}return true},setSelectionStart:function(index){index=Math.max(index,0);this._updateAndFire("selectionStart",index)},setSelectionEnd:function(index){index=Math.min(index,this.text.length);this._updateAndFire("selectionEnd",index)},_updateAndFire:function(property,index){if(this[property]!==index){this._fireSelectionChanged();this[property]=index}this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed");this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},getSelectionStyles:function(startIndex,endIndex){if(arguments.length===2){var styles=[];for(var i=startIndex;i<endIndex;i++){styles.push(this.getSelectionStyles(i))}return styles}var loc=this.get2DCursorLocation(startIndex),style=this._getStyleDeclaration(loc.lineIndex,loc.charIndex);return style||{}},setSelectionStyles:function(styles){if(this.selectionStart===this.selectionEnd){this._extendStyles(this.selectionStart,styles)}else{for(var i=this.selectionStart;i<this.selectionEnd;i++){this._extendStyles(i,styles)}}this._forceClearCache=true;return this},_extendStyles:function(index,styles){var loc=this.get2DCursorLocation(index);if(!this._getLineStyle(loc.lineIndex)){this._setLineStyle(loc.lineIndex,{})}if(!this._getStyleDeclaration(loc.lineIndex,loc.charIndex)){this._setStyleDeclaration(loc.lineIndex,loc.charIndex,{})}fabric.util.object.extend(this._getStyleDeclaration(loc.lineIndex,loc.charIndex),styles)},_initDimensions:function(ctx){if(!ctx){this.clearContextTop()}this.callSuper("_initDimensions",ctx)},render:function(ctx,noTransform){this.clearContextTop();this.callSuper("render",ctx,noTransform);this.cursorOffsetCache={};this.renderCursorOrSelection()},_render:function(ctx){this.callSuper("_render",ctx);this.ctx=ctx},clearContextTop:function(){if(!this.active||!this.isEditing){return}if(this.canvas&&this.canvas.contextTop){var ctx=this.canvas.contextTop;ctx.save();ctx.transform.apply(ctx,this.canvas.viewportTransform);this.transform(ctx);this.transformMatrix&&ctx.transform.apply(ctx,this.transformMatrix);this._clearTextArea(ctx);ctx.restore()}},renderCursorOrSelection:function(){if(!this.active||!this.isEditing){return}var chars=this.text.split(""),boundaries,ctx;if(this.canvas&&this.canvas.contextTop){ctx=this.canvas.contextTop;ctx.save();ctx.transform.apply(ctx,this.canvas.viewportTransform);this.transform(ctx);this.transformMatrix&&ctx.transform.apply(ctx,this.transformMatrix);this._clearTextArea(ctx)}else{ctx=this.ctx;ctx.save()}if(this.selectionStart===this.selectionEnd){boundaries=this._getCursorBoundaries(chars,"cursor");this.renderCursor(boundaries,ctx)}else{boundaries=this._getCursorBoundaries(chars,"selection");this.renderSelection(chars,boundaries,ctx)}ctx.restore()},_clearTextArea:function(ctx){var width=this.width+4,height=this.height+4;ctx.clearRect(-width/2,-height/2,width,height)},get2DCursorLocation:function(selectionStart){if(typeof selectionStart==="undefined"){selectionStart=this.selectionStart}var len=this._textLines.length;for(var i=0;i<len;i++){if(selectionStart<=this._textLines[i].length){return{lineIndex:i,charIndex:selectionStart}}selectionStart-=this._textLines[i].length+1}return{lineIndex:i-1,charIndex:this._textLines[i-1].length<selectionStart?this._textLines[i-1].length:selectionStart}},getCurrentCharStyle:function(lineIndex,charIndex){var style=this._getStyleDeclaration(lineIndex,charIndex===0?0:charIndex-1);return{fontSize:style&&style.fontSize||this.fontSize,fill:style&&style.fill||this.fill,textBackgroundColor:style&&style.textBackgroundColor||this.textBackgroundColor,textDecoration:style&&style.textDecoration||this.textDecoration,fontFamily:style&&style.fontFamily||this.fontFamily,fontWeight:style&&style.fontWeight||this.fontWeight,fontStyle:style&&style.fontStyle||this.fontStyle,stroke:style&&style.stroke||this.stroke,strokeWidth:style&&style.strokeWidth||this.strokeWidth}},getCurrentCharFontSize:function(lineIndex,charIndex){var style=this._getStyleDeclaration(lineIndex,charIndex===0?0:charIndex-1);return style&&style.fontSize?style.fontSize:this.fontSize},getCurrentCharColor:function(lineIndex,charIndex){var style=this._getStyleDeclaration(lineIndex,charIndex===0?0:charIndex-1);return style&&style.fill?style.fill:this.cursorColor},_getCursorBoundaries:function(chars,typeOfBoundaries){var left=Math.round(this._getLeftOffset()),top=this._getTopOffset(),offsets=this._getCursorBoundariesOffsets(chars,typeOfBoundaries);return{left:left,top:top,leftOffset:offsets.left+offsets.lineLeft,topOffset:offsets.top}},_getCursorBoundariesOffsets:function(chars,typeOfBoundaries){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache){return this.cursorOffsetCache}var lineLeftOffset=0,lineIndex=0,charIndex=0,topOffset=0,leftOffset=0,boundaries;for(var i=0;i<this.selectionStart;i++){if(chars[i]==="\n"){leftOffset=0;topOffset+=this._getHeightOfLine(this.ctx,lineIndex);lineIndex++;charIndex=0}else{leftOffset+=this._getWidthOfChar(this.ctx,chars[i],lineIndex,charIndex);charIndex++}lineLeftOffset=this._getLineLeftOffset(this._getLineWidth(this.ctx,lineIndex))}if(typeOfBoundaries==="cursor"){topOffset+=(1-this._fontSizeFraction)*this._getHeightOfLine(this.ctx,lineIndex)/this.lineHeight-this.getCurrentCharFontSize(lineIndex,charIndex)*(1-this._fontSizeFraction)}if(this.charSpacing!==0&&charIndex===this._textLines[lineIndex].length){leftOffset-=this._getWidthOfCharSpacing()}boundaries={top:topOffset,left:leftOffset>0?leftOffset:0,lineLeft:lineLeftOffset};this.cursorOffsetCache=boundaries;return this.cursorOffsetCache},renderCursor:function(boundaries,ctx){var cursorLocation=this.get2DCursorLocation(),lineIndex=cursorLocation.lineIndex,charIndex=cursorLocation.charIndex,charHeight=this.getCurrentCharFontSize(lineIndex,charIndex),leftOffset=boundaries.leftOffset,multiplier=this.scaleX*this.canvas.getZoom(),cursorWidth=this.cursorWidth/multiplier;ctx.fillStyle=this.getCurrentCharColor(lineIndex,charIndex);ctx.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity;ctx.fillRect(boundaries.left+leftOffset-cursorWidth/2,boundaries.top+boundaries.topOffset,cursorWidth,charHeight)},renderSelection:function(chars,boundaries,ctx){ctx.fillStyle=this.selectionColor;var start=this.get2DCursorLocation(this.selectionStart),end=this.get2DCursorLocation(this.selectionEnd),startLine=start.lineIndex,endLine=end.lineIndex;for(var i=startLine;i<=endLine;i++){var lineOffset=this._getLineLeftOffset(this._getLineWidth(ctx,i))||0,lineHeight=this._getHeightOfLine(this.ctx,i),realLineHeight=0,boxWidth=0,line=this._textLines[i];if(i===startLine){for(var j=0,len=line.length;j<len;j++){if(j>=start.charIndex&&(i!==endLine||j<end.charIndex)){boxWidth+=this._getWidthOfChar(ctx,line[j],i,j)}if(j<start.charIndex){lineOffset+=this._getWidthOfChar(ctx,line[j],i,j)}}if(j===line.length){boxWidth-=this._getWidthOfCharSpacing()}}else if(i>startLine&&i<endLine){boxWidth+=this._getLineWidth(ctx,i)||5}else if(i===endLine){for(var j2=0,j2len=end.charIndex;j2<j2len;j2++){boxWidth+=this._getWidthOfChar(ctx,line[j2],i,j2)}if(end.charIndex===line.length){boxWidth-=this._getWidthOfCharSpacing()}}realLineHeight=lineHeight;if(this.lineHeight<1||i===endLine&&this.lineHeight>1){lineHeight/=this.lineHeight}ctx.fillRect(boundaries.left+lineOffset,boundaries.top+boundaries.topOffset,boxWidth>0?boxWidth:0,lineHeight);boundaries.topOffset+=realLineHeight}},_renderChars:function(method,ctx,line,left,top,lineIndex,charOffset){if(this.isEmptyStyles()){return this._renderCharsFast(method,ctx,line,left,top)}charOffset=charOffset||0;var lineHeight=this._getHeightOfLine(ctx,lineIndex),prevStyle,thisStyle,charsToRender="";ctx.save();top-=lineHeight/this.lineHeight*this._fontSizeFraction;for(var i=charOffset,len=line.length+charOffset;i<=len;i++){prevStyle=prevStyle||this.getCurrentCharStyle(lineIndex,i);thisStyle=this.getCurrentCharStyle(lineIndex,i+1);if(this._hasStyleChanged(prevStyle,thisStyle)||i===len){this._renderChar(method,ctx,lineIndex,i-1,charsToRender,left,top,lineHeight);charsToRender="";prevStyle=thisStyle}charsToRender+=line[i-charOffset]}ctx.restore()},_renderCharsFast:function(method,ctx,line,left,top){if(method==="fillText"&&this.fill){this.callSuper("_renderChars",method,ctx,line,left,top)}if(method==="strokeText"&&(this.stroke&&this.strokeWidth>0||this.skipFillStrokeCheck)){this.callSuper("_renderChars",method,ctx,line,left,top)}},_renderChar:function(method,ctx,lineIndex,i,_char,left,top,lineHeight){var charWidth,charHeight,shouldFill,shouldStroke,decl=this._getStyleDeclaration(lineIndex,i),offset,textDecoration,chars,additionalSpace,_charWidth;
if(decl){charHeight=this._getHeightOfChar(ctx,_char,lineIndex,i);shouldStroke=decl.stroke;shouldFill=decl.fill;textDecoration=decl.textDecoration}else{charHeight=this.fontSize}shouldStroke=(shouldStroke||this.stroke)&&method==="strokeText";shouldFill=(shouldFill||this.fill)&&method==="fillText";decl&&ctx.save();charWidth=this._applyCharStylesGetWidth(ctx,_char,lineIndex,i,decl||null);textDecoration=textDecoration||this.textDecoration;if(decl&&decl.textBackgroundColor){this._removeShadow(ctx)}if(this.charSpacing!==0){additionalSpace=this._getWidthOfCharSpacing();chars=_char.split("");charWidth=0;for(var j=0,len=chars.length,jChar;j<len;j++){jChar=chars[j];shouldFill&&ctx.fillText(jChar,left+charWidth,top);shouldStroke&&ctx.strokeText(jChar,left+charWidth,top);_charWidth=ctx.measureText(jChar).width+additionalSpace;charWidth+=_charWidth>0?_charWidth:0}}else{shouldFill&&ctx.fillText(_char,left,top);shouldStroke&&ctx.strokeText(_char,left,top)}if(textDecoration||textDecoration!==""){offset=this._fontSizeFraction*lineHeight/this.lineHeight;this._renderCharDecoration(ctx,textDecoration,left,top,offset,charWidth,charHeight)}decl&&ctx.restore();ctx.translate(charWidth,0)},_hasStyleChanged:function(prevStyle,thisStyle){return prevStyle.fill!==thisStyle.fill||prevStyle.fontSize!==thisStyle.fontSize||prevStyle.textBackgroundColor!==thisStyle.textBackgroundColor||prevStyle.textDecoration!==thisStyle.textDecoration||prevStyle.fontFamily!==thisStyle.fontFamily||prevStyle.fontWeight!==thisStyle.fontWeight||prevStyle.fontStyle!==thisStyle.fontStyle||prevStyle.stroke!==thisStyle.stroke||prevStyle.strokeWidth!==thisStyle.strokeWidth},_renderCharDecoration:function(ctx,textDecoration,left,top,offset,charWidth,charHeight){if(!textDecoration){return}var decorationWeight=charHeight/15,positions={underline:top+charHeight/10,"line-through":top-charHeight*(this._fontSizeFraction+this._fontSizeMult-1)+decorationWeight,overline:top-(this._fontSizeMult-this._fontSizeFraction)*charHeight},decorations=["underline","line-through","overline"],i,decoration;for(i=0;i<decorations.length;i++){decoration=decorations[i];if(textDecoration.indexOf(decoration)>-1){ctx.fillRect(left,positions[decoration],charWidth,decorationWeight)}}},_renderTextLine:function(method,ctx,line,left,top,lineIndex){if(!this.isEmptyStyles()){top+=this.fontSize*(this._fontSizeFraction+.03)}this.callSuper("_renderTextLine",method,ctx,line,left,top,lineIndex)},_renderTextDecoration:function(ctx){if(this.isEmptyStyles()){return this.callSuper("_renderTextDecoration",ctx)}},_renderTextLinesBackground:function(ctx){this.callSuper("_renderTextLinesBackground",ctx);var lineTopOffset=0,heightOfLine,lineWidth,lineLeftOffset,leftOffset=this._getLeftOffset(),topOffset=this._getTopOffset(),colorCache="",line,_char,style,leftCache,topCache,widthCache,heightCache;ctx.save();for(var i=0,len=this._textLines.length;i<len;i++){heightOfLine=this._getHeightOfLine(ctx,i);line=this._textLines[i];if(line===""||!this.styles||!this._getLineStyle(i)){lineTopOffset+=heightOfLine;continue}lineWidth=this._getLineWidth(ctx,i);lineLeftOffset=this._getLineLeftOffset(lineWidth);leftCache=topCache=widthCache=heightCache=0;for(var j=0,jlen=line.length;j<jlen;j++){style=this._getStyleDeclaration(i,j)||{};if(colorCache!==style.textBackgroundColor){if(heightCache&&widthCache){ctx.fillStyle=colorCache;ctx.fillRect(leftCache,topCache,widthCache,heightCache)}leftCache=topCache=widthCache=heightCache=0;colorCache=style.textBackgroundColor||""}if(!style.textBackgroundColor){colorCache="";continue}_char=line[j];if(colorCache===style.textBackgroundColor){colorCache=style.textBackgroundColor;if(!leftCache){leftCache=leftOffset+lineLeftOffset+this._getWidthOfCharsAt(ctx,i,j)}topCache=topOffset+lineTopOffset;widthCache+=this._getWidthOfChar(ctx,_char,i,j);heightCache=heightOfLine/this.lineHeight}}if(heightCache&&widthCache){ctx.fillStyle=colorCache;ctx.fillRect(leftCache,topCache,widthCache,heightCache);leftCache=topCache=widthCache=heightCache=0}lineTopOffset+=heightOfLine}ctx.restore()},_getCacheProp:function(_char,styleDeclaration){return _char+styleDeclaration.fontSize+styleDeclaration.fontWeight+styleDeclaration.fontStyle},_getFontCache:function(fontFamily){if(!fabric.charWidthsCache[fontFamily]){fabric.charWidthsCache[fontFamily]={}}return fabric.charWidthsCache[fontFamily]},_applyCharStylesGetWidth:function(ctx,_char,lineIndex,charIndex,decl){var charDecl=decl||this._getStyleDeclaration(lineIndex,charIndex),styleDeclaration=clone(charDecl),width,cacheProp,charWidthsCache;this._applyFontStyles(styleDeclaration);charWidthsCache=this._getFontCache(styleDeclaration.fontFamily);cacheProp=this._getCacheProp(_char,styleDeclaration);if(!charDecl&&charWidthsCache[cacheProp]&&this.caching){return charWidthsCache[cacheProp]}if(typeof styleDeclaration.shadow==="string"){styleDeclaration.shadow=new fabric.Shadow(styleDeclaration.shadow)}var fill=styleDeclaration.fill||this.fill;ctx.fillStyle=fill.toLive?fill.toLive(ctx,this):fill;if(styleDeclaration.stroke){ctx.strokeStyle=styleDeclaration.stroke&&styleDeclaration.stroke.toLive?styleDeclaration.stroke.toLive(ctx,this):styleDeclaration.stroke}ctx.lineWidth=styleDeclaration.strokeWidth||this.strokeWidth;ctx.font=this._getFontDeclaration.call(styleDeclaration);if(styleDeclaration.shadow){styleDeclaration.scaleX=this.scaleX;styleDeclaration.scaleY=this.scaleY;styleDeclaration.canvas=this.canvas;styleDeclaration.getObjectScaling=this.getObjectScaling;this._setShadow.call(styleDeclaration,ctx)}if(!this.caching||!charWidthsCache[cacheProp]){width=ctx.measureText(_char).width;this.caching&&(charWidthsCache[cacheProp]=width);return width}return charWidthsCache[cacheProp]},_applyFontStyles:function(styleDeclaration){if(!styleDeclaration.fontFamily){styleDeclaration.fontFamily=this.fontFamily}if(!styleDeclaration.fontSize){styleDeclaration.fontSize=this.fontSize}if(!styleDeclaration.fontWeight){styleDeclaration.fontWeight=this.fontWeight}if(!styleDeclaration.fontStyle){styleDeclaration.fontStyle=this.fontStyle}},_getStyleDeclaration:function(lineIndex,charIndex,returnCloneOrEmpty){if(returnCloneOrEmpty){return this.styles[lineIndex]&&this.styles[lineIndex][charIndex]?clone(this.styles[lineIndex][charIndex]):{}}return this.styles[lineIndex]&&this.styles[lineIndex][charIndex]?this.styles[lineIndex][charIndex]:null},_setStyleDeclaration:function(lineIndex,charIndex,style){this.styles[lineIndex][charIndex]=style},_deleteStyleDeclaration:function(lineIndex,charIndex){delete this.styles[lineIndex][charIndex]},_getLineStyle:function(lineIndex){return this.styles[lineIndex]},_setLineStyle:function(lineIndex,style){this.styles[lineIndex]=style},_deleteLineStyle:function(lineIndex){delete this.styles[lineIndex]},_getWidthOfChar:function(ctx,_char,lineIndex,charIndex){if(!this._isMeasuring&&this.textAlign==="justify"&&this._reSpacesAndTabs.test(_char)){return this._getWidthOfSpace(ctx,lineIndex)}ctx.save();var width=this._applyCharStylesGetWidth(ctx,_char,lineIndex,charIndex);if(this.charSpacing!==0){width+=this._getWidthOfCharSpacing()}ctx.restore();return width>0?width:0},_getHeightOfChar:function(ctx,lineIndex,charIndex){var style=this._getStyleDeclaration(lineIndex,charIndex);return style&&style.fontSize?style.fontSize:this.fontSize},_getWidthOfCharsAt:function(ctx,lineIndex,charIndex){var width=0,i,_char;for(i=0;i<charIndex;i++){_char=this._textLines[lineIndex][i];width+=this._getWidthOfChar(ctx,_char,lineIndex,i)}return width},_measureLine:function(ctx,lineIndex){this._isMeasuring=true;var width=this._getWidthOfCharsAt(ctx,lineIndex,this._textLines[lineIndex].length);if(this.charSpacing!==0){width-=this._getWidthOfCharSpacing()}this._isMeasuring=false;return width>0?width:0},_getWidthOfSpace:function(ctx,lineIndex){if(this.__widthOfSpace[lineIndex]){return this.__widthOfSpace[lineIndex]}var line=this._textLines[lineIndex],wordsWidth=this._getWidthOfWords(ctx,line,lineIndex,0),widthDiff=this.width-wordsWidth,numSpaces=line.length-line.replace(this._reSpacesAndTabs,"").length,width=Math.max(widthDiff/numSpaces,ctx.measureText(" ").width);this.__widthOfSpace[lineIndex]=width;return width},_getWidthOfWords:function(ctx,line,lineIndex,charOffset){var width=0;for(var charIndex=0;charIndex<line.length;charIndex++){var _char=line[charIndex];if(!_char.match(/\s/)){width+=this._getWidthOfChar(ctx,_char,lineIndex,charIndex+charOffset)}}return width},_getHeightOfLine:function(ctx,lineIndex){if(this.__lineHeights[lineIndex]){return this.__lineHeights[lineIndex]}var line=this._textLines[lineIndex],maxHeight=this._getHeightOfChar(ctx,lineIndex,0);for(var i=1,len=line.length;i<len;i++){var currentCharHeight=this._getHeightOfChar(ctx,lineIndex,i);if(currentCharHeight>maxHeight){maxHeight=currentCharHeight}}this.__lineHeights[lineIndex]=maxHeight*this.lineHeight*this._fontSizeMult;return this.__lineHeights[lineIndex]},_getTextHeight:function(ctx){var lineHeight,height=0;for(var i=0,len=this._textLines.length;i<len;i++){lineHeight=this._getHeightOfLine(ctx,i);height+=i===len-1?lineHeight/this.lineHeight:lineHeight}return height},toObject:function(propertiesToInclude){return fabric.util.object.extend(this.callSuper("toObject",propertiesToInclude),{styles:clone(this.styles,true)})}});fabric.IText.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("IText",object,callback,forceAsync,"text")}})();(function(){var clone=fabric.util.object.clone;fabric.util.object.extend(fabric.IText.prototype,{initBehavior:function(){this.initAddedHandler();this.initRemovedHandler();this.initCursorSelectionHandlers();this.initDoubleClickSimulation();this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing();this.selected=false;this.callSuper("onDeselect")},initAddedHandler:function(){var _this=this;this.on("added",function(){var canvas=_this.canvas;if(canvas){if(!canvas._hasITextHandlers){canvas._hasITextHandlers=true;_this._initCanvasHandlers(canvas)}canvas._iTextInstances=canvas._iTextInstances||[];canvas._iTextInstances.push(_this)}})},initRemovedHandler:function(){var _this=this;this.on("removed",function(){var canvas=_this.canvas;if(canvas){canvas._iTextInstances=canvas._iTextInstances||[];fabric.util.removeFromArray(canvas._iTextInstances,_this);if(canvas._iTextInstances.length===0){canvas._hasITextHandlers=false;_this._removeCanvasHandlers(canvas)}}})},_initCanvasHandlers:function(canvas){canvas._mouseUpITextHandler=function(){if(canvas._iTextInstances){canvas._iTextInstances.forEach(function(obj){obj.__isMousedown=false})}}.bind(this);canvas.on("mouse:up",canvas._mouseUpITextHandler)},_removeCanvasHandlers:function(canvas){canvas.off("mouse:up",canvas._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(obj,targetOpacity,duration,completeMethod){var tickState;tickState={isAborted:false,abort:function(){this.isAborted=true}};obj.animate("_currentCursorOpacity",targetOpacity,{duration:duration,onComplete:function(){if(!tickState.isAborted){obj[completeMethod]()}},onChange:function(){if(obj.canvas&&obj.selectionStart===obj.selectionEnd){obj.renderCursorOrSelection()}},abort:function(){return tickState.isAborted}});return tickState},_onTickComplete:function(){var _this=this;if(this._cursorTimeout1){clearTimeout(this._cursorTimeout1)}this._cursorTimeout1=setTimeout(function(){_this._currentTickCompleteState=_this._animateCursor(_this,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(restart){var _this=this,delay=restart?0:this.cursorDelay;this.abortCursorAnimation();this._currentCursorOpacity=1;this._cursorTimeout2=setTimeout(function(){_this._tick()},delay)},abortCursorAnimation:function(){var shouldClear=this._currentTickState||this._currentTickCompleteState;this._currentTickState&&this._currentTickState.abort();this._currentTickCompleteState&&this._currentTickCompleteState.abort();clearTimeout(this._cursorTimeout1);clearTimeout(this._cursorTimeout2);this._currentCursorOpacity=0;if(shouldClear){this.canvas&&this.canvas.clearContext(this.canvas.contextTop||this.ctx)}},selectAll:function(){this.selectionStart=0;this.selectionEnd=this.text.length;this._fireSelectionChanged();this._updateTextarea()},getSelectedText:function(){return this.text.slice(this.selectionStart,this.selectionEnd)},findWordBoundaryLeft:function(startFrom){var offset=0,index=startFrom-1;if(this._reSpace.test(this.text.charAt(index))){while(this._reSpace.test(this.text.charAt(index))){offset++;index--}}while(/\S/.test(this.text.charAt(index))&&index>-1){offset++;index--}return startFrom-offset},findWordBoundaryRight:function(startFrom){var offset=0,index=startFrom;if(this._reSpace.test(this.text.charAt(index))){while(this._reSpace.test(this.text.charAt(index))){offset++;index++}}while(/\S/.test(this.text.charAt(index))&&index<this.text.length){offset++;index++}return startFrom+offset},findLineBoundaryLeft:function(startFrom){var offset=0,index=startFrom-1;while(!/\n/.test(this.text.charAt(index))&&index>-1){offset++;index--}return startFrom-offset},findLineBoundaryRight:function(startFrom){var offset=0,index=startFrom;while(!/\n/.test(this.text.charAt(index))&&index<this.text.length){offset++;index++}return startFrom+offset},getNumNewLinesInSelectedText:function(){var selectedText=this.getSelectedText(),numNewLines=0;for(var i=0,len=selectedText.length;i<len;i++){if(selectedText[i]==="\n"){numNewLines++}}return numNewLines},searchWordBoundary:function(selectionStart,direction){var index=this._reSpace.test(this.text.charAt(selectionStart))?selectionStart-1:selectionStart,_char=this.text.charAt(index),reNonWord=/[ \n\.,;!\?\-]/;while(!reNonWord.test(_char)&&index>0&&index<this.text.length){index+=direction;_char=this.text.charAt(index)}if(reNonWord.test(_char)&&_char!=="\n"){index+=direction===1?0:1}return index},selectWord:function(selectionStart){selectionStart=selectionStart||this.selectionStart;var newSelectionStart=this.searchWordBoundary(selectionStart,-1),newSelectionEnd=this.searchWordBoundary(selectionStart,1);this.selectionStart=newSelectionStart;this.selectionEnd=newSelectionEnd;this._fireSelectionChanged();this._updateTextarea();this.renderCursorOrSelection()},selectLine:function(selectionStart){selectionStart=selectionStart||this.selectionStart;var newSelectionStart=this.findLineBoundaryLeft(selectionStart),newSelectionEnd=this.findLineBoundaryRight(selectionStart);this.selectionStart=newSelectionStart;this.selectionEnd=newSelectionEnd;this._fireSelectionChanged();this._updateTextarea()},enterEditing:function(e){if(this.isEditing||!this.editable){return}if(this.canvas){this.exitEditingOnOthers(this.canvas)}this.isEditing=true;this.selected=true;this.initHiddenTextarea(e);this.hiddenTextarea.focus();this._updateTextarea();this._saveEditingProps();this._setEditingProps();this._textBeforeEdit=this.text;this._tick();this.fire("editing:entered");this._fireSelectionChanged();if(!this.canvas){return this}this.canvas.fire("text:editing:entered",{target:this});this.initMouseMoveHandler();this.canvas.renderAll();return this},exitEditingOnOthers:function(canvas){if(canvas._iTextInstances){canvas._iTextInstances.forEach(function(obj){obj.selected=false;if(obj.isEditing){obj.exitEditing()}})}},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(options){if(!this.__isMousedown||!this.isEditing){return}var newSelectionStart=this.getSelectionStartFromPointer(options.e),currentStart=this.selectionStart,currentEnd=this.selectionEnd;if((newSelectionStart!==this.__selectionStartOnMouseDown||currentStart===currentEnd)&&(currentStart===newSelectionStart||currentEnd===newSelectionStart)){return}if(newSelectionStart>this.__selectionStartOnMouseDown){this.selectionStart=this.__selectionStartOnMouseDown;this.selectionEnd=newSelectionStart}else{this.selectionStart=newSelectionStart;this.selectionEnd=this.__selectionStartOnMouseDown}if(this.selectionStart!==currentStart||this.selectionEnd!==currentEnd){this.restartCursorIfNeeded();this._fireSelectionChanged();this._updateTextarea();this.renderCursorOrSelection()}},_setEditingProps:function(){this.hoverCursor="text";if(this.canvas){this.canvas.defaultCursor=this.canvas.moveCursor="text"}this.borderColor=this.editingBorderColor;this.hasControls=this.selectable=false;this.lockMovementX=this.lockMovementY=true},_updateTextarea:function(){if(!this.hiddenTextarea||this.inCompositionMode){return}this.cursorOffsetCache={};this.hiddenTextarea.value=this.text;this.hiddenTextarea.selectionStart=this.selectionStart;this.hiddenTextarea.selectionEnd=this.selectionEnd;if(this.selectionStart===this.selectionEnd){var style=this._calcTextareaPosition();this.hiddenTextarea.style.left=style.left;this.hiddenTextarea.style.top=style.top;this.hiddenTextarea.style.fontSize=style.fontSize}},_calcTextareaPosition:function(){if(!this.canvas){return{x:1,y:1}}var chars=this.text.split(""),boundaries=this._getCursorBoundaries(chars,"cursor"),cursorLocation=this.get2DCursorLocation(),lineIndex=cursorLocation.lineIndex,charIndex=cursorLocation.charIndex,charHeight=this.getCurrentCharFontSize(lineIndex,charIndex),leftOffset=boundaries.leftOffset,m=this.calcTransformMatrix(),p={x:boundaries.left+leftOffset,y:boundaries.top+boundaries.topOffset+charHeight},upperCanvas=this.canvas.upperCanvasEl,maxWidth=upperCanvas.width-charHeight,maxHeight=upperCanvas.height-charHeight;p=fabric.util.transformPoint(p,m);p=fabric.util.transformPoint(p,this.canvas.viewportTransform);if(p.x<0){p.x=0}if(p.x>maxWidth){p.x=maxWidth}if(p.y<0){p.y=0}if(p.y>maxHeight){p.y=maxHeight}p.x+=this.canvas._offset.left;p.y+=this.canvas._offset.top;return{left:p.x+"px",top:p.y+"px",fontSize:charHeight}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){if(!this._savedProps){return}this.hoverCursor=this._savedProps.overCursor;this.hasControls=this._savedProps.hasControls;this.borderColor=this._savedProps.borderColor;this.lockMovementX=this._savedProps.lockMovementX;this.lockMovementY=this._savedProps.lockMovementY;if(this.canvas){this.canvas.defaultCursor=this._savedProps.defaultCursor;this.canvas.moveCursor=this._savedProps.moveCursor}},exitEditing:function(){var isTextChanged=this._textBeforeEdit!==this.text;this.selected=false;this.isEditing=false;this.selectable=true;this.selectionEnd=this.selectionStart;if(this.hiddenTextarea){this.hiddenTextarea.blur&&this.hiddenTextarea.blur();this.canvas&&this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea);this.hiddenTextarea=null}this.abortCursorAnimation();this._restoreEditingProps();this._currentCursorOpacity=0;this.fire("editing:exited");isTextChanged&&this.fire("modified");if(this.canvas){this.canvas.off("mouse:move",this.mouseMoveHandler);this.canvas.fire("text:editing:exited",{target:this});isTextChanged&&this.canvas.fire("object:modified",{target:this})}return this},_removeExtraneousStyles:function(){for(var prop in this.styles){if(!this._textLines[prop]){delete this.styles[prop]}}},_removeCharsFromTo:function(start,end){while(end!==start){this._removeSingleCharAndStyle(start+1);end--}this.selectionStart=start;this.selectionEnd=start},_removeSingleCharAndStyle:function(index){var isBeginningOfLine=this.text[index-1]==="\n",indexStyle=isBeginningOfLine?index:index-1;this.removeStyleObject(isBeginningOfLine,indexStyle);this.text=this.text.slice(0,index-1)+this.text.slice(index);this._textLines=this._splitTextIntoLines()},insertChars:function(_chars,useCopiedStyle){var style;if(this.selectionEnd-this.selectionStart>1){this._removeCharsFromTo(this.selectionStart,this.selectionEnd)}if(!useCopiedStyle&&this.isEmptyStyles()){this.insertChar(_chars,false);return}for(var i=0,len=_chars.length;i<len;i++){if(useCopiedStyle){style=fabric.util.object.clone(fabric.copiedTextStyle[i],true)}this.insertChar(_chars[i],i<len-1,style)}},insertChar:function(_char,skipUpdate,styleObject){var isEndOfLine=this.text[this.selectionStart]==="\n";this.text=this.text.slice(0,this.selectionStart)+_char+this.text.slice(this.selectionEnd);this._textLines=this._splitTextIntoLines();this.insertStyleObjects(_char,isEndOfLine,styleObject);this.selectionStart+=_char.length;this.selectionEnd=this.selectionStart;if(skipUpdate){return}this._updateTextarea();this.setCoords();this._fireSelectionChanged();this.fire("changed");this.restartCursorIfNeeded();if(this.canvas){this.canvas.fire("text:changed",{target:this});this.canvas.renderAll()}},restartCursorIfNeeded:function(){if(!this._currentTickState||this._currentTickState.isAborted||!this._currentTickCompleteState||this._currentTickCompleteState.isAborted){this.initDelayedCursor()}},insertNewlineStyleObject:function(lineIndex,charIndex,isEndOfLine){this.shiftLineStyles(lineIndex,+1);var currentCharStyle={},newLineStyles={};if(this.styles[lineIndex]&&this.styles[lineIndex][charIndex-1]){currentCharStyle=this.styles[lineIndex][charIndex-1]}if(isEndOfLine&&currentCharStyle){newLineStyles[0]=clone(currentCharStyle);this.styles[lineIndex+1]=newLineStyles}else{var somethingAdded=false;for(var index in this.styles[lineIndex]){var numIndex=parseInt(index,10);if(numIndex>=charIndex){somethingAdded=true;newLineStyles[numIndex-charIndex]=this.styles[lineIndex][index];delete this.styles[lineIndex][index]}}somethingAdded&&(this.styles[lineIndex+1]=newLineStyles)}this._forceClearCache=true},insertCharStyleObject:function(lineIndex,charIndex,style){var currentLineStyles=this.styles[lineIndex],currentLineStylesCloned=clone(currentLineStyles);if(charIndex===0&&!style){charIndex=1}for(var index in currentLineStylesCloned){var numericIndex=parseInt(index,10);if(numericIndex>=charIndex){currentLineStyles[numericIndex+1]=currentLineStylesCloned[numericIndex];if(!currentLineStylesCloned[numericIndex-1]){delete currentLineStyles[numericIndex]}}}var newStyle=style||clone(currentLineStyles[charIndex-1]);newStyle&&(this.styles[lineIndex][charIndex]=newStyle);this._forceClearCache=true},insertStyleObjects:function(_chars,isEndOfLine,styleObject){var cursorLocation=this.get2DCursorLocation(),lineIndex=cursorLocation.lineIndex,charIndex=cursorLocation.charIndex;if(!this._getLineStyle(lineIndex)){this._setLineStyle(lineIndex,{})}if(_chars==="\n"){this.insertNewlineStyleObject(lineIndex,charIndex,isEndOfLine)}else{this.insertCharStyleObject(lineIndex,charIndex,styleObject)}},shiftLineStyles:function(lineIndex,offset){var clonedStyles=clone(this.styles);for(var line in clonedStyles){var numericLine=parseInt(line,10);if(numericLine<=lineIndex){delete clonedStyles[numericLine]}}for(var line in this.styles){var numericLine=parseInt(line,10);if(numericLine>lineIndex){this.styles[numericLine+offset]=clonedStyles[numericLine];if(!clonedStyles[numericLine-offset]){delete this.styles[numericLine]}}}},removeStyleObject:function(isBeginningOfLine,index){var cursorLocation=this.get2DCursorLocation(index),lineIndex=cursorLocation.lineIndex,charIndex=cursorLocation.charIndex;this._removeStyleObject(isBeginningOfLine,cursorLocation,lineIndex,charIndex)},_getTextOnPreviousLine:function(lIndex){return this._textLines[lIndex-1]},_removeStyleObject:function(isBeginningOfLine,cursorLocation,lineIndex,charIndex){if(isBeginningOfLine){var textOnPreviousLine=this._getTextOnPreviousLine(cursorLocation.lineIndex),newCharIndexOnPrevLine=textOnPreviousLine?textOnPreviousLine.length:0;if(!this.styles[lineIndex-1]){this.styles[lineIndex-1]={}}for(charIndex in this.styles[lineIndex]){this.styles[lineIndex-1][parseInt(charIndex,10)+newCharIndexOnPrevLine]=this.styles[lineIndex][charIndex]}this.shiftLineStyles(cursorLocation.lineIndex,-1)}else{var currentLineStyles=this.styles[lineIndex];if(currentLineStyles){delete currentLineStyles[charIndex]}var currentLineStylesCloned=clone(currentLineStyles);for(var i in currentLineStylesCloned){var numericIndex=parseInt(i,10);if(numericIndex>=charIndex&&numericIndex!==0){currentLineStyles[numericIndex-1]=currentLineStylesCloned[numericIndex];delete currentLineStyles[numericIndex]}}}},insertNewline:function(){this.insertChars("\n")},setSelectionStartEndWithShift:function(start,end,newSelection){if(newSelection<=start){if(end===start){this._selectionDirection="left"}else if(this._selectionDirection==="right"){this._selectionDirection="left";this.selectionEnd=start}this.selectionStart=newSelection}else if(newSelection>start&&newSelection<end){if(this._selectionDirection==="right"){this.selectionEnd=newSelection}else{this.selectionStart=newSelection}}else{if(end===start){this._selectionDirection="right"}else if(this._selectionDirection==="left"){this._selectionDirection="right";this.selectionStart=end}this.selectionEnd=newSelection}},setSelectionInBoundaries:function(){var length=this.text.length;if(this.selectionStart>length){this.selectionStart=length}else if(this.selectionStart<0){this.selectionStart=0}if(this.selectionEnd>length){this.selectionEnd=length}else if(this.selectionEnd<0){this.selectionEnd=0}}})})();fabric.util.object.extend(fabric.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date;this.__lastLastClickTime=+new Date;this.__lastPointer={};this.on("mousedown",this.onMouseDown.bind(this))},onMouseDown:function(options){this.__newClickTime=+new Date;var newPointer=this.canvas.getPointer(options.e);if(this.isTripleClick(newPointer)){this.fire("tripleclick",options);this._stopEvent(options.e)}else if(this.isDoubleClick(newPointer)){this.fire("dblclick",options);this._stopEvent(options.e)}this.__lastLastClickTime=this.__lastClickTime;this.__lastClickTime=this.__newClickTime;this.__lastPointer=newPointer;this.__lastIsEditing=this.isEditing;this.__lastSelected=this.selected},isDoubleClick:function(newPointer){return this.__newClickTime-this.__lastClickTime<500&&this.__lastPointer.x===newPointer.x&&this.__lastPointer.y===newPointer.y&&this.__lastIsEditing},isTripleClick:function(newPointer){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===newPointer.x&&this.__lastPointer.y===newPointer.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault();e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler();this.initMouseupHandler();this.initClicks()},initClicks:function(){this.on("dblclick",function(options){this.selectWord(this.getSelectionStartFromPointer(options.e))});this.on("tripleclick",function(options){this.selectLine(this.getSelectionStartFromPointer(options.e))})},initMousedownHandler:function(){this.on("mousedown",function(options){if(!this.editable){return}var pointer=this.canvas.getPointer(options.e);this.__mousedownX=pointer.x;this.__mousedownY=pointer.y;this.__isMousedown=true;if(this.selected){this.setCursorByClick(options.e)}if(this.isEditing){this.__selectionStartOnMouseDown=this.selectionStart;if(this.selectionStart===this.selectionEnd){this.abortCursorAnimation()}this.renderCursorOrSelection()}})},_isObjectMoved:function(e){var pointer=this.canvas.getPointer(e);return this.__mousedownX!==pointer.x||this.__mousedownY!==pointer.y},initMouseupHandler:function(){this.on("mouseup",function(options){this.__isMousedown=false;if(!this.editable||this._isObjectMoved(options.e)){return}if(this.__lastSelected&&!this.__corner){this.enterEditing(options.e);if(this.selectionStart===this.selectionEnd){this.initDelayedCursor(true)}else{this.renderCursorOrSelection()}}this.selected=true})},setCursorByClick:function(e){var newSelection=this.getSelectionStartFromPointer(e),start=this.selectionStart,end=this.selectionEnd;if(e.shiftKey){this.setSelectionStartEndWithShift(start,end,newSelection)}else{this.selectionStart=newSelection;this.selectionEnd=newSelection}if(this.isEditing){this._fireSelectionChanged();this._updateTextarea()}},getSelectionStartFromPointer:function(e){var mouseOffset=this.getLocalPointer(e),prevWidth=0,width=0,height=0,charIndex=0,newSelectionStart,line;for(var i=0,len=this._textLines.length;i<len;i++){line=this._textLines[i];height+=this._getHeightOfLine(this.ctx,i)*this.scaleY;var widthOfLine=this._getLineWidth(this.ctx,i),lineLeftOffset=this._getLineLeftOffset(widthOfLine);width=lineLeftOffset*this.scaleX;for(var j=0,jlen=line.length;j<jlen;j++){prevWidth=width;width+=this._getWidthOfChar(this.ctx,line[j],i,this.flipX?jlen-j:j)*this.scaleX;if(height<=mouseOffset.y||width<=mouseOffset.x){charIndex++;continue}return this._getNewSelectionStartFromOffset(mouseOffset,prevWidth,width,charIndex+i,jlen)}if(mouseOffset.y<height){return this._getNewSelectionStartFromOffset(mouseOffset,prevWidth,width,charIndex+i-1,jlen)}}if(typeof newSelectionStart==="undefined"){return this.text.length}},_getNewSelectionStartFromOffset:function(mouseOffset,prevWidth,width,index,jlen){var distanceBtwLastCharAndCursor=mouseOffset.x-prevWidth,distanceBtwNextCharAndCursor=width-mouseOffset.x,offset=distanceBtwNextCharAndCursor>distanceBtwLastCharAndCursor?0:1,newSelectionStart=index+offset;if(this.flipX){newSelectionStart=jlen-newSelectionStart}if(newSelectionStart>this.text.length){newSelectionStart=this.text.length}return newSelectionStart}});fabric.util.object.extend(fabric.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=fabric.document.createElement("textarea");this.hiddenTextarea.setAttribute("autocapitalize","off");var style=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="white-space: nowrap; position: absolute; top: "+style.top+"; left: "+style.left+"; opacity: 0; width: 1px; height: 1px; z-index: -999;";fabric.document.body.appendChild(this.hiddenTextarea);fabric.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this));fabric.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this));fabric.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this));fabric.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this));fabric.util.addListener(this.hiddenTextarea,"cut",this.cut.bind(this));fabric.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this));fabric.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this));fabric.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this));fabric.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this));if(!this._clickHandlerInitialized&&this.canvas){fabric.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this));this._clickHandlerInitialized=true}},_keysMap:{8:"removeChars",9:"exitEditing",27:"exitEditing",13:"insertNewline",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown",46:"forwardDelete"},_ctrlKeysMapUp:{67:"copy",88:"cut"},_ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(!this.isEditing){return}if(e.keyCode in this._keysMap){this[this._keysMap[e.keyCode]](e)}else if(e.keyCode in this._ctrlKeysMapDown&&(e.ctrlKey||e.metaKey)){this[this._ctrlKeysMapDown[e.keyCode]](e)}else{return}e.stopImmediatePropagation();e.preventDefault();if(e.keyCode>=33&&e.keyCode<=40){this.clearContextTop();this.renderCursorOrSelection()}else{this.canvas&&this.canvas.renderAll()}},onKeyUp:function(e){if(!this.isEditing||this._copyDone){this._copyDone=false;return}if(e.keyCode in this._ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)){this[this._ctrlKeysMapUp[e.keyCode]](e)}else{return}e.stopImmediatePropagation();e.preventDefault();this.canvas&&this.canvas.renderAll()},onInput:function(e){if(!this.isEditing||this.inCompositionMode){return;
}var offset=this.selectionStart||0,offsetEnd=this.selectionEnd||0,textLength=this.text.length,newTextLength=this.hiddenTextarea.value.length,diff,charsToInsert,start;if(newTextLength>textLength){start=this._selectionDirection==="left"?offsetEnd:offset;diff=newTextLength-textLength;charsToInsert=this.hiddenTextarea.value.slice(start,start+diff)}else{diff=newTextLength-textLength+offsetEnd-offset;charsToInsert=this.hiddenTextarea.value.slice(offset,offset+diff)}this.insertChars(charsToInsert);e.stopPropagation()},onCompositionStart:function(){this.inCompositionMode=true;this.prevCompositionLength=0;this.compositionStart=this.selectionStart},onCompositionEnd:function(){this.inCompositionMode=false},onCompositionUpdate:function(e){var data=e.data;this.selectionStart=this.compositionStart;this.selectionEnd=this.selectionEnd===this.selectionStart?this.compositionStart+this.prevCompositionLength:this.selectionEnd;this.insertChars(data,false);this.prevCompositionLength=data.length},forwardDelete:function(e){if(this.selectionStart===this.selectionEnd){if(this.selectionStart===this.text.length){return}this.moveCursorRight(e)}this.removeChars(e)},copy:function(e){if(this.selectionStart===this.selectionEnd){return}var selectedText=this.getSelectedText(),clipboardData=this._getClipboardData(e);if(clipboardData){clipboardData.setData("text",selectedText)}fabric.copiedText=selectedText;fabric.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd);e.stopImmediatePropagation();e.preventDefault();this._copyDone=true},paste:function(e){var copiedText=null,clipboardData=this._getClipboardData(e),useCopiedStyle=true;if(clipboardData){copiedText=clipboardData.getData("text").replace(/\r/g,"");if(!fabric.copiedTextStyle||fabric.copiedText!==copiedText){useCopiedStyle=false}}else{copiedText=fabric.copiedText}if(copiedText){this.insertChars(copiedText,useCopiedStyle)}e.stopImmediatePropagation();e.preventDefault()},cut:function(e){if(this.selectionStart===this.selectionEnd){return}this.copy(e);this.removeChars(e)},_getClipboardData:function(e){return e&&e.clipboardData||fabric.window.clipboardData},_getWidthBeforeCursor:function(lineIndex,charIndex){var textBeforeCursor=this._textLines[lineIndex].slice(0,charIndex),widthOfLine=this._getLineWidth(this.ctx,lineIndex),widthBeforeCursor=this._getLineLeftOffset(widthOfLine),_char;for(var i=0,len=textBeforeCursor.length;i<len;i++){_char=textBeforeCursor[i];widthBeforeCursor+=this._getWidthOfChar(this.ctx,_char,lineIndex,i)}return widthBeforeCursor},getDownCursorOffset:function(e,isRight){var selectionProp=this._getSelectionForOffset(e,isRight),cursorLocation=this.get2DCursorLocation(selectionProp),lineIndex=cursorLocation.lineIndex;if(lineIndex===this._textLines.length-1||e.metaKey||e.keyCode===34){return this.text.length-selectionProp}var charIndex=cursorLocation.charIndex,widthBeforeCursor=this._getWidthBeforeCursor(lineIndex,charIndex),indexOnOtherLine=this._getIndexOnLine(lineIndex+1,widthBeforeCursor),textAfterCursor=this._textLines[lineIndex].slice(charIndex);return textAfterCursor.length+indexOnOtherLine+2},_getSelectionForOffset:function(e,isRight){if(e.shiftKey&&this.selectionStart!==this.selectionEnd&&isRight){return this.selectionEnd}else{return this.selectionStart}},getUpCursorOffset:function(e,isRight){var selectionProp=this._getSelectionForOffset(e,isRight),cursorLocation=this.get2DCursorLocation(selectionProp),lineIndex=cursorLocation.lineIndex;if(lineIndex===0||e.metaKey||e.keyCode===33){return-selectionProp}var charIndex=cursorLocation.charIndex,widthBeforeCursor=this._getWidthBeforeCursor(lineIndex,charIndex),indexOnOtherLine=this._getIndexOnLine(lineIndex-1,widthBeforeCursor),textBeforeCursor=this._textLines[lineIndex].slice(0,charIndex);return-this._textLines[lineIndex-1].length+indexOnOtherLine-textBeforeCursor.length},_getIndexOnLine:function(lineIndex,width){var widthOfLine=this._getLineWidth(this.ctx,lineIndex),textOnLine=this._textLines[lineIndex],lineLeftOffset=this._getLineLeftOffset(widthOfLine),widthOfCharsOnLine=lineLeftOffset,indexOnLine=0,foundMatch;for(var j=0,jlen=textOnLine.length;j<jlen;j++){var _char=textOnLine[j],widthOfChar=this._getWidthOfChar(this.ctx,_char,lineIndex,j);widthOfCharsOnLine+=widthOfChar;if(widthOfCharsOnLine>width){foundMatch=true;var leftEdge=widthOfCharsOnLine-widthOfChar,rightEdge=widthOfCharsOnLine,offsetFromLeftEdge=Math.abs(leftEdge-width),offsetFromRightEdge=Math.abs(rightEdge-width);indexOnLine=offsetFromRightEdge<offsetFromLeftEdge?j:j-1;break}}if(!foundMatch){indexOnLine=textOnLine.length-1}return indexOnLine},moveCursorDown:function(e){if(this.selectionStart>=this.text.length&&this.selectionEnd>=this.text.length){return}this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){if(this.selectionStart===0&&this.selectionEnd===0){return}this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(direction,e){var action="get"+direction+"CursorOffset",offset=this[action](e,this._selectionDirection==="right");if(e.shiftKey){this.moveCursorWithShift(offset)}else{this.moveCursorWithoutShift(offset)}if(offset!==0){this.setSelectionInBoundaries();this.abortCursorAnimation();this._currentCursorOpacity=1;this.initDelayedCursor();this._fireSelectionChanged();this._updateTextarea()}},moveCursorWithShift:function(offset){var newSelection=this._selectionDirection==="left"?this.selectionStart+offset:this.selectionEnd+offset;this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,newSelection);return offset!==0},moveCursorWithoutShift:function(offset){if(offset<0){this.selectionStart+=offset;this.selectionEnd=this.selectionStart}else{this.selectionEnd+=offset;this.selectionStart=this.selectionEnd}return offset!==0},moveCursorLeft:function(e){if(this.selectionStart===0&&this.selectionEnd===0){return}this._moveCursorLeftOrRight("Left",e)},_move:function(e,prop,direction){var newValue;if(e.altKey){newValue=this["findWordBoundary"+direction](this[prop])}else if(e.metaKey||e.keyCode===35||e.keyCode===36){newValue=this["findLineBoundary"+direction](this[prop])}else{this[prop]+=direction==="Left"?-1:1;return true}if(typeof newValue!==undefined&&this[prop]!==newValue){this[prop]=newValue;return true}},_moveLeft:function(e,prop){return this._move(e,prop,"Left")},_moveRight:function(e,prop){return this._move(e,prop,"Right")},moveCursorLeftWithoutShift:function(e){var change=true;this._selectionDirection="left";if(this.selectionEnd===this.selectionStart&&this.selectionStart!==0){change=this._moveLeft(e,"selectionStart")}this.selectionEnd=this.selectionStart;return change},moveCursorLeftWithShift:function(e){if(this._selectionDirection==="right"&&this.selectionStart!==this.selectionEnd){return this._moveLeft(e,"selectionEnd")}else if(this.selectionStart!==0){this._selectionDirection="left";return this._moveLeft(e,"selectionStart")}},moveCursorRight:function(e){if(this.selectionStart>=this.text.length&&this.selectionEnd>=this.text.length){return}this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(direction,e){var actionName="moveCursor"+direction+"With";this._currentCursorOpacity=1;if(e.shiftKey){actionName+="Shift"}else{actionName+="outShift"}if(this[actionName](e)){this.abortCursorAnimation();this.initDelayedCursor();this._fireSelectionChanged();this._updateTextarea()}},moveCursorRightWithShift:function(e){if(this._selectionDirection==="left"&&this.selectionStart!==this.selectionEnd){return this._moveRight(e,"selectionStart")}else if(this.selectionEnd!==this.text.length){this._selectionDirection="right";return this._moveRight(e,"selectionEnd")}},moveCursorRightWithoutShift:function(e){var changed=true;this._selectionDirection="right";if(this.selectionStart===this.selectionEnd){changed=this._moveRight(e,"selectionStart");this.selectionEnd=this.selectionStart}else{this.selectionStart=this.selectionEnd}return changed},removeChars:function(e){if(this.selectionStart===this.selectionEnd){this._removeCharsNearCursor(e)}else{this._removeCharsFromTo(this.selectionStart,this.selectionEnd)}this.set("dirty",true);this.setSelectionEnd(this.selectionStart);this._removeExtraneousStyles();this.canvas&&this.canvas.renderAll();this.setCoords();this.fire("changed");this.canvas&&this.canvas.fire("text:changed",{target:this})},_removeCharsNearCursor:function(e){if(this.selectionStart===0){return}if(e.metaKey){var leftLineBoundary=this.findLineBoundaryLeft(this.selectionStart);this._removeCharsFromTo(leftLineBoundary,this.selectionStart);this.setSelectionStart(leftLineBoundary)}else if(e.altKey){var leftWordBoundary=this.findWordBoundaryLeft(this.selectionStart);this._removeCharsFromTo(leftWordBoundary,this.selectionStart);this.setSelectionStart(leftWordBoundary)}else{this._removeSingleCharAndStyle(this.selectionStart);this.setSelectionStart(this.selectionStart-1)}}});(function(){var toFixed=fabric.util.toFixed,NUM_FRACTION_DIGITS=fabric.Object.NUM_FRACTION_DIGITS;fabric.util.object.extend(fabric.IText.prototype,{_setSVGTextLineText:function(lineIndex,textSpans,height,textLeftOffset,textTopOffset,textBgRects){if(!this._getLineStyle(lineIndex)){fabric.Text.prototype._setSVGTextLineText.call(this,lineIndex,textSpans,height,textLeftOffset,textTopOffset)}else{this._setSVGTextLineChars(lineIndex,textSpans,height,textLeftOffset,textBgRects)}},_setSVGTextLineChars:function(lineIndex,textSpans,height,textLeftOffset,textBgRects){var chars=this._textLines[lineIndex],charOffset=0,lineLeftOffset=this._getLineLeftOffset(this._getLineWidth(this.ctx,lineIndex))-this.width/2,lineOffset=this._getSVGLineTopOffset(lineIndex),heightOfLine=this._getHeightOfLine(this.ctx,lineIndex);for(var i=0,len=chars.length;i<len;i++){var styleDecl=this._getStyleDeclaration(lineIndex,i)||{};textSpans.push(this._createTextCharSpan(chars[i],styleDecl,lineLeftOffset,lineOffset.lineTop+lineOffset.offset,charOffset));var charWidth=this._getWidthOfChar(this.ctx,chars[i],lineIndex,i);if(styleDecl.textBackgroundColor){textBgRects.push(this._createTextCharBg(styleDecl,lineLeftOffset,lineOffset.lineTop,heightOfLine,charWidth,charOffset))}charOffset+=charWidth}},_getSVGLineTopOffset:function(lineIndex){var lineTopOffset=0,lastHeight=0;for(var j=0;j<lineIndex;j++){lineTopOffset+=this._getHeightOfLine(this.ctx,j)}lastHeight=this._getHeightOfLine(this.ctx,j);return{lineTop:lineTopOffset,offset:(this._fontSizeMult-this._fontSizeFraction)*lastHeight/(this.lineHeight*this._fontSizeMult)}},_createTextCharBg:function(styleDecl,lineLeftOffset,lineTopOffset,heightOfLine,charWidth,charOffset){return[' <rect fill="',styleDecl.textBackgroundColor,'" x="',toFixed(lineLeftOffset+charOffset,NUM_FRACTION_DIGITS),'" y="',toFixed(lineTopOffset-this.height/2,NUM_FRACTION_DIGITS),'" width="',toFixed(charWidth,NUM_FRACTION_DIGITS),'" height="',toFixed(heightOfLine/this.lineHeight,NUM_FRACTION_DIGITS),'"></rect>\n'].join("")},_createTextCharSpan:function(_char,styleDecl,lineLeftOffset,lineTopOffset,charOffset){var fillStyles=this.getSvgStyles.call(fabric.util.object.extend({visible:true,fill:this.fill,stroke:this.stroke,type:"text",getSvgFilter:fabric.Object.prototype.getSvgFilter},styleDecl));return[' <tspan x="',toFixed(lineLeftOffset+charOffset,NUM_FRACTION_DIGITS),'" y="',toFixed(lineTopOffset-this.height/2,NUM_FRACTION_DIGITS),'" ',styleDecl.fontFamily?'font-family="'+styleDecl.fontFamily.replace(/"/g,"'")+'" ':"",styleDecl.fontSize?'font-size="'+styleDecl.fontSize+'" ':"",styleDecl.fontStyle?'font-style="'+styleDecl.fontStyle+'" ':"",styleDecl.fontWeight?'font-weight="'+styleDecl.fontWeight+'" ':"",styleDecl.textDecoration?'text-decoration="'+styleDecl.textDecoration+'" ':"",'style="',fillStyles,'">',fabric.util.string.escapeXml(_char),"</tspan>\n"].join("")}})})();(function(global){"use strict";var fabric=global.fabric||(global.fabric={});fabric.Textbox=fabric.util.createClass(fabric.IText,fabric.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingY:true,lockScalingFlip:true,noScaleCache:false,initialize:function(text,options){this.callSuper("initialize",text,options);this.setControlsVisibility(fabric.Textbox.getTextboxControlVisibility());this.ctx=this.objectCaching?this._cacheContext:fabric.util.createCanvasElement().getContext("2d");this._dimensionAffectingProps.push("width")},_initDimensions:function(ctx){if(this.__skipDimension){return}if(!ctx){ctx=fabric.util.createCanvasElement().getContext("2d");this._setTextStyles(ctx);this.clearContextTop()}this.dynamicMinWidth=0;this._textLines=this._splitTextIntoLines(ctx);if(this.dynamicMinWidth>this.width){this._set("width",this.dynamicMinWidth)}this._clearCache();this.height=this._getTextHeight(ctx)},_generateStyleMap:function(){var realLineCount=0,realLineCharCount=0,charCount=0,map={};for(var i=0;i<this._textLines.length;i++){if(this.text[charCount]==="\n"&&i>0){realLineCharCount=0;charCount++;realLineCount++}else if(this.text[charCount]===" "&&i>0){realLineCharCount++;charCount++}map[i]={line:realLineCount,offset:realLineCharCount};charCount+=this._textLines[i].length;realLineCharCount+=this._textLines[i].length}return map},_getStyleDeclaration:function(lineIndex,charIndex,returnCloneOrEmpty){if(this._styleMap){var map=this._styleMap[lineIndex];if(!map){return returnCloneOrEmpty?{}:null}lineIndex=map.line;charIndex=map.offset+charIndex}return this.callSuper("_getStyleDeclaration",lineIndex,charIndex,returnCloneOrEmpty)},_setStyleDeclaration:function(lineIndex,charIndex,style){var map=this._styleMap[lineIndex];lineIndex=map.line;charIndex=map.offset+charIndex;this.styles[lineIndex][charIndex]=style},_deleteStyleDeclaration:function(lineIndex,charIndex){var map=this._styleMap[lineIndex];lineIndex=map.line;charIndex=map.offset+charIndex;delete this.styles[lineIndex][charIndex]},_getLineStyle:function(lineIndex){var map=this._styleMap[lineIndex];return this.styles[map.line]},_setLineStyle:function(lineIndex,style){var map=this._styleMap[lineIndex];this.styles[map.line]=style},_deleteLineStyle:function(lineIndex){var map=this._styleMap[lineIndex];delete this.styles[map.line]},_wrapText:function(ctx,text){var lines=text.split(this._reNewline),wrapped=[],i;for(i=0;i<lines.length;i++){wrapped=wrapped.concat(this._wrapLine(ctx,lines[i],i))}return wrapped},_measureText:function(ctx,text,lineIndex,charOffset){var width=0;charOffset=charOffset||0;for(var i=0,len=text.length;i<len;i++){width+=this._getWidthOfChar(ctx,text[i],lineIndex,i+charOffset)}return width},_wrapLine:function(ctx,text,lineIndex){var lineWidth=0,lines=[],line="",words=text.split(" "),word="",offset=0,infix=" ",wordWidth=0,infixWidth=0,largestWordWidth=0,lineJustStarted=true,additionalSpace=this._getWidthOfCharSpacing();for(var i=0;i<words.length;i++){word=words[i];wordWidth=this._measureText(ctx,word,lineIndex,offset);offset+=word.length;lineWidth+=infixWidth+wordWidth-additionalSpace;if(lineWidth>=this.width&&!lineJustStarted){lines.push(line);line="";lineWidth=wordWidth;lineJustStarted=true}else{lineWidth+=additionalSpace}if(!lineJustStarted){line+=infix}line+=word;infixWidth=this._measureText(ctx,infix,lineIndex,offset);offset++;lineJustStarted=false;if(wordWidth>largestWordWidth){largestWordWidth=wordWidth}}i&&lines.push(line);if(largestWordWidth>this.dynamicMinWidth){this.dynamicMinWidth=largestWordWidth-additionalSpace}return lines},_splitTextIntoLines:function(ctx){ctx=ctx||this.ctx;var originalAlign=this.textAlign;this._styleMap=null;ctx.save();this._setTextStyles(ctx);this.textAlign="left";var lines=this._wrapText(ctx,this.text);this.textAlign=originalAlign;ctx.restore();this._textLines=lines;this._styleMap=this._generateStyleMap();return lines},setOnGroup:function(key,value){if(key==="scaleX"){this.set("scaleX",Math.abs(1/value));this.set("width",this.get("width")*value/(typeof this.__oldScaleX==="undefined"?1:this.__oldScaleX));this.__oldScaleX=value}},get2DCursorLocation:function(selectionStart){if(typeof selectionStart==="undefined"){selectionStart=this.selectionStart}var numLines=this._textLines.length,removed=0;for(var i=0;i<numLines;i++){var line=this._textLines[i],lineLen=line.length;if(selectionStart<=removed+lineLen){return{lineIndex:i,charIndex:selectionStart-removed}}removed+=lineLen;if(this.text[removed]==="\n"||this.text[removed]===" "){removed++}}return{lineIndex:numLines-1,charIndex:this._textLines[numLines-1].length}},_getCursorBoundariesOffsets:function(chars,typeOfBoundaries){var topOffset=0,leftOffset=0,cursorLocation=this.get2DCursorLocation(),lineChars=this._textLines[cursorLocation.lineIndex].split(""),lineLeftOffset=this._getLineLeftOffset(this._getLineWidth(this.ctx,cursorLocation.lineIndex));for(var i=0;i<cursorLocation.charIndex;i++){leftOffset+=this._getWidthOfChar(this.ctx,lineChars[i],cursorLocation.lineIndex,i)}for(i=0;i<cursorLocation.lineIndex;i++){topOffset+=this._getHeightOfLine(this.ctx,i)}if(typeOfBoundaries==="cursor"){topOffset+=(1-this._fontSizeFraction)*this._getHeightOfLine(this.ctx,cursorLocation.lineIndex)/this.lineHeight-this.getCurrentCharFontSize(cursorLocation.lineIndex,cursorLocation.charIndex)*(1-this._fontSizeFraction)}return{top:topOffset,left:leftOffset,lineLeft:lineLeftOffset}},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},toObject:function(propertiesToInclude){return this.callSuper("toObject",["minWidth"].concat(propertiesToInclude))}});fabric.Textbox.fromObject=function(object,callback,forceAsync){return fabric.Object._fromObject("Textbox",object,callback,forceAsync,"text")};fabric.Textbox.getTextboxControlVisibility=function(){return{tl:false,tr:false,br:false,bl:false,ml:true,mt:false,mr:true,mb:false,mtr:true}}})(typeof exports!=="undefined"?exports:this);(function(){var setObjectScaleOverridden=fabric.Canvas.prototype._setObjectScale;fabric.Canvas.prototype._setObjectScale=function(localMouse,transform,lockScalingX,lockScalingY,by,lockScalingFlip,_dim){var t=transform.target;if(t instanceof fabric.Textbox){var w=t.width*(localMouse.x/transform.scaleX/(t.width+t.strokeWidth));if(w>=t.getMinWidth()){t.set("width",w);return true}}else{return setObjectScaleOverridden.call(fabric.Canvas.prototype,localMouse,transform,lockScalingX,lockScalingY,by,lockScalingFlip,_dim)}};fabric.Group.prototype._refreshControlsVisibility=function(){if(typeof fabric.Textbox==="undefined"){return}for(var i=this._objects.length;i--;){if(this._objects[i]instanceof fabric.Textbox){this.setControlsVisibility(fabric.Textbox.getTextboxControlVisibility());return}}};fabric.util.object.extend(fabric.Textbox.prototype,{_removeExtraneousStyles:function(){for(var prop in this._styleMap){if(!this._textLines[prop]){delete this.styles[this._styleMap[prop].line]}}},insertCharStyleObject:function(lineIndex,charIndex,style){var map=this._styleMap[lineIndex];lineIndex=map.line;charIndex=map.offset+charIndex;fabric.IText.prototype.insertCharStyleObject.apply(this,[lineIndex,charIndex,style])},insertNewlineStyleObject:function(lineIndex,charIndex,isEndOfLine){var map=this._styleMap[lineIndex];lineIndex=map.line;charIndex=map.offset+charIndex;fabric.IText.prototype.insertNewlineStyleObject.apply(this,[lineIndex,charIndex,isEndOfLine])},shiftLineStyles:function(lineIndex,offset){var map=this._styleMap[lineIndex];lineIndex=map.line;fabric.IText.prototype.shiftLineStyles.call(this,lineIndex,offset)},_getTextOnPreviousLine:function(lIndex){var textOnPreviousLine=this._textLines[lIndex-1];while(this._styleMap[lIndex-2]&&this._styleMap[lIndex-2].line===this._styleMap[lIndex-1].line){textOnPreviousLine=this._textLines[lIndex-2]+textOnPreviousLine;lIndex--}return textOnPreviousLine},removeStyleObject:function(isBeginningOfLine,index){var cursorLocation=this.get2DCursorLocation(index),map=this._styleMap[cursorLocation.lineIndex],lineIndex=map.line,charIndex=map.offset+cursorLocation.charIndex;this._removeStyleObject(isBeginningOfLine,cursorLocation,lineIndex,charIndex)}})})();(function(){var override=fabric.IText.prototype._getNewSelectionStartFromOffset;fabric.IText.prototype._getNewSelectionStartFromOffset=function(mouseOffset,prevWidth,width,index,jlen){index=override.call(this,mouseOffset,prevWidth,width,index,jlen);var tmp=0,removed=0;for(var i=0;i<this._textLines.length;i++){tmp+=this._textLines[i].length;if(tmp+removed>=index){break}if(this.text[tmp+removed]==="\n"||this.text[tmp+removed]===" "){removed++}}return index-i+removed}})();(function(){if(typeof document!=="undefined"&&typeof window!=="undefined"){return}var DOMParser=require("xmldom").DOMParser,URL=require("url"),HTTP=require("http"),HTTPS=require("https"),Canvas=require("canvas"),Image=require("canvas").Image;function request(url,encoding,callback){var oURL=URL.parse(url);if(!oURL.port){oURL.port=oURL.protocol.indexOf("https:")===0?443:80}var reqHandler=oURL.protocol.indexOf("https:")===0?HTTPS:HTTP,req=reqHandler.request({hostname:oURL.hostname,port:oURL.port,path:oURL.path,method:"GET"},function(response){var body="";if(encoding){response.setEncoding(encoding)}response.on("end",function(){callback(body)});response.on("data",function(chunk){if(response.statusCode===200){body+=chunk}})});req.on("error",function(err){if(err.errno===process.ECONNREFUSED){fabric.log("ECONNREFUSED: connection refused to "+oURL.hostname+":"+oURL.port)}else{fabric.log(err.message)}callback(null)});req.end()}function requestFs(path,callback){var fs=require("fs");fs.readFile(path,function(err,data){if(err){fabric.log(err);throw err}else{callback(data)}})}fabric.util.loadImage=function(url,callback,context){function createImageAndCallBack(data){if(data){img.src=new Buffer(data,"binary");img._src=url;callback&&callback.call(context,img)}else{img=null;callback&&callback.call(context,null,true)}}var img=new Image;if(url&&(url instanceof Buffer||url.indexOf("data")===0)){img.src=img._src=url;callback&&callback.call(context,img)}else if(url&&url.indexOf("http")!==0){requestFs(url,createImageAndCallBack)}else if(url){request(url,"binary",createImageAndCallBack)}else{callback&&callback.call(context,url)}};fabric.loadSVGFromURL=function(url,callback,reviver){url=url.replace(/^\n\s*/,"").replace(/\?.*$/,"").trim();if(url.indexOf("http")!==0){requestFs(url,function(body){fabric.loadSVGFromString(body.toString(),callback,reviver)})}else{request(url,"",function(body){fabric.loadSVGFromString(body,callback,reviver)})}};fabric.loadSVGFromString=function(string,callback,reviver){var doc=(new DOMParser).parseFromString(string);fabric.parseSVGDocument(doc.documentElement,function(results,options){callback&&callback(results,options)},reviver)};fabric.util.getScript=function(url,callback){request(url,"",function(body){eval(body);callback&&callback()})};fabric.createCanvasForNode=function(width,height,options,nodeCanvasOptions){nodeCanvasOptions=nodeCanvasOptions||options;var canvasEl=fabric.document.createElement("canvas"),nodeCanvas=new Canvas(width||600,height||600,nodeCanvasOptions),nodeCacheCanvas=new Canvas(width||600,height||600,nodeCanvasOptions);canvasEl.style={};canvasEl.width=nodeCanvas.width;canvasEl.height=nodeCanvas.height;options=options||{};options.nodeCanvas=nodeCanvas;options.nodeCacheCanvas=nodeCacheCanvas;var FabricCanvas=fabric.Canvas||fabric.StaticCanvas,fabricCanvas=new FabricCanvas(canvasEl,options);fabricCanvas.nodeCanvas=nodeCanvas;fabricCanvas.nodeCacheCanvas=nodeCacheCanvas;fabricCanvas.contextContainer=nodeCanvas.getContext("2d");fabricCanvas.contextCache=nodeCacheCanvas.getContext("2d");fabricCanvas.Font=Canvas.Font;return fabricCanvas};var originaInitStatic=fabric.StaticCanvas.prototype._initStatic;fabric.StaticCanvas.prototype._initStatic=function(el,options){el=el||fabric.document.createElement("canvas");this.nodeCanvas=new Canvas(el.width,el.height);this.nodeCacheCanvas=new Canvas(el.width,el.height);originaInitStatic.call(this,el,options);this.contextContainer=this.nodeCanvas.getContext("2d");this.contextCache=this.nodeCacheCanvas.getContext("2d");this.Font=Canvas.Font};fabric.StaticCanvas.prototype.createPNGStream=function(){return this.nodeCanvas.createPNGStream()};fabric.StaticCanvas.prototype.createJPEGStream=function(opts){return this.nodeCanvas.createJPEGStream(opts)};fabric.StaticCanvas.prototype._initRetinaScaling=function(){if(!this._isRetinaScaling()){return}this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio);this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio);this.nodeCanvas.width=this.width*fabric.devicePixelRatio;this.nodeCanvas.height=this.height*fabric.devicePixelRatio;this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio);return this};if(fabric.Canvas){fabric.Canvas.prototype._initRetinaScaling=fabric.StaticCanvas.prototype._initRetinaScaling}var origSetBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension;fabric.StaticCanvas.prototype._setBackstoreDimension=function(prop,value){origSetBackstoreDimension.call(this,prop,value);this.nodeCanvas[prop]=value;return this};if(fabric.Canvas){fabric.Canvas.prototype._setBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension}})()}).call(this,require("_process"),require("buffer").Buffer)},{_process:10,buffer:2,canvas:1,fs:1,http:27,https:7,jsdom:1,url:34,xmldom:1}]},{},[]);var PNG=require("pngjs").PNG,pixelmatch=require("pixelmatch"),fabric=require("fabric").fabric;var c1=new fabric.Canvas("c1"),c2=new fabric.Canvas("c2");var ctx1=c1.getContext(),ctx2=c2.getContext(),ctx3=document.getElementById("c3").getContext("2d");var pixelsElm=document.getElementById("pixels");c1.add(new fabric.IText("hi",{left:20,top:20}));c2.add(new fabric.IText("hoi",{left:20,top:20}));document.getElementById("compare").addEventListener("click",function(){var img1=ctx1.getImageData(0,0,100,100);var img2=ctx2.getImageData(0,0,100,100);var diff=ctx3.createImageData(100,100);var res=pixelmatch(img1.data,img2.data,diff.data,100,100);ctx3.putImageData(diff,0,0);pixelsElm.innerHTML=res})},0);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"pngjs": "3.0.1",
"pixelmatch": "4.0.2",
"fabric": "1.7.11"
}
}
<!-- contents of this file will be placed inside the <body> -->
<canvas id="c1" width="100" height="100" style="border: black 3px solid;"></canvas>
<canvas id="c2" width="100" height="100" style="border: black 3px solid;"></canvas>
<canvas id="c3" width="100" height="100" style="border: black 3px solid;"></canvas>
<div>
<button id="compare">Compare</button>
<div id="pixels"></div>
</div>
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment