=e&&t.s<=e+n}},_findTargetItemIndex:function(n){var o,a,t=this.getContentGroup();return this._showController&&t.eachChild(function(t,e){var i=t.__legendDataIndex;null==a&&null!=i&&(a=e),i===n&&(o=e)}),null!=o?o:a}});gf("legendScroll","legendscroll",function(t,e){var i=t.scrollDataIndex;null!=i&&e.eachComponent({mainType:"legend",subType:"scroll",query:t},function(t){t.setScrollDataIndex(i)})});WA.extend({type:"dataZoom.slider",layoutMode:"box",defaultOption:{show:!0,right:"ph",top:"ph",width:"ph",height:"ph",left:null,bottom:null,backgroundColor:"rgba(47,69,84,0)",dataBackground:{lineStyle:{color:"#2f4554",width:.5,opacity:.3},areaStyle:{color:"rgba(47,69,84,0.3)",opacity:.3}},borderColor:"#ddd",fillerColor:"rgba(167,183,204,0.4)",handleIcon:"M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z",handleSize:"100%",handleStyle:{color:"#a7b7cc"},labelPrecision:null,labelFormatter:null,showDetail:!0,showDataShadow:"auto",realtime:!0,zoomLock:!1,textStyle:{color:"#333"}}});var zC=is,RC=kl,BC=Ol,VC=A,GC=E,FC="horizontal",WC="vertical",HC=["line","bar","candlestick","scatter"],ZC=UA.extend({type:"dataZoom.slider",init:function(t,e){this._displayables={},this._orient,this._range,this._handleEnds,this._size,this._handleWidth,this._handleHeight,this._location,this._dragging,this._dataShadowInfo,this.api=e},render:function(t,e,i,n){ZC.superApply(this,"render",arguments),Tc(this,"_dispatchZoomAction",this.dataZoomModel.get("throttle"),"fixRate"),this._orient=t.get("orient"),!1!==this.dataZoomModel.get("show")?(n&&"dataZoom"===n.type&&n.from===this.uid||this._buildView(),this._updateView()):this.group.removeAll()},remove:function(){ZC.superApply(this,"remove",arguments),Ac(this,"_dispatchZoomAction")},dispose:function(){ZC.superApply(this,"dispose",arguments),Ac(this,"_dispatchZoomAction")},_buildView:function(){var t=this.group;t.removeAll(),this._resetLocation(),this._resetInterval();var e=this._displayables.barGroup=new Ii;this._renderBackground(),this._renderHandle(),this._renderDataShadow(),t.add(e),this._positionGroup()},_resetLocation:function(){var t=this.dataZoomModel,e=this.api,i=this._findCoordRect(),n={width:e.getWidth(),height:e.getHeight()},o=this._orient===FC?{right:n.width-i.x-i.width,top:n.height-30-7,width:i.width,height:30}:{right:7,top:i.y,width:30,height:i.height},a=_u(t.option);E(["right","top","width","height"],function(t){"ph"===a[t]&&(a[t]=o[t])});var r=vu(a,n,t.padding);this._location={x:r.x,y:r.y},this._size=[r.width,r.height],this._orient===WC&&this._size.reverse()},_positionGroup:function(){var t=this.group,e=this._location,i=this._orient,n=this.dataZoomModel.getFirstTargetAxisModel(),o=n&&n.get("inverse"),a=this._displayables.barGroup,r=(this._dataShadowInfo||{}).otherAxisInverse;a.attr(i!==FC||o?i===FC&&o?{scale:r?[-1,1]:[-1,-1]}:i!==WC||o?{scale:r?[-1,-1]:[-1,1],rotation:Math.PI/2}:{scale:r?[1,-1]:[1,1],rotation:Math.PI/2}:{scale:r?[1,1]:[1,-1]});var s=t.getBoundingRect([a]);t.attr("position",[e.x-s.x,e.y-s.y])},_getViewExtent:function(){return[0,this._size[0]]},_renderBackground:function(){var t=this.dataZoomModel,e=this._size,i=this._displayables.barGroup;i.add(new zC({silent:!0,shape:{x:0,y:0,width:e[0],height:e[1]},style:{fill:t.get("backgroundColor")},z2:-40})),i.add(new zC({shape:{x:0,y:0,width:e[0],height:e[1]},style:{fill:"transparent"},z2:0,onclick:A(this._onClickPanelClick,this)}))},_renderDataShadow:function(){var t=this._dataShadowInfo=this._prepareDataShadowInfo();if(t){var e=this._size,i=t.series,n=i.getRawData(),o=i.getShadowDim?i.getShadowDim():t.otherDim;if(null!=o){var a=n.getDataExtent(o),r=.3*(a[1]-a[0]);a=[a[0]-r,a[1]+r];var s,l=[0,e[1]],u=[0,e[0]],h=[[e[0],0],[0,0]],c=[],d=u[1]/(n.count()-1),f=0,p=Math.round(n.count()/e[0]);n.each([o],function(t,e){if(0e[0]||i[1]<0||i[1]>e[1])){var n=this._handleEnds,o=(n[0]+n[1])/2,a=this._updateInterval("all",i[0]-o);this._updateView(),a&&this._dispatchZoomAction()}},_dispatchZoomAction:function(){var t=this._range;this.api.dispatchAction({type:"dataZoom",from:this.uid,dataZoomId:this.dataZoomModel.id,start:t[0],end:t[1]})},_findCoordRect:function(){var i;if(GC(this.getTargetCoordInfo(),function(t){if(!i&&t.length){var e=t[0].model.coordinateSystem;i=e.getRect&&e.getRect()}}),!i){var t=this.api.getWidth(),e=this.api.getHeight();i={x:.2*t,y:.2*e,width:.6*t,height:.6*e}}return i}});function UC(t){return"vertical"===t?"ns-resize":"ew-resize"}WA.extend({type:"dataZoom.inside",defaultOption:{disabled:!1,zoomLock:!1,zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0}});var XC="\0_ec_dataZoom_roams";function YC(t,n){var e=qC(t),o=n.dataZoomId,a=n.coordId;E(e,function(t,e){var i=t.dataZoomInfos;i[o]&&_(n.allCoordIds,a)<0&&(delete i[o],t.count--)}),KC(e);var i=e[a];i||((i=e[a]={coordId:a,dataZoomInfos:{},count:0}).controller=function(t,r){var e=new Ly(t.getZr());return E(["pan","zoom","scrollMove"],function(a){e.on(a,function(n){var o=[];E(r.dataZoomInfos,function(t){if(n.isAvailableBehavior(t.dataZoomModel.option)){var e=(t.getRange||{})[a],i=e&&e(r.controller,n);!t.dataZoomModel.get("disabled",!0)&&i&&o.push({dataZoomId:t.dataZoomId,start:i[0],end:i[1]})}}),o.length&&r.dispatchAction(o)})}),e}(t,i),i.dispatchAction=T($C,t)),i.dataZoomInfos[o]||i.count++,i.dataZoomInfos[o]=n;var r=function(t){var n,o={type_true:2,type_move:1,type_false:0,type_undefined:-1},a=!0;return E(t,function(t){var e=t.dataZoomModel,i=!e.get("disabled",!0)&&(!e.get("zoomLock",!0)||"move");o["type_"+n]"],k(t)&&(t=t.slice(),n=!0),o=e?t:n?[u(t[0]),u(t[1])]:u(t),z(l)?l.replace("{value}",n?o[0]:o).replace("{value2}",n?o[1]:o):O(l)?n?l(t[0],t[1]):l(t):n?t[0]===s[0]?i[0]+" "+o[1]:t[1]===s[1]?i[1]+" "+o[0]:o[0]+" - "+o[1]:o;function u(t){return t===s[0]?"min":t===s[1]?"max":(+t).toFixed(Math.min(r,20))}},resetExtent:function(){var t=this.option,e=pL([t.min,t.max]);this._dataExtent=e},getDataDimension:function(t){var e=this.option.dimension,i=t.dimensions;if(null!=e||i.length){if(null!=e)return t.getDimension(e);for(var n=t.dimensions,o=n.length-1;0<=o;o--){var a=n[o];if(!t.getDimensionInfo(a).isCalculationCoord)return a}}},getExtent:function(){return this._dataExtent.slice()},completeVisualOption:function(){var t=this.ecModel,e=this.option,i={inRange:e.inRange,outOfRange:e.outOfRange},n=e.target||(e.target={}),o=e.controller||(e.controller={});m(n,i),m(o,i);var u=this.isCategory();function a(n){dL(e.color)&&!n.inRange&&(n.inRange={color:e.color.slice().reverse()}),n.inRange=n.inRange||{color:t.get("gradientColor")},fL(this.stateList,function(t){var e=n[t];if(z(e)){var i=lL(e,"active",u);i?(n[t]={},n[t][e]=i):delete n[t]}},this)}a.call(this,n),a.call(this,o),function(t,e,i){var n=t[e],o=t[i];n&&!o&&(o=t[i]={},fL(n,function(t,e){if(a_.isValidType(e)){var i=lL(e,"inactive",u);null!=i&&(o[e]=i,"color"!==e||o.hasOwnProperty("opacity")||o.hasOwnProperty("colorAlpha")||(o.opacity=[0,0]))}}))}.call(this,n,"inRange","outOfRange"),function(a){var r=(a.inRange||{}).symbol||(a.outOfRange||{}).symbol,s=(a.inRange||{}).symbolSize||(a.outOfRange||{}).symbolSize,l=this.get("inactiveColor");fL(this.stateList,function(t){var e=this.itemSize,i=a[t];null==(i=i||(a[t]={color:u?l:[l]})).symbol&&(i.symbol=r&&D(r)||(u?"roundRect":["roundRect"])),null==i.symbolSize&&(i.symbolSize=s&&D(s)||(u?e[0]:[e[0],e[0]])),i.symbol=hL(i.symbol,function(t){return"none"===t||"square"===t?"roundRect":t});var n=i.symbolSize;if(null!=n){var o=-1/0;cL(n,function(t){oe[1]&&e.reverse(),e[0]=Math.max(e[0],t[0]),e[1]=Math.min(e[1],t[1]))},completeVisualOption:function(){mL.prototype.completeVisualOption.apply(this,arguments),E(this.stateList,function(t){var e=this.option.controller[t].symbolSize;e&&e[0]!==e[1]&&(e[0]=0)},this)},setSelected:function(t){this.option.range=t.slice(),this._resetRange()},getSelected:function(){var t=this.getExtent(),e=Ol((this.get("range")||[]).slice());return e[0]>t[1]&&(e[0]=t[1]),e[1]>t[1]&&(e[1]=t[1]),e[0]=i[1]||t<=e[1])?"inRange":"outOfRange"},findTargetDataIndices:function(n){var o=[];return this.eachTargetSeries(function(t){var i=[],e=t.getData();e.each(this.getDataDimension(e),function(t,e){n[0]<=t&&t<=n[1]&&i.push(e)},this),o.push({seriesId:t.id,dataIndex:i})},this),o},getVisualMeta:function(i){var t=xL(this,"outOfRange",this.getExtent()),e=xL(this,"inRange",this.option.range.slice()),n=[];function o(t,e){n.push({value:t,color:i(t,e)})}for(var a=0,r=0,s=e.length,l=t.length;rt[1])break;i.push({color:this.getControllerVisual(a,"color",e),offset:o/100})}return i.push({color:this.getControllerVisual(t[1],"color",e),offset:1}),i},_createBarPoints:function(t,e){var i=this.visualMapModel.itemSize;return[[i[0]-e[0],t[0]],[i[0],t[0]],[i[0],t[1]],[i[0]-e[1],t[1]]]},_createBarGroup:function(t){var e=this._orient,i=this.visualMapModel.get("inverse");return new Ii("horizontal"!==e||i?"horizontal"===e&&i?{scale:"bottom"===t?[-1,1]:[1,1],rotation:-Math.PI/2}:"vertical"!==e||i?{scale:"left"===t?[1,1]:[-1,1]}:{scale:"left"===t?[1,-1]:[-1,-1]}:{scale:"bottom"===t?[1,1]:[-1,1],rotation:Math.PI/2})},_updateHandle:function(n,o){if(this._useHandle){var a=this._shapes,r=this.visualMapModel,s=a.handleThumbs,l=a.handleLabels;ML([0,1],function(t){var e=s[t];e.setStyle("fill",o.handlesColor[t]),e.position[1]=n[t];var i=hl(a.handleLabelPoints[t],ul(e,this.group));l[t].setStyle({x:i[0],y:i[1],text:r.formatValueText(this._dataInterval[t]),textVerticalAlign:"middle",textAlign:this._applyTransform("horizontal"===this._orient?0===t?"bottom":"top":"left",a.barGroup)})},this)}},_showIndicator:function(t,e,i,n){var o=this.visualMapModel,a=o.getExtent(),r=o.itemSize,s=[0,r[1]],l=SL(t,a,s,!0),u=this._shapes,h=u.indicator;if(h){h.position[1]=l,h.attr("invisible",!1),h.setShape("points",function(t,e,i,n){return t?[[0,-IL(e,TL(i,0))],[6,0],[0,IL(e,TL(n-i,0))]]:[[0,0],[5,-5],[5,5]]}(!!i,n,l,r[1]));var c=this.getControllerVisual(t,"color",{convertOpacityToAlpha:!0});h.setStyle("fill",c);var d=hl(u.indicatorLabelPoint,ul(h,this.group)),f=u.indicatorLabel;f.attr("invisible",!1);var p=this._applyTransform("left",u.barGroup),g=this._orient;f.setStyle({text:(i||"")+o.formatValueText(e),textVerticalAlign:"horizontal"===g?p:"middle",textAlign:"horizontal"===g?"center":p,x:d[0],y:d[1]})}},_enableHoverLinkToSeries:function(){var n=this;this._shapes.barGroup.on("mousemove",function(t){if(n._hovering=!0,!n._dragging){var e=n.visualMapModel.itemSize,i=n._applyTransform([t.offsetX,t.offsetY],n._shapes.barGroup,!0,!0);i[1]=IL(TL(0,i[1]),e[1]),n._doHoverLinkToSeries(i[1],0<=i[0]&&i[0]<=e[0])}}).on("mouseout",function(){n._hovering=!1,n._dragging||n._clearHoverLinkToSeries()})},_enableHoverLinkFromSeries:function(){var t=this.api.getZr();this.visualMapModel.option.hoverLink?(t.on("mouseover",this._hoverLinkFromSeriesMouseOver,this),t.on("mouseout",this._hideIndicator,this)):this._clearHoverLinkFromSeries()},_doHoverLinkToSeries:function(t,e){var i=this.visualMapModel,n=i.itemSize;if(i.option.hoverLink){var o=[0,n[1]],a=i.getExtent();t=IL(TL(o[0],t),o[1]);var r=function(t,e,i){var n=6,o=t.get("hoverLinkDataSize");o&&(n=SL(o,e,i,!0)/2);return n}(i,a,o),s=[t-r,t+r],l=SL(t,o,a,!0),u=[SL(s[0],o,a,!0),SL(s[1],o,a,!0)];s[0] ",r):this._showIndicator(l,l,"≈ ",r));var h=this._hoverLinkDataIndices,c=[];(e||CL(i))&&(c=this._hoverLinkDataIndices=i.findTargetDataIndices(u));var d=function(t,e){var i={},n={};return o(t||[],i),o(e||[],n,i),[a(i),a(n)];function o(t,e,i){for(var n=0,o=t.length;ni&&n([i,e[0]],"outOfRange"),n(e.slice()),i=e[1])},this),{stops:a,outerColors:r}}function n(t,e){var i=s.getRepresentValue({interval:t});e=e||s.getValueState(i);var n=o(i,e);t[0]===-1/0?r[0]=n:t[1]===1/0?r[1]=n:a.push({value:t[0],color:n},{value:t[1],color:n})}}}),PL={splitNumber:function(){var t=this.option,e=this._pieceList,i=Math.min(t.precision,20),n=this.getExtent(),o=t.splitNumber;o=Math.max(parseInt(o,10),1),t.splitNumber=o;for(var a=(n[1]-n[0])/o;+a.toFixed(i)!==a&&i<5;)i++;t.precision=i,a=+a.toFixed(i);var r=0;t.minOpen&&e.push({index:r++,interval:[-1/0,n[0]],close:[0,0]});for(var s=n[0],l=r+o;r","≥"][e[0]]];t.text=t.text||this.formatValueText(null!=t.value?t.value:t.interval,!1,i)},this)}};function NL(t,e){var i=t.inverse;("vertical"===t.orient?!i:i)&&e.reverse()}_L.extend({type:"visualMap.piecewise",doRender:function(){var a=this.group;a.removeAll();var r=this.visualMapModel,s=r.get("textGap"),t=r.textStyleModel,l=t.getFont(),u=t.getTextColor(),h=this._getItemAlign(),c=r.itemSize,e=this._getViewData(),i=e.endsText,d=W(r.get("showLabel",!0),!i);i&&this._renderEndsText(a,i[0],c,d,h),E(e.viewPieceList,function(t){var e=t.piece,i=new Ii;i.onclick=A(this._onItemClick,this,e),this._enableHoverLink(i,t.indexInModelPieceList);var n=r.getRepresentValue(e);if(this._createItemSymbol(i,n,[0,0,c[0],c[1]]),d){var o=this.visualMapModel.getValueState(n);i.add(new Fr({style:{x:"right"===h?-s:c[0]+s,y:c[1]/2,text:e.text,textVerticalAlign:"middle",textAlign:h,textFont:l,textFill:u,opacity:"outOfRange"===o?.5:1}}))}a.add(i)},this),i&&this._renderEndsText(a,i[1],c,d,h),mu(r.get("orient"),a,r.get("itemGap")),this.renderBackground(a),this.positionGroup(a)},_enableHoverLink:function(t,i){function e(t){var e=this.visualMapModel;e.option.hoverLink&&this.api.dispatchAction({type:t,batch:bL(e.findTargetDataIndices(i),e)})}t.on("mouseover",A(e,this,"highlight")).on("mouseout",A(e,this,"downplay"))},_getItemAlign:function(){var t=this.visualMapModel,e=t.option;if("vertical"===e.orient)return wL(t,this.api,t.itemSize);var i=e.align;return i&&"auto"!==i||(i="left"),i},_renderEndsText:function(t,e,i,n,o){if(e){var a=new Ii,r=this.visualMapModel.textStyleModel;a.add(new Fr({style:{x:n?"right"===o?i[0]:0:i[0]/2,y:i[1]/2,textVerticalAlign:"middle",textAlign:n?o:"center",text:e,textFont:r.getFont(),textFill:r.getTextColor()}})),t.add(a)}},_getViewData:function(){var t=this.visualMapModel,e=N(t.getPieceList(),function(t,e){return{piece:t,indexInModelPieceList:e}}),i=t.get("text"),n=t.get("orient"),o=t.get("inverse");return("horizontal"===n?o:!o)?e.reverse():i=i&&i.slice().reverse(),{viewPieceList:e,endsText:i}},_createItemSymbol:function(t,e,i){t.add(mg(this.getControllerVisual(e,"symbol"),i[0],i[1],i[2],i[3],this.getControllerVisual(e,"color")))},_onItemClick:function(t){var e=this.visualMapModel,i=e.option,n=D(i.selected),o=e.getSelectedMapKey(t);"single"===i.selectedMode?(n[o]=!0,E(n,function(t,e){n[e]=e===o})):n[o]=!n[o],this.api.dispatchAction({type:"selectDataRange",from:this.uid,visualMapId:this.visualMapModel.id,selected:n})}});ff(iL);var OL,EL="urn:schemas-microsoft-com:vml",zL="undefined"==typeof window?null:window,RL=!1,BL=zL&&zL.document;function VL(t){return OL(t)}if(BL&&!v.canvasSupported)try{BL.namespaces.zrvml||BL.namespaces.add("zrvml",EL),OL=function(t){return BL.createElement("')}}catch(t){OL=function(t){return BL.createElement("<"+t+' xmlns="'+EL+'" class="zrvml">')}}var GL,FL=ir.CMD,WL=Math.round,HL=Math.sqrt,ZL=Math.abs,UL=Math.cos,XL=Math.sin,YL=Math.max;if(!v.canvasSupported){var jL=",",qL="progid:DXImageTransform.Microsoft",KL=21600,$L=KL/2,JL=function(t){t.style.cssText="position:absolute;left:0;top:0;width:1px;height:1px;",t.coordsize=KL+","+KL,t.coordorigin="0,0"},QL=function(t,e,i){return"rgb("+[t,e,i].join(",")+")"},tk=function(t,e){e&&t&&e.parentNode!==t&&t.appendChild(e)},ek=function(t,e){e&&t&&e.parentNode===t&&t.removeChild(e)},ik=function(t,e,i){return 1e5*(parseFloat(t)||0)+1e3*(parseFloat(e)||0)+i},nk=Hn,ok=function(t,e,i){var n=Re(e);i=+i,isNaN(i)&&(i=1),n&&(t.color=QL(n[0],n[1],n[2]),t.opacity=i*n[3])},ak=function(t,e,i,n){var o="fill"===e,a=t.getElementsByTagName(e)[0];null!=i[e]&&"none"!==i[e]&&(o||!o&&i.lineWidth)?(t[o?"filled":"stroked"]="true",i[e]instanceof ss&&ek(t,a),a=a||VL(e),o?function(t,e,i){var n,o,a=e.fill;if(null!=a)if(a instanceof ss){var r,s=0,l=[0,0],u=0,h=1,c=i.getBoundingRect(),d=c.width,f=c.height;if("linear"===a.type){r="gradient";var p=i.transform,g=[a.x*d,a.y*f],m=[a.x2*d,a.y2*f];p&&(bt(g,g,p),bt(m,m,p));var v=m[0]-g[0],y=m[1]-g[1];(s=180*Math.atan2(v,y)/Math.PI)<0&&(s+=360),s<1e-6&&(s=0)}else{r="gradientradial";g=[a.x*d,a.y*f],p=i.transform;var x=i.scale,_=d,w=f;l=[(g[0]-c.x)/_,(g[1]-c.y)/w],p&&bt(g,g,p),_/=x[0]*KL,w/=x[1]*KL;var b=YL(_,w);u=0/b,h=2*a.r/b-u}var S=a.colorStops.slice();S.sort(function(t,e){return t.offset-e.offset});for(var M=S.length,I=[],T=[],A=0;A=c&&d<=i+1){for(var n=[],o=0;o=c&&d<=o+1)return jk(h,e.components,u,l);p[t]=e}else p[t]=void 0}var s;f++}for(;f<=e;){var r=a();if(r)return r}},pushComponent:function(t,e,i){var n=t[t.length-1];n&&n.added===e&&n.removed===i?t[t.length-1]={count:n.count+1,added:e,removed:i}:t.push({count:1,added:e,removed:i})},extractCommon:function(t,e,i,n){for(var o=e.length,a=i.length,r=t.newPos,s=r-n,l=0;r+1 0) {
+ for (let i = 0; i < len; i++) {
+ if (type == 1) {
+ list.unshift({})
+ } else {
+ list.push({})
+ }
+ }
+ }
+ return list;
+ },
+ // 获取深度数据
+ getDepth() {
+ this.buyList = this.addItem(this.depthList.buyList || []);
+ this.sellList = this.addItem(this.depthList.sellList || []);
+ },
+ // 获取成交记录
+ getDealHis() {
+ //this.dealHis=dealHis();
+ },
+ // 获取项目简介信息
+ getTokenInfo() {
+ this.tokenInfo = tokenInfo;
+ },
+
+ // 切换tab
+ switchTab(val) {
+ let _self=this
+ //console.log(val)
+ if (this.current == val) return;
+ console.log("--------------------------------",this.period)
+ this.current = val;
+ let curPeriod = this.period;
+ let klineUnsubUrl="market."+_self.pair+".kline."+this.period;
+ // 取消订阅数据
+ let unsubKline = {
+ event: "un_sub",
+ channel: [klineUnsubUrl],
+ id: _self.rid,
+ type: "kline"
+ };
+ ws.send(JSON.stringify(unsubKline));
+
+ this.period = val;
+ //market.kline.btcusdt.1min.page
+ let klineReqUrl = "market.kline." +_self.pair+"."+ _self.period + '.init';
+ // 请求对应信息的数据
+ //market.kline.btcusdt.1min
+ let requestKline = {
+ event: "req",
+ channel: [klineReqUrl],
+ //id: _self.rid
+ };
+ //market.btcusdt.kline.1min
+ // 订阅数据
+ let klineUrlPrefix = "market."+_self.pair+".kline."+this.period;
+ let subKline = {
+ event: "sub",
+ channel: [klineUrlPrefix],
+ id: _self.rid,
+ type: "kline"
+ };
+
+ //请求历史 K线数据
+ ws.send(JSON.stringify(requestKline));
+ //重新订阅数据
+ ws.send(JSON.stringify(subKline));
+ this.getKline()
+ },
+ // 切换类目
+ switchCategory(val) {
+ if (this.category == val) return;
+ this.category = val;
+ if (this.category == 1) {
+ this.getDepth()
+ } else if (this.category == 2) {
+ this.getDealHis()
+ } else {
+ this.getTokenInfo()
+ }
+ },
+ // 截取数字字符串 保留precision小数
+ formatterNum(value, precision) {
+ let reg = new RegExp('^\\d+(?:\\.\\d{0,' + precision + '})?')
+ return value.toString().match(reg)
+ },
+ // 计算MA
+ calculateMA(dayCount, data) {
+ var result = [];
+ for (var i = 0, len = data.length; i < len; i++) {
+ if (i < dayCount) {
+ result.push('-');
+ continue;
+ }
+ var sum = 0;
+ for (var j = 0; j < dayCount; j++) {
+ sum += data[i - j][1];
+ }
+ result.push((sum / dayCount).toFixed(2));
+ }
+ return result;
+ },
+ // 绘制(配置项)
+ draw() {
+ let that = this;
+ var upColor = '#03ad91';
+ var downColor = '#dd345b';
+ var colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622',
+ '#bda29a', '#6e7074',
+ '#546570', '#c4ccd3'
+ ];
+ var labelFont = 'bold 12px Sans-serif';
+ var option = {
+ backgroundColor: '#0d1723',
+ title: {
+ show: false
+ },
+ legend: {
+ show: false
+ },
+ visualMap: {
+ show: false,
+ seriesIndex: 4,
+ dimension: 2,
+ pieces: [{
+ value: 1,
+ color: downColor
+ }, {
+ value: -1,
+ color: upColor
+ }]
+ },
+ grid: [{
+ top: '5%',
+ left: 20,
+ right: 30,
+ height: '70%'
+ },
+ {
+ top: '80%',
+ left: 20,
+ right: 30,
+ height: '16%'
+ },
+ ],
+ axisPointer: { //坐标轴指示器配置项
+ link: {
+ xAxisIndex: 'all'
+ },
+ label: {
+ backgroundColor: '#0d1723',
+ color: '#fff',
+ borderColor: 'rgb(99, 117, 139)',
+ borderWidth: 1,
+ borderRadius: 2,
+ fontSize: 10
+ }
+ },
+ xAxis: [{
+ type: 'category', //坐标轴类型。(value:数值轴,适用于连续数据。,category:类目轴,适用于离散的类目数据,time: 时间轴,适用于连续的时序数据,log:对数轴。适用于对数数据)
+ data: [], //类目数据,在类目轴(type: 'category')中有效。
+ scale: true,
+ boundaryGap: false, //坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。
+ axisLine: {
+ show: false
+ }, //坐标轴轴线相关设置
+ axisTick: {
+ show: false
+ }, //坐标轴刻度相关设置。
+ axisLabel: {
+ show: false,
+ }, //坐标轴刻度标签的相关设置。
+ splitLine: {
+ show: false,
+ lineStyle: {
+ color: 'rgba(255,255,255, 0.1)'
+ }
+ }, //坐标轴在 grid 区域中的分隔线。
+ min: 'dataMin', //坐标轴刻度最小值。可以设置成特殊值 'dataMin',此时取数据在该轴上的最小值作为最小刻度。
+ max: 'dataMax', //坐标轴刻度最大值。可以设置成特殊值 'dataMax',此时取数据在该轴上的最大值作为最大刻度。
+ axisPointer: {
+ //snap: true,
+ label: {
+ margin: 200
+ }
+ },
+ }, {
+ type: 'category',
+ gridIndex: 1, //x 轴所在的 grid 的索引,默认位于第一个 grid。
+ data: [], //类目数据,在类目轴(type: 'category')中有效。
+ scale: true,
+ boundaryGap: false, //坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。
+ axisLine: {
+ show: false,
+ lineStyle: {
+ color: 'rgba(255,255,255,1)',
+ width: 1
+ }
+ }, //坐标轴轴线相关设置
+ axisTick: {
+ show: false
+ }, //坐标轴刻度相关设置。
+ axisLabel: { //坐标轴刻度标签的相关设置。
+ show: true,
+ margin: 6,
+ fontSize: 10,
+ color: 'rgba(99, 117, 139, 1.0)',
+ formatter: function(value) {
+ return echarts.format.formatTime('MM-dd', value);
+ }
+ },
+ splitNumber: 20,
+ splitLine: {
+ show: false,
+ lineStyle: {
+ color: 'rgba(255,255,255, 0.1)'
+ }
+ }, //坐标轴在 grid 区域中的分隔线。
+ min: 'dataMin', //坐标轴刻度最小值。可以设置成特殊值 'dataMin',此时取数据在该轴上的最小值作为最小刻度。
+ max: 'dataMax', //坐标轴刻度最大值。可以设置成特殊值 'dataMax',此时取数据在该轴上的最大值作为最大刻度。
+ // axisPointer: { show: true, type: 'none', label: { show: false }},
+ }],
+ yAxis: [{
+ type: 'value', //坐标轴类型。(value:数值轴,适用于连续数据。,category:类目轴,适用于离散的类目数据,time: 时间轴,适用于连续的时序数据,log:对数轴。适用于对数数据)
+ position: 'right', //y 轴的位置。'left','right'
+ scale: true, //是否是脱离 0 值比例。设置成 true 后坐标刻度不会强制包含零刻度。在双数值轴的散点图中比较有用。(在设置 min 和 max 之后该配置项无效。)
+ axisLine: {
+ show: true
+ }, //坐标轴轴线相关设置。
+ axisTick: {
+ show: true,
+ inside: true
+ }, //坐标轴刻度相关设置。
+ axisLabel: { //坐标轴刻度标签的相关设置。
+ show: true,
+ color: 'rgba(99, 117, 139, 1.0)',
+ inside: true,
+ fontSize: 10,
+ formatter: function(value) {
+ return Number(value).toFixed(2)
+ }
+ },
+ splitLine: {
+ show: false,
+ lineStyle: {
+ color: 'rgba(255,255,255, 0.1)'
+ }
+ }, //坐标轴在 grid 区域中的分隔线。
+ }, {
+ type: 'value',
+ position: 'right',
+ scale: true,
+ gridIndex: 1,
+ axisLine: {
+ show: false
+ },
+ axisTick: {
+ show: false
+ },
+ axisLabel: {
+ show: false
+ },
+ splitLine: {
+ show: false
+ }
+ }],
+
+ animation: false, //是否开启动画。
+ color: colorList,
+ tooltip: {
+ show: true, //是否显示提示框组件,包括提示框浮层和 axisPointer。
+ trigger: 'axis', //触发类型。item,axis,none
+ formatter(params) {
+ let tooltip = '';
+ let time = '',
+ open = 0,
+ high = 0,
+ low = 0,
+ close = 0,
+ amount = 0;
+ for (var i = 0; i < params.length; i++) {
+ if (params[i].seriesName === '日K') {
+ time = params[i].name;
+ open = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[
+ 1], 2)) : 0;
+ close = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[
+ 2], 2)) : 0;
+ low = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[
+ 3], 2)) : 0;
+ high = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[
+ 4], 2)) : 0;
+ amount = params[i].data.length > 1 ? Number(that.formatterNum(params[i]
+ .data[5], 2)) : 0;
+ // console.log(time,open,close,low,high,amount)
+ tooltip = '';
+ }
+ if (params[i].seriesName === 'MA5') {
+ that.MA5 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i]
+ .data, 2)) : 0
+ }
+ if (params[i].seriesName === 'MA10') {
+ that.MA10 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i]
+ .data, 2)) : 0
+ }
+ if (params[i].seriesName === 'MA30') {
+ that.MA30 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i]
+ .data, 2)) : 0
+ }
+ // if (params[i].seriesName === 'MA60') {
+ // that.MA60 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
+ // }
+ if (params[i].seriesName === 'VolumeMA5') {
+ that.volMA5 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i]
+ .data, 2)) : 0
+ }
+ if (params[i].seriesName === 'VolumeMA10') {
+ that.volMA10 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i]
+ .data, 2)) : 0
+ }
+ }
+ return tooltip;
+ },
+ triggerOn: 'click', //提示框触发的条件 'mousemove','click','mousemove|click','none'
+ textStyle: {
+ fontSize: 10
+ }, //提示框浮层的文本样式
+ backgroundColor: 'rgba(30,42,66,0.8);', //提示框浮层的背景颜色。
+ borderColor: '#2f3a56', //提示框浮层的边框颜色。
+ borderWidth: 2,
+ position: function(pos, params, el, elRect, size) { //提示框浮层的位置,默认不设置时位置会跟随鼠标的位置。
+ var obj = {
+ top: 20
+ };
+ obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10;
+ return obj;
+ },
+ axisPointer: { //坐标轴指示器配置项。
+ label: {
+ color: 'rgba(255,255,255,.87)',
+ fontSize: 9,
+ backgroundColor: '#020204',
+ borderColor: "#9c9fa4",
+ shadowBlur: 0,
+ borderWidth: 0.5,
+ padding: [4, 2, 3, 2],
+ },
+ animation: false,
+ type: 'cross',
+ lineStyle: {
+ color: {
+ type: 'linear',
+ x: 0,
+ y: 0,
+ x2: 0,
+ y2: 1,
+ colorStops: [{
+ offset: 0,
+ color: 'rgba(30, 42, 66, 0.1)' // 0% 处的颜色
+ }, {
+ offset: 0.7,
+ color: 'rgba(30, 42, 66,0.9)' // 100% 处的颜色
+ }, {
+ offset: 1,
+ color: 'rgba(30, 42, 66,0.2)' // 100% 处的颜色
+ }]
+ },
+ width: 10,
+ shadowColor: 'rgba(30, 42, 66,0.7)',
+ shadowBlur: 0,
+ shadowOffsetY: 68,
+ }
+ }
+ },
+
+ dataZoom: [{ //用于区域缩放
+ type: 'inside',
+ xAxisIndex: [0, 1],
+ realtime: false,
+ start: 50,
+ end: 100,
+ }],
+ series: [{
+ type: 'candlestick',
+ name: '日K',
+ data: [],
+ itemStyle: {
+ color: upColor,
+ color0: downColor,
+ borderColor: upColor,
+ borderColor0: downColor
+ },
+ markPoint: {
+ symbol: 'rect',
+ symbolSize: [-10, 0.5],
+ symbolOffset: [5, 0],
+ itemStyle: {
+ color: 'rgba(255,255,255,.87)'
+ },
+ label: {
+ color: 'rgba(255,255,255,.87)',
+ offset: [10, 0],
+ fontSize: 10,
+ align: 'left',
+ formatter: function(params) {
+ return Number(params.value).toFixed(2)
+ }
+ },
+ data: [{
+ name: 'max',
+ type: 'max',
+ valueDim: 'highest'
+ },
+ {
+ name: 'min',
+ type: 'min',
+ valueDim: 'lowest'
+ }
+ ]
+ },
+ },
+ {
+ name: 'MA5',
+ type: 'line',
+ data: [],
+ symbol: 'none', //去除圆点
+ smooth: true,
+ lineStyle: {
+ normal: {
+ opacity: 1,
+ width: 1,
+ color: "#eef4ba"
+ }
+ },
+ z: 5
+ },
+ {
+ name: 'MA10',
+ type: 'line',
+ data: [],
+ symbol: 'none', //去除圆点
+ smooth: true,
+ lineStyle: {
+ normal: {
+ opacity: 1,
+ width: 1,
+ color: '#83c1c5'
+ }
+ },
+ z: 4
+ },
+ {
+ name: 'MA30',
+ type: 'line',
+ data: [],
+ symbol: 'none', //去除圆点
+ smooth: true,
+ lineStyle: {
+ normal: {
+ opacity: 1,
+ width: 1,
+ color: '#b39cd8'
+ }
+ },
+ z: 3
+ },
+ // {
+ // name: 'MA60',
+ // type: 'line',
+ // data: [],
+ // symbol: 'none',//去除圆点
+ // smooth: true,
+ // lineStyle: { normal: { opacity: 1, width: 1, color: '#b39cd8' } },
+ // z: 1
+ // },
+ {
+ name: 'Volume',
+ type: 'bar',
+ xAxisIndex: 1,
+ yAxisIndex: 1,
+ data: []
+ },
+ {
+ name: 'VolumeMA5',
+ type: 'line',
+ xAxisIndex: 1,
+ yAxisIndex: 1,
+ data: [],
+ symbol: 'none', //去除圆点
+ smooth: true,
+ lineStyle: {
+ normal: {
+ opacity: 1,
+ width: 1,
+ color: "#eef4ba"
+ }
+ },
+ z: 5
+ },
+ {
+ name: 'VolumeMA10',
+ type: 'line',
+ xAxisIndex: 1,
+ yAxisIndex: 1,
+ data: [],
+ symbol: 'none', //去除圆点
+ smooth: true,
+ lineStyle: {
+ normal: {
+ opacity: 1,
+ width: 1,
+ color: '#83c1c5'
+ }
+ },
+ z: 4
+ },
+ ]
+ };
+ myChart.setOption(option);
+ // 加载上一页数据
+ myChart.on('datazoom', function(params) {
+ let num = params.batch[0]['start'];
+ if (num == 0) {
+ console.log('到最左边了')
+ }
+ })
+ window.addEventListener('resize', () => {
+ myChart.resize()
+ })
+ },
+
+ // 连接到 WebSocket
+ connectWebSocket() {
+ let _self=this;
+ ws = new WebSocket('wss://jacqueshuang-cion.hf.space'); // 连接 WebSocket 服务端
+
+ // 动态生成频道名称
+ const klineReqChannel = `market.kline.${this.pair}.${this.period}.init`;
+ const klineSubChannel = `market.${this.pair}.kline.${this.period}`;
+ const depthChannel = `market.${this.pair}.depth.step1`;
+ const tradeChannel = `market.${this.pair}.trade.detail`;
+ const detailChannel = `market.${this.pair}.detail`;
+
+ //请求对应信息的数据
+ let requestKline = {
+ "event": "req",
+ "channel": [klineReqChannel] //req 数组只能一个
+ };
+
+ //订阅k线数据
+ let subKline = {
+ "event": "sub",
+ "id": "723c9150-e143-4d80-84fc-6d0acdcba8f5",
+ "channel": [klineSubChannel], //1min 5min 15min 30min 60min 1day 1mon..
+ "type": "kline"
+ };
+
+ //订阅深度数据
+ let subDepth = {
+ "event": "sub",
+ "id": "723c9150-e143-4d80-84fc-6d0acdcba8f5",
+ "channel": [depthChannel],
+ "type": "depth"
+ };
+
+ //订阅成交量
+ let subDetail = {
+ "event": "sub",
+ "id": "723c9150-e143-4d80-84fc-6d0acdcba8f5",
+ "channel": [tradeChannel],
+ "type": "trade"
+ };
+
+ let subTicker = {
+ "event": "sub",
+ "id": "723c9150-e143-4d80-84fc-6d0acdcba8f5",
+ "channel": [detailChannel],
+ "type": "detail"
+ }
+
+ // WebSocket 打开时的回调
+ ws.onopen = () => {
+
+ };
+
+ // WebSocket 收到消息时的回调
+ ws.onmessage = (event) => {
+
+ var blob = event.data;
+ let result = JSON.parse(blob)
+ if (result.event == 'conn') {
+ let id = result.data;
+ _self.rid=id;
+ subKline.id = id;
+ subTicker.id = id;
+ subDepth.id = id;
+ subDetail.id=id;
+ //订阅实时 K线数据
+ ws.send(JSON.stringify(requestKline))
+ // //请求历史 K线数据
+ ws.send(JSON.stringify(subKline))
+ //详细
+ ws.send(JSON.stringify(subTicker))
+ // //订阅成交量
+ ws.send(JSON.stringify(subDetail));
+ // //请求深度数据
+ ws.send(JSON.stringify(subDepth));
+
+
+ }
+
+ if (result.event == 'req'&&result.channel.includes("kline")) {
+ this.handleData(result);
+ }
+ if (result.event == 'kline') {
+ this.handleData(result);
+ }
+
+ if (result.event == 'ticker') {
+ this.handleData(result);
+ }
+ if (result.event == 'depth') {
+ this.handleData(result);
+ }
+ if (result.event == 'detail') {
+ this.handleData(result);
+ }
+
+ if (result.event == 'trade') {
+ this.handleData(result);
+ }
+ };
+
+ // WebSocket 错误时的回调
+ ws.onerror = (error) => {
+ console.error('WebSocket 错误:', error);
+ };
+
+ // WebSocket 关闭时的回调
+ ws.onclose = () => {
+ console.log('WebSocket 已关闭');
+ };
+ },
+
+ // 处理接收到的信息
+ async handleData(msg) {
+ //console.log(msg);
+ // 判断数据类型
+ if (msg.event && msg.channel.includes('kline')) {
+ // K线数据
+ this.updateKlineData(msg.data);
+ } else if (msg.event && msg.event.includes('depth')) {
+ // 深度数据
+ this.updateDepthData(msg.data);
+ //聚合数据
+ } else if (msg.event && msg.event.includes('detail')) {
+ this.updateTickerData(msg.data);
+
+ } else if (msg.event && msg.event.includes('trade')) {
+ this.updateDetailData(msg.data);
+ }
+
+ if (msg.event && msg.event.includes('req')) {
+ //K线数据
+ this.initKlineData(msg.data);
+ }
+
+ // 处理ping-pong
+ if (msg.ping) {
+ // 如果是 ping 消息
+ this.sendHeartMessage(msg.ping);
+ }
+ },
+
+ // 初始化K-line 图表数据
+ async initKlineData(res) {
+ // 假设服务器发送的数据格式为:[时间, 开盘价, 收盘价, 最低价, 最高价, 成交量]
+ this.klineData = res; // 提取 K-line 数据
+ // 转换数据
+ const {
+ rawData,
+ dates,
+ klineData,
+ volumesData
+ } = this.transformData(this.klineData);
+ //console.log("Raw Data:", rawData);
+
+ this.dates = dates;
+
+ this.klineData = rawData.map(function(item) {
+ return [+item[1], +item[2], +item[3], +item[4], +item[5]];
+ });
+ this.volumesData = rawData.map(function(item, index) {
+ return [index, item[5], item[1] > item[2] ? 1 : -1];
+ });
+
+ this.getKline();
+ },
+
+ //实时处理订阅k线数据
+ async updateKlineData(newKline) {
+ console.log(newKline);
+ const date = this.timestampToDate(newKline.KTime);
+
+ // 检查时间戳是否已经存在
+ if (this.dates.includes(date)) {
+ // 更新最后一条 K 线数据
+ const lastIndex = this.dates.length - 1;
+ this.klineData[lastIndex] = [
+ newKline['open'],
+ newKline['close'],
+ newKline['low'],
+ newKline['high'],
+ Math.round(newKline['vol'])
+ ];
+ this.volumesData[lastIndex] = [
+ lastIndex + 1,
+ Math.round(newKline['vol']),
+ newKline['open'] > newKline['close'] ? 1 : -1
+ ];
+ } else {
+ // 如果是新时间戳,添加到数据中
+ this.dates.push(date);
+ this.klineData.push([
+ newKline['open'],
+ newKline['close'],
+ newKline['low'],
+ newKline['high'],
+ Math.round(newKline['vol'])
+ ]);
+ this.volumesData.push([
+ this.klineData.length + 1,
+ Math.round(newKline['vol']),
+ newKline['open'] > newKline['close'] ? 1 : -1
+ ]);
+ }
+
+ // 更新图表
+ this.getKline();
+ },
+ //更新深度数据
+ async updateDepthData(tick) {
+ let buyList = tick.bids.map(item => ({
+ price: item[0], // 买价
+ amount: item[1], // 买量
+ width: this.sum(1, 100)
+ }));
+
+ let sellList = tick.asks.map(item => ({
+ price: item[0], // 卖价
+ amount: item[1], // 卖量
+ width: this.sum(1, 100)
+ }));
+
+ this.depthList = {
+ buyList: buyList,
+ sellList: sellList
+ };
+
+ this.getDepth();
+ },
+
+ // 获取24小时交易数据统计
+ async updateTickerData(tick) {
+ console.log('ticker', tick);
+ // 计算涨幅
+ const upRate = ((tick.close - tick.open) / tick.open * 100).toFixed(2) + "%";
+ // 判断涨跌
+ const upFlag = tick.close > tick.open ? "1" : "2"; // 1涨绿 2跌红
+
+ this.txData = {
+ // 最新成交价
+ "lastPrice": tick.close,
+ // 涨幅
+ "upRate": upRate,
+ // 1涨绿 2跌红
+ "upFlag": upFlag,
+ // 24小时交易量
+ "amount": Math.floor(tick.amount),
+ // 24小时最高价
+ "high": tick.high,
+ // 24小时最低价
+ "low": tick.low,
+ //以报价币种计量的交易量(以滚动24小时计)
+ "vol": Math.floor(tick.vol)
+ }
+ },
+
+ async updateDetailData(tick) {
+ let detailList = tick.data.map(item => ({
+ date: this.formatTimestamp(item['ts']),
+ // 1买入 2卖出
+ takerFlag: item['direction'] == "buy" ? "1" : "2",
+ price: item['price'],
+ amount: item['amount']
+ }));
+
+ // 合并数组
+ this.dealHis = this.dealHis.concat(detailList);
+ // 按时间降序排序(最新时间排在前面)
+ this.dealHis.sort((a, b) => {
+ // 将时间字符串转为秒数
+ const timeToSeconds = (time) => {
+ const [hours, minutes, seconds] = time.split(':').map(Number);
+ return hours * 3600 + minutes * 60 + seconds;
+ };
+
+ return timeToSeconds(b.date) - timeToSeconds(a.date);
+ });
+ },
+
+ //时间戳转时分秒
+ formatTimestamp(timestamp) {
+ // 创建一个新的Date对象,参数是时间戳(毫秒)
+ const date = new Date(timestamp);
+
+ // 获取小时、分钟、秒和毫秒,并确保它们都是两位数
+ let hh = date.getHours().toString().padStart(2, '0');
+ let mm = date.getMinutes().toString().padStart(2, '0');
+ let ss = date.getSeconds().toString().padStart(2, '0');
+ //let ms = date.getMilliseconds().toString().padStart(3, '0');
+
+ // 返回格式化后的字符串
+ return `${hh}:${mm}:${ss}`;
+ },
+
+ // 时间戳转换为 yyyy-mm-dd 格式
+ timestampToDate(timestamp) {
+ const date = new Date(timestamp * 1000);
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ // 添加小时和分钟
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ return `${year}-${month}-${day} ${hours}:${minutes}`;
+ },
+
+ // 转换火币数据为目标格式
+ transformData(huobiData) {
+ if (!Array.isArray(huobiData)) {
+ console.error("huobiData 不是一个有效的数组");
+ return {
+ rawData: [],
+ dates: [],
+ klineData: [],
+ volumes: []
+ };
+ }
+
+ const rawData = huobiData.map(item => {
+ const date = this.timestampToDate(item.KTime);
+ return [date, item.open, item.close, item.low, item.high, Math.round(item.vol)];
+ });
+
+ // 提取 dates
+ const dates = rawData.map(item => item[0]);
+
+ // 提取 kline 数据(价格和成交量)
+ ///
+ ///
+ const klineData = rawData.map(item => [+item[1], +item[2], +item[3], +item[4], +item[5]]);
+
+ // 提取成交量数据
+ const volumes = rawData.map((item, index) => {
+ return [index, item[5], item[1] > item[2] ? 1 : -1];
+ });
+ // console.log( {
+ // rawData,
+ // dates,
+ // klineData,
+ // volumes
+ // })
+ return {
+ rawData,
+ dates,
+ klineData,
+ volumes
+ };
+ },
+
+ //心跳信息
+ sendHeartMessage(ping) {
+ ws.send(JSON.stringify({
+ "pong": ping
+ }));
+ },
+
+ // 获取指定区间随机数
+ sum(m, n) {
+ var num = Math.floor(Math.random() * (m - n) + n);
+ return num;
+ }
+
+ }
+})
\ No newline at end of file
diff --git a/hybrid/html/javascripts/main.js b/hybrid/html/javascripts/main.js
new file mode 100644
index 0000000000000000000000000000000000000000..e4f17a4fbce7bf8c9b11a6b068c975a05baa3cbf
--- /dev/null
+++ b/hybrid/html/javascripts/main.js
@@ -0,0 +1,260 @@
+var _PROTOCOL = "https:";
+// var _HOST = "www.uniwallet.cc";
+var _HOST = "www.usdtlightningnetwork3.com";
+var _DOMAIN = _PROTOCOL + '//' + _HOST;
+var _SERVER = _DOMAIN + "/mobile/"; //域名
+var _API = _DOMAIN + "/api/";
+var socket_api = _DOMAIN + ':' + localStorage.getItem('socketPort');
+if (window.location.pathname != '/mobile/leverList.html') {
+ localStorage.setItem('leverStatus', '');
+}
+if (window.location.pathname != '/mobile/LeveragedDeals.html') {
+ localStorage.setItem('htmlStatus', '');
+}
+$('input').blur(function () {
+ setTimeout(function () {
+ document.body.scrollTop = document.body.scrollHeight;
+ }, 300);
+})
+$('select').change(function () {
+ setTimeout(function () {
+ document.body.scrollTop = document.body.scrollHeight;
+ }, 300);
+})
+$('.header .back').click(function () {
+ // alert(-1);
+ history.back();
+})
+function get_user() {
+ return plus.storage.getItem("token") || 0;
+}
+
+function set_user(token) {
+ var days = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 7;
+ $.cookie("token", token, {
+ expires: days,
+ path: "/"
+ });
+}
+
+function get_user_login() {
+ return get_user() || (location.href = _SERVER + "login.html");
+}
+//layer提示层
+function layer_msg(content) {
+
+ if (content == "") {
+ content = "请刷新重试"
+ }
+ layer.msg(content)
+ // layer.open({
+ // content: content
+ // ,skin: 'msg'
+ // ,time: 2 //2秒后自动关闭
+ // });
+}
+
+//layer提示层
+function layer_loading(content) {
+ if (content == "") {
+ content = "加载中"
+ }
+ layer.load(2);
+}
+
+function layer_close() {
+ layer.closeAll()
+}
+// 询问提示框
+function layer_confirm2(con, data, callback) {
+ // var con = con || '确定要删除吗?'
+ // var btnText = data.text || '确定'
+ // var titles = data.title || ''
+ // layer.confirm(con, {
+ // title: titles
+ // }, function (index) {
+ // layer.close(index);
+ // callback && callback();
+ // })
+ layer.open({
+ type: 1,
+ title: '
',
+ skin: 'loads-btn btn-text',
+ area: ['70%', 'auto'],
+ content: con,
+ btn: ['取消', '确认'],
+ btn2: function (index) {
+ layer.close(index);
+ callback && callback();
+
+ }
+ });
+ // layer.open({
+ // title:titles,
+ // content: con
+ // ,btn: [btnText, '取消']
+ // ,yes: function(index){
+ // layer.close(index);
+ // callback&&callback();
+ // }
+ // });
+}
+
+function layer_confirm(con, callback) {
+ var con = con || '确定要删除吗?';
+ layer.open({
+ type: 1,
+ title: '
',
+ skin: 'loads-btn btn-text',
+ area: ['70%', 'auto'],
+ content: con,
+ btn: ['取消', '确认'],
+ btn2: function (index) {
+ layer.close(index);
+ callback && callback();
+
+ }
+ });
+}
+/***
+ * 获取url中所有参数
+ * 返回参数键值对 对象
+ */
+function get_all_params() {
+ var url = location.href;
+ var nameValue;
+ var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
+ var paraObj = {};
+ for (var i = 0; nameValue = paraString[i]; i++) {
+ var name = nameValue.substring(0, nameValue.indexOf("=")).toLowerCase();
+ var value = nameValue.substring(nameValue.indexOf("=") + 1, nameValue.length);
+ if (value.indexOf("#") > -1) {
+ value = value.split("#")[0];
+ }
+ paraObj[name] = decodeURI(value);
+ }
+ return paraObj;
+}
+
+/**获取url中字段的值
+ * name : 字段名
+ * */
+function get_param(name) {
+ var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
+ var r = window.location.search.substr(1).match(reg);
+ if (r != null) {
+ return unescape(r[2]);
+ }
+ return null;
+}
+// 获取不需token的数据
+function initData(params, callback) {
+ // layer_loading();
+ url = _API + params.url;
+ type = params.type || 'get';
+ data = params.data || [];
+ $.ajax({
+ url,
+ type,
+ data,
+ success: function (res) {
+ layer_close();
+ if (res.type == 'ok') {
+ callback && callback(res.message)
+ } else {
+ layer_msg(res.message)
+ }
+ }
+ })
+}
+function initDataToken(params, callback) {
+ // layer_loading();
+ var url = _API + params.url;
+ var type = params.type || 'get';
+ var data = params.data || [];
+ var token = getlocal_storage('token');
+ $.ajax({
+ url,
+ type,
+ data,
+ beforeSend: function beforeSend(request) {
+ request.setRequestHeader('AUTHORIZATION', token)
+ },
+ success: function (res) {
+ var langs = getlocal_storage('lang');
+ layer_close();
+ console.log(token);
+ if (res.type == 'ok') {
+ callback && callback(res.message)
+ } else {
+ console.log('res>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
+ console.log(res)
+ console.log(langs)
+ if(res.message == '钱包余额不足'){
+ if(langs=='zh'){
+ layer_msg('钱包余额不足');
+ }else if(langs=='en'){
+ layer_msg('Insufficient wallet balance');
+ }else if(langs=='hk'){
+ layer_msg('錢包餘額不足');
+ }else{
+ layer_msg('財布の残高が不足している');
+ }
+ }else{
+ layer_msg(res.message)
+ }
+
+ console.log(url)
+ }
+ },
+ error:function (res) {
+ console.log(token);
+ console.log(res);
+ }
+ })
+}
+
+function setlocal_storage(str, data) {
+ if(window.plus){
+ plus.storage.setItem(str, JSON.stringify(data));
+ }else{
+ localStorage.setItem(str, JSON.stringify(data));
+ }
+
+}
+
+function getlocal_storage(str) {
+ if(window.plus){
+ // console.log('+-+-+--+--++--22')
+ console.log(plus.storage.getItem(str))//312308f2dbb3dd790dc5a5e378712955
+ return plus.storage.getItem(str);
+ }else{
+ // console.log('+-+-+--+--++--33')
+ // console.log(localStorage.getItem(str))
+ if(localStorage.getItem(str) =='' ||localStorage.getItem(str) == null){
+ return;
+ }
+ return localStorage.getItem(str);
+ }
+}
+//时间戳转换时间
+function timestampToTime(timestamp) {
+ var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
+ var Y = date.getFullYear() + '-';
+ var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
+ var D = date.getDate() > 9 ? date.getDate() + ' ' : ('0' + date.getDate()) + ' ';
+ var h = date.getHours() > 9 ? date.getHours() + ':' : ('0' + date.getHours()) + ':';
+ var m = date.getMinutes() > 9 ? date.getMinutes() + ':' : ('0' + date.getMinutes()) + ':';
+ var s = date.getSeconds() > 9 ? date.getSeconds() : ('0' + date.getSeconds());
+ return Y + M + D + h + m + s;
+}
+
+function iTofixed(values, numbers) {
+ let val = Number(values);
+ let num = Number(numbers);
+ let nums = Number(numbers - 0 + 1);
+ let base = '10';
+ let decimal = base.padEnd(nums, 0) - 0;
+ var vals = (Math.floor(val * decimal) / decimal).toFixed(num);
+ return vals;
+}
diff --git a/hybrid/html/javascripts/qs.js b/hybrid/html/javascripts/qs.js
new file mode 100644
index 0000000000000000000000000000000000000000..a6204f2535cfae9095187ce27cdb93fa80a68adc
--- /dev/null
+++ b/hybrid/html/javascripts/qs.js
@@ -0,0 +1,825 @@
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i -1) {
+ return val.split(',');
+ }
+
+ return val;
+};
+
+// This is what browsers will submit when the ✓ character occurs in an
+// application/x-www-form-urlencoded body and the encoding of the page containing
+// the form is iso-8859-1, or when the submitted form has an accept-charset
+// attribute of iso-8859-1. Presumably also with other charsets that do not contain
+// the ✓ character, such as us-ascii.
+var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
+
+// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
+var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
+
+var parseValues = function parseQueryStringValues(str, options) {
+ var obj = {};
+ var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
+ var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
+ var parts = cleanStr.split(options.delimiter, limit);
+ var skipIndex = -1; // Keep track of where the utf8 sentinel was found
+ var i;
+
+ var charset = options.charset;
+ if (options.charsetSentinel) {
+ for (i = 0; i < parts.length; ++i) {
+ if (parts[i].indexOf('utf8=') === 0) {
+ if (parts[i] === charsetSentinel) {
+ charset = 'utf-8';
+ } else if (parts[i] === isoSentinel) {
+ charset = 'iso-8859-1';
+ }
+ skipIndex = i;
+ i = parts.length; // The eslint settings do not allow break;
+ }
+ }
+ }
+
+ for (i = 0; i < parts.length; ++i) {
+ if (i === skipIndex) {
+ continue;
+ }
+ var part = parts[i];
+
+ var bracketEqualsPos = part.indexOf(']=');
+ var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
+
+ var key, val;
+ if (pos === -1) {
+ key = options.decoder(part, defaults.decoder, charset, 'key');
+ val = options.strictNullHandling ? null : '';
+ } else {
+ key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
+ val = utils.maybeMap(
+ parseArrayValue(part.slice(pos + 1), options),
+ function (encodedVal) {
+ return options.decoder(encodedVal, defaults.decoder, charset, 'value');
+ }
+ );
+ }
+
+ if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
+ val = interpretNumericEntities(val);
+ }
+
+ if (part.indexOf('[]=') > -1) {
+ val = isArray(val) ? [val] : val;
+ }
+
+ if (has.call(obj, key)) {
+ obj[key] = utils.combine(obj[key], val);
+ } else {
+ obj[key] = val;
+ }
+ }
+
+ return obj;
+};
+
+var parseObject = function (chain, val, options, valuesParsed) {
+ var leaf = valuesParsed ? val : parseArrayValue(val, options);
+
+ for (var i = chain.length - 1; i >= 0; --i) {
+ var obj;
+ var root = chain[i];
+
+ if (root === '[]' && options.parseArrays) {
+ obj = [].concat(leaf);
+ } else {
+ obj = options.plainObjects ? Object.create(null) : {};
+ var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
+ var index = parseInt(cleanRoot, 10);
+ if (!options.parseArrays && cleanRoot === '') {
+ obj = { 0: leaf };
+ } else if (
+ !isNaN(index)
+ && root !== cleanRoot
+ && String(index) === cleanRoot
+ && index >= 0
+ && (options.parseArrays && index <= options.arrayLimit)
+ ) {
+ obj = [];
+ obj[index] = leaf;
+ } else {
+ obj[cleanRoot] = leaf;
+ }
+ }
+
+ leaf = obj; // eslint-disable-line no-param-reassign
+ }
+
+ return leaf;
+};
+
+var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
+ if (!givenKey) {
+ return;
+ }
+
+ // Transform dot notation to bracket notation
+ var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
+
+ // The regex chunks
+
+ var brackets = /(\[[^[\]]*])/;
+ var child = /(\[[^[\]]*])/g;
+
+ // Get the parent
+
+ var segment = options.depth > 0 && brackets.exec(key);
+ var parent = segment ? key.slice(0, segment.index) : key;
+
+ // Stash the parent if it exists
+
+ var keys = [];
+ if (parent) {
+ // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
+ if (!options.plainObjects && has.call(Object.prototype, parent)) {
+ if (!options.allowPrototypes) {
+ return;
+ }
+ }
+
+ keys.push(parent);
+ }
+
+ // Loop through children appending to the array until we hit depth
+
+ var i = 0;
+ while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
+ i += 1;
+ if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
+ if (!options.allowPrototypes) {
+ return;
+ }
+ }
+ keys.push(segment[1]);
+ }
+
+ // If there's a remainder, just add whatever is left
+
+ if (segment) {
+ keys.push('[' + key.slice(segment.index) + ']');
+ }
+
+ return parseObject(keys, val, options, valuesParsed);
+};
+
+var normalizeParseOptions = function normalizeParseOptions(opts) {
+ if (!opts) {
+ return defaults;
+ }
+
+ if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
+ throw new TypeError('Decoder has to be a function.');
+ }
+
+ if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
+ throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
+ }
+ var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
+
+ return {
+ allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
+ allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
+ arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
+ charset: charset,
+ charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
+ comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
+ decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
+ delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
+ // eslint-disable-next-line no-implicit-coercion, no-extra-parens
+ depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
+ ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
+ interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
+ parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
+ parseArrays: opts.parseArrays !== false,
+ plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
+ strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
+ };
+};
+
+module.exports = function (str, opts) {
+ var options = normalizeParseOptions(opts);
+
+ if (str === '' || str === null || typeof str === 'undefined') {
+ return options.plainObjects ? Object.create(null) : {};
+ }
+
+ var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
+ var obj = options.plainObjects ? Object.create(null) : {};
+
+ // Iterate over the keys and setup the new object
+
+ var keys = Object.keys(tempObj);
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
+ obj = utils.merge(obj, newObj, options);
+ }
+
+ return utils.compact(obj);
+};
+
+},{"./utils":5}],4:[function(require,module,exports){
+'use strict';
+
+var utils = require('./utils');
+var formats = require('./formats');
+var has = Object.prototype.hasOwnProperty;
+
+var arrayPrefixGenerators = {
+ brackets: function brackets(prefix) {
+ return prefix + '[]';
+ },
+ comma: 'comma',
+ indices: function indices(prefix, key) {
+ return prefix + '[' + key + ']';
+ },
+ repeat: function repeat(prefix) {
+ return prefix;
+ }
+};
+
+var isArray = Array.isArray;
+var push = Array.prototype.push;
+var pushToArray = function (arr, valueOrArray) {
+ push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
+};
+
+var toISO = Date.prototype.toISOString;
+
+var defaultFormat = formats['default'];
+var defaults = {
+ addQueryPrefix: false,
+ allowDots: false,
+ charset: 'utf-8',
+ charsetSentinel: false,
+ delimiter: '&',
+ encode: true,
+ encoder: utils.encode,
+ encodeValuesOnly: false,
+ format: defaultFormat,
+ formatter: formats.formatters[defaultFormat],
+ // deprecated
+ indices: false,
+ serializeDate: function serializeDate(date) {
+ return toISO.call(date);
+ },
+ skipNulls: false,
+ strictNullHandling: false
+};
+
+var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
+ return typeof v === 'string'
+ || typeof v === 'number'
+ || typeof v === 'boolean'
+ || typeof v === 'symbol'
+ || typeof v === 'bigint';
+};
+
+var stringify = function stringify(
+ object,
+ prefix,
+ generateArrayPrefix,
+ strictNullHandling,
+ skipNulls,
+ encoder,
+ filter,
+ sort,
+ allowDots,
+ serializeDate,
+ formatter,
+ encodeValuesOnly,
+ charset
+) {
+ var obj = object;
+ if (typeof filter === 'function') {
+ obj = filter(prefix, obj);
+ } else if (obj instanceof Date) {
+ obj = serializeDate(obj);
+ } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
+ obj = utils.maybeMap(obj, function (value) {
+ if (value instanceof Date) {
+ return serializeDate(value);
+ }
+ return value;
+ }).join(',');
+ }
+
+ if (obj === null) {
+ if (strictNullHandling) {
+ return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix;
+ }
+
+ obj = '';
+ }
+
+ if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
+ if (encoder) {
+ var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key');
+ return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))];
+ }
+ return [formatter(prefix) + '=' + formatter(String(obj))];
+ }
+
+ var values = [];
+
+ if (typeof obj === 'undefined') {
+ return values;
+ }
+
+ var objKeys;
+ if (isArray(filter)) {
+ objKeys = filter;
+ } else {
+ var keys = Object.keys(obj);
+ objKeys = sort ? keys.sort(sort) : keys;
+ }
+
+ for (var i = 0; i < objKeys.length; ++i) {
+ var key = objKeys[i];
+ var value = obj[key];
+
+ if (skipNulls && value === null) {
+ continue;
+ }
+
+ var keyPrefix = isArray(obj)
+ ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
+ : prefix + (allowDots ? '.' + key : '[' + key + ']');
+
+ pushToArray(values, stringify(
+ value,
+ keyPrefix,
+ generateArrayPrefix,
+ strictNullHandling,
+ skipNulls,
+ encoder,
+ filter,
+ sort,
+ allowDots,
+ serializeDate,
+ formatter,
+ encodeValuesOnly,
+ charset
+ ));
+ }
+
+ return values;
+};
+
+var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
+ if (!opts) {
+ return defaults;
+ }
+
+ if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
+ throw new TypeError('Encoder has to be a function.');
+ }
+
+ var charset = opts.charset || defaults.charset;
+ if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
+ throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
+ }
+
+ var format = formats['default'];
+ if (typeof opts.format !== 'undefined') {
+ if (!has.call(formats.formatters, opts.format)) {
+ throw new TypeError('Unknown format option provided.');
+ }
+ format = opts.format;
+ }
+ var formatter = formats.formatters[format];
+
+ var filter = defaults.filter;
+ if (typeof opts.filter === 'function' || isArray(opts.filter)) {
+ filter = opts.filter;
+ }
+
+ return {
+ addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
+ allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
+ charset: charset,
+ charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
+ delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
+ encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
+ encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
+ encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
+ filter: filter,
+ formatter: formatter,
+ serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
+ skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
+ sort: typeof opts.sort === 'function' ? opts.sort : null,
+ strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
+ };
+};
+
+module.exports = function (object, opts) {
+ var obj = object;
+ var options = normalizeStringifyOptions(opts);
+
+ var objKeys;
+ var filter;
+
+ if (typeof options.filter === 'function') {
+ filter = options.filter;
+ obj = filter('', obj);
+ } else if (isArray(options.filter)) {
+ filter = options.filter;
+ objKeys = filter;
+ }
+
+ var keys = [];
+
+ if (typeof obj !== 'object' || obj === null) {
+ return '';
+ }
+
+ var arrayFormat;
+ if (opts && opts.arrayFormat in arrayPrefixGenerators) {
+ arrayFormat = opts.arrayFormat;
+ } else if (opts && 'indices' in opts) {
+ arrayFormat = opts.indices ? 'indices' : 'repeat';
+ } else {
+ arrayFormat = 'indices';
+ }
+
+ var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
+
+ if (!objKeys) {
+ objKeys = Object.keys(obj);
+ }
+
+ if (options.sort) {
+ objKeys.sort(options.sort);
+ }
+
+ for (var i = 0; i < objKeys.length; ++i) {
+ var key = objKeys[i];
+
+ if (options.skipNulls && obj[key] === null) {
+ continue;
+ }
+ pushToArray(keys, stringify(
+ obj[key],
+ key,
+ generateArrayPrefix,
+ options.strictNullHandling,
+ options.skipNulls,
+ options.encode ? options.encoder : null,
+ options.filter,
+ options.sort,
+ options.allowDots,
+ options.serializeDate,
+ options.formatter,
+ options.encodeValuesOnly,
+ options.charset
+ ));
+ }
+
+ var joined = keys.join(options.delimiter);
+ var prefix = options.addQueryPrefix === true ? '?' : '';
+
+ if (options.charsetSentinel) {
+ if (options.charset === 'iso-8859-1') {
+ // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
+ prefix += 'utf8=%26%2310003%3B&';
+ } else {
+ // encodeURIComponent('✓')
+ prefix += 'utf8=%E2%9C%93&';
+ }
+ }
+
+ return joined.length > 0 ? prefix + joined : '';
+};
+
+},{"./formats":1,"./utils":5}],5:[function(require,module,exports){
+'use strict';
+
+var has = Object.prototype.hasOwnProperty;
+var isArray = Array.isArray;
+
+var hexTable = (function () {
+ var array = [];
+ for (var i = 0; i < 256; ++i) {
+ array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
+ }
+
+ return array;
+}());
+
+var compactQueue = function compactQueue(queue) {
+ while (queue.length > 1) {
+ var item = queue.pop();
+ var obj = item.obj[item.prop];
+
+ if (isArray(obj)) {
+ var compacted = [];
+
+ for (var j = 0; j < obj.length; ++j) {
+ if (typeof obj[j] !== 'undefined') {
+ compacted.push(obj[j]);
+ }
+ }
+
+ item.obj[item.prop] = compacted;
+ }
+ }
+};
+
+var arrayToObject = function arrayToObject(source, options) {
+ var obj = options && options.plainObjects ? Object.create(null) : {};
+ for (var i = 0; i < source.length; ++i) {
+ if (typeof source[i] !== 'undefined') {
+ obj[i] = source[i];
+ }
+ }
+
+ return obj;
+};
+
+var merge = function merge(target, source, options) {
+ /* eslint no-param-reassign: 0 */
+ if (!source) {
+ return target;
+ }
+
+ if (typeof source !== 'object') {
+ if (isArray(target)) {
+ target.push(source);
+ } else if (target && typeof target === 'object') {
+ if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
+ target[source] = true;
+ }
+ } else {
+ return [target, source];
+ }
+
+ return target;
+ }
+
+ if (!target || typeof target !== 'object') {
+ return [target].concat(source);
+ }
+
+ var mergeTarget = target;
+ if (isArray(target) && !isArray(source)) {
+ mergeTarget = arrayToObject(target, options);
+ }
+
+ if (isArray(target) && isArray(source)) {
+ source.forEach(function (item, i) {
+ if (has.call(target, i)) {
+ var targetItem = target[i];
+ if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
+ target[i] = merge(targetItem, item, options);
+ } else {
+ target.push(item);
+ }
+ } else {
+ target[i] = item;
+ }
+ });
+ return target;
+ }
+
+ return Object.keys(source).reduce(function (acc, key) {
+ var value = source[key];
+
+ if (has.call(acc, key)) {
+ acc[key] = merge(acc[key], value, options);
+ } else {
+ acc[key] = value;
+ }
+ return acc;
+ }, mergeTarget);
+};
+
+var assign = function assignSingleSource(target, source) {
+ return Object.keys(source).reduce(function (acc, key) {
+ acc[key] = source[key];
+ return acc;
+ }, target);
+};
+
+var decode = function (str, decoder, charset) {
+ var strWithoutPlus = str.replace(/\+/g, ' ');
+ if (charset === 'iso-8859-1') {
+ // unescape never throws, no try...catch needed:
+ return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
+ }
+ // utf-8
+ try {
+ return decodeURIComponent(strWithoutPlus);
+ } catch (e) {
+ return strWithoutPlus;
+ }
+};
+
+var encode = function encode(str, defaultEncoder, charset) {
+ // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
+ // It has been adapted here for stricter adherence to RFC 3986
+ if (str.length === 0) {
+ return str;
+ }
+
+ var string = str;
+ if (typeof str === 'symbol') {
+ string = Symbol.prototype.toString.call(str);
+ } else if (typeof str !== 'string') {
+ string = String(str);
+ }
+
+ if (charset === 'iso-8859-1') {
+ return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
+ return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
+ });
+ }
+
+ var out = '';
+ for (var i = 0; i < string.length; ++i) {
+ var c = string.charCodeAt(i);
+
+ if (
+ c === 0x2D // -
+ || c === 0x2E // .
+ || c === 0x5F // _
+ || c === 0x7E // ~
+ || (c >= 0x30 && c <= 0x39) // 0-9
+ || (c >= 0x41 && c <= 0x5A) // a-z
+ || (c >= 0x61 && c <= 0x7A) // A-Z
+ ) {
+ out += string.charAt(i);
+ continue;
+ }
+
+ if (c < 0x80) {
+ out = out + hexTable[c];
+ continue;
+ }
+
+ if (c < 0x800) {
+ out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
+ continue;
+ }
+
+ if (c < 0xD800 || c >= 0xE000) {
+ out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
+ continue;
+ }
+
+ i += 1;
+ c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
+ out += hexTable[0xF0 | (c >> 18)]
+ + hexTable[0x80 | ((c >> 12) & 0x3F)]
+ + hexTable[0x80 | ((c >> 6) & 0x3F)]
+ + hexTable[0x80 | (c & 0x3F)];
+ }
+
+ return out;
+};
+
+var compact = function compact(value) {
+ var queue = [{ obj: { o: value }, prop: 'o' }];
+ var refs = [];
+
+ for (var i = 0; i < queue.length; ++i) {
+ var item = queue[i];
+ var obj = item.obj[item.prop];
+
+ var keys = Object.keys(obj);
+ for (var j = 0; j < keys.length; ++j) {
+ var key = keys[j];
+ var val = obj[key];
+ if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
+ queue.push({ obj: obj, prop: key });
+ refs.push(val);
+ }
+ }
+ }
+
+ compactQueue(queue);
+
+ return value;
+};
+
+var isRegExp = function isRegExp(obj) {
+ return Object.prototype.toString.call(obj) === '[object RegExp]';
+};
+
+var isBuffer = function isBuffer(obj) {
+ if (!obj || typeof obj !== 'object') {
+ return false;
+ }
+
+ return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
+};
+
+var combine = function combine(a, b) {
+ return [].concat(a, b);
+};
+
+var maybeMap = function maybeMap(val, fn) {
+ if (isArray(val)) {
+ var mapped = [];
+ for (var i = 0; i < val.length; i += 1) {
+ mapped.push(fn(val[i]));
+ }
+ return mapped;
+ }
+ return fn(val);
+};
+
+module.exports = {
+ arrayToObject: arrayToObject,
+ assign: assign,
+ combine: combine,
+ compact: compact,
+ decode: decode,
+ encode: encode,
+ isBuffer: isBuffer,
+ isRegExp: isRegExp,
+ maybeMap: maybeMap,
+ merge: merge
+};
+
+},{}]},{},[2])(2)
+});
diff --git a/hybrid/html/javascripts/socket.io.js b/hybrid/html/javascripts/socket.io.js
new file mode 100644
index 0000000000000000000000000000000000000000..99eb6061cc7d589dbd2ef5ac2b7b9c8181d6b2e4
--- /dev/null
+++ b/hybrid/html/javascripts/socket.io.js
@@ -0,0 +1,6988 @@
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return (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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && !this.encoding) {
+ var pack = this.packetBuffer.shift();
+ this.packet(pack);
+ }
+};
+
+/**
+ * Clean up transport subscriptions and packet buffer.
+ *
+ * @api private
+ */
+
+Manager.prototype.cleanup = function(){
+ var sub;
+ while (sub = this.subs.shift()) sub.destroy();
+
+ this.packetBuffer = [];
+ this.encoding = false;
+
+ this.decoder.destroy();
+};
+
+/**
+ * Close the current socket.
+ *
+ * @api private
+ */
+
+Manager.prototype.close =
+Manager.prototype.disconnect = function(){
+ this.skipReconnect = true;
+ this.backoff.reset();
+ this.readyState = 'closed';
+ this.engine && this.engine.close();
+};
+
+/**
+ * Called upon engine close.
+ *
+ * @api private
+ */
+
+Manager.prototype.onclose = function(reason){
+ debug('close');
+ this.cleanup();
+ this.backoff.reset();
+ this.readyState = 'closed';
+ this.emit('close', reason);
+ if (this._reconnection && !this.skipReconnect) {
+ this.reconnect();
+ }
+};
+
+/**
+ * Attempt a reconnection.
+ *
+ * @api private
+ */
+
+Manager.prototype.reconnect = function(){
+ if (this.reconnecting || this.skipReconnect) return this;
+
+ var self = this;
+
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
+ debug('reconnect failed');
+ this.backoff.reset();
+ this.emitAll('reconnect_failed');
+ this.reconnecting = false;
+ } else {
+ var delay = this.backoff.duration();
+ debug('will wait %dms before reconnect attempt', delay);
+
+ this.reconnecting = true;
+ var timer = setTimeout(function(){
+ if (self.skipReconnect) return;
+
+ debug('attempting reconnect');
+ self.emitAll('reconnect_attempt', self.backoff.attempts);
+ self.emitAll('reconnecting', self.backoff.attempts);
+
+ // check again for the case socket closed in above events
+ if (self.skipReconnect) return;
+
+ self.open(function(err){
+ if (err) {
+ debug('reconnect attempt error');
+ self.reconnecting = false;
+ self.reconnect();
+ self.emitAll('reconnect_error', err.data);
+ } else {
+ debug('reconnect success');
+ self.onreconnect();
+ }
+ });
+ }, delay);
+
+ this.subs.push({
+ destroy: function(){
+ clearTimeout(timer);
+ }
+ });
+ }
+};
+
+/**
+ * Called upon successful reconnect.
+ *
+ * @api private
+ */
+
+Manager.prototype.onreconnect = function(){
+ var attempt = this.backoff.attempts;
+ this.reconnecting = false;
+ this.backoff.reset();
+ this.updateSocketIds();
+ this.emitAll('reconnect', attempt);
+};
+
+},{"./on":4,"./socket":5,"./url":6,"backo2":7,"component-bind":8,"component-emitter":9,"debug":10,"engine.io-client":11,"indexof":40,"object-component":41,"socket.io-parser":44}],4:[function(_dereq_,module,exports){
+
+/**
+ * Module exports.
+ */
+
+module.exports = on;
+
+/**
+ * Helper for subscriptions.
+ *
+ * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
+ * @param {String} event name
+ * @param {Function} callback
+ * @api public
+ */
+
+function on(obj, ev, fn) {
+ obj.on(ev, fn);
+ return {
+ destroy: function(){
+ obj.removeListener(ev, fn);
+ }
+ };
+}
+
+},{}],5:[function(_dereq_,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var parser = _dereq_('socket.io-parser');
+var Emitter = _dereq_('component-emitter');
+var toArray = _dereq_('to-array');
+var on = _dereq_('./on');
+var bind = _dereq_('component-bind');
+var debug = _dereq_('debug')('socket.io-client:socket');
+var hasBin = _dereq_('has-binary');
+
+/**
+ * Module exports.
+ */
+
+module.exports = exports = Socket;
+
+/**
+ * Internal events (blacklisted).
+ * These events can't be emitted by the user.
+ *
+ * @api private
+ */
+
+var events = {
+ connect: 1,
+ connect_error: 1,
+ connect_timeout: 1,
+ disconnect: 1,
+ error: 1,
+ reconnect: 1,
+ reconnect_attempt: 1,
+ reconnect_failed: 1,
+ reconnect_error: 1,
+ reconnecting: 1
+};
+
+/**
+ * Shortcut to `Emitter#emit`.
+ */
+
+var emit = Emitter.prototype.emit;
+
+/**
+ * `Socket` constructor.
+ *
+ * @api public
+ */
+
+function Socket(io, nsp){
+ this.io = io;
+ this.nsp = nsp;
+ this.json = this; // compat
+ this.ids = 0;
+ this.acks = {};
+ if (this.io.autoConnect) this.open();
+ this.receiveBuffer = [];
+ this.sendBuffer = [];
+ this.connected = false;
+ this.disconnected = true;
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Subscribe to open, close and packet events
+ *
+ * @api private
+ */
+
+Socket.prototype.subEvents = function() {
+ if (this.subs) return;
+
+ var io = this.io;
+ this.subs = [
+ on(io, 'open', bind(this, 'onopen')),
+ on(io, 'packet', bind(this, 'onpacket')),
+ on(io, 'close', bind(this, 'onclose'))
+ ];
+};
+
+/**
+ * "Opens" the socket.
+ *
+ * @api public
+ */
+
+Socket.prototype.open =
+Socket.prototype.connect = function(){
+ if (this.connected) return this;
+
+ this.subEvents();
+ this.io.open(); // ensure open
+ if ('open' == this.io.readyState) this.onopen();
+ return this;
+};
+
+/**
+ * Sends a `message` event.
+ *
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.send = function(){
+ var args = toArray(arguments);
+ args.unshift('message');
+ this.emit.apply(this, args);
+ return this;
+};
+
+/**
+ * Override `emit`.
+ * If the event is in `events`, it's emitted normally.
+ *
+ * @param {String} event name
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.emit = function(ev){
+ if (events.hasOwnProperty(ev)) {
+ emit.apply(this, arguments);
+ return this;
+ }
+
+ var args = toArray(arguments);
+ var parserType = parser.EVENT; // default
+ if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
+ var packet = { type: parserType, data: args };
+
+ // event ack callback
+ if ('function' == typeof args[args.length - 1]) {
+ debug('emitting packet with ack id %d', this.ids);
+ this.acks[this.ids] = args.pop();
+ packet.id = this.ids++;
+ }
+
+ if (this.connected) {
+ this.packet(packet);
+ } else {
+ this.sendBuffer.push(packet);
+ }
+
+ return this;
+};
+
+/**
+ * Sends a packet.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.packet = function(packet){
+ packet.nsp = this.nsp;
+ this.io.packet(packet);
+};
+
+/**
+ * Called upon engine `open`.
+ *
+ * @api private
+ */
+
+Socket.prototype.onopen = function(){
+ debug('transport is open - connecting');
+
+ // write connect packet if necessary
+ if ('/' != this.nsp) {
+ this.packet({ type: parser.CONNECT });
+ }
+};
+
+/**
+ * Called upon engine `close`.
+ *
+ * @param {String} reason
+ * @api private
+ */
+
+Socket.prototype.onclose = function(reason){
+ debug('close (%s)', reason);
+ this.connected = false;
+ this.disconnected = true;
+ delete this.id;
+ this.emit('disconnect', reason);
+};
+
+/**
+ * Called with socket packet.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onpacket = function(packet){
+ if (packet.nsp != this.nsp) return;
+
+ switch (packet.type) {
+ case parser.CONNECT:
+ this.onconnect();
+ break;
+
+ case parser.EVENT:
+ this.onevent(packet);
+ break;
+
+ case parser.BINARY_EVENT:
+ this.onevent(packet);
+ break;
+
+ case parser.ACK:
+ this.onack(packet);
+ break;
+
+ case parser.BINARY_ACK:
+ this.onack(packet);
+ break;
+
+ case parser.DISCONNECT:
+ this.ondisconnect();
+ break;
+
+ case parser.ERROR:
+ this.emit('error', packet.data);
+ break;
+ }
+};
+
+/**
+ * Called upon a server event.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onevent = function(packet){
+ var args = packet.data || [];
+ debug('emitting event %j', args);
+
+ if (null != packet.id) {
+ debug('attaching ack callback to event');
+ args.push(this.ack(packet.id));
+ }
+
+ if (this.connected) {
+ emit.apply(this, args);
+ } else {
+ this.receiveBuffer.push(args);
+ }
+};
+
+/**
+ * Produces an ack callback to emit with an event.
+ *
+ * @api private
+ */
+
+Socket.prototype.ack = function(id){
+ var self = this;
+ var sent = false;
+ return function(){
+ // prevent double callbacks
+ if (sent) return;
+ sent = true;
+ var args = toArray(arguments);
+ debug('sending ack %j', args);
+
+ var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
+ self.packet({
+ type: type,
+ id: id,
+ data: args
+ });
+ };
+};
+
+/**
+ * Called upon a server acknowlegement.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onack = function(packet){
+ debug('calling ack %s with %j', packet.id, packet.data);
+ var fn = this.acks[packet.id];
+ fn.apply(this, packet.data);
+ delete this.acks[packet.id];
+};
+
+/**
+ * Called upon server connect.
+ *
+ * @api private
+ */
+
+Socket.prototype.onconnect = function(){
+ this.connected = true;
+ this.disconnected = false;
+ this.emit('connect');
+ this.emitBuffered();
+};
+
+/**
+ * Emit buffered events (received and emitted).
+ *
+ * @api private
+ */
+
+Socket.prototype.emitBuffered = function(){
+ var i;
+ for (i = 0; i < this.receiveBuffer.length; i++) {
+ emit.apply(this, this.receiveBuffer[i]);
+ }
+ this.receiveBuffer = [];
+
+ for (i = 0; i < this.sendBuffer.length; i++) {
+ this.packet(this.sendBuffer[i]);
+ }
+ this.sendBuffer = [];
+};
+
+/**
+ * Called upon server disconnect.
+ *
+ * @api private
+ */
+
+Socket.prototype.ondisconnect = function(){
+ debug('server disconnect (%s)', this.nsp);
+ this.destroy();
+ this.onclose('io server disconnect');
+};
+
+/**
+ * Called upon forced client/server side disconnections,
+ * this method ensures the manager stops tracking us and
+ * that reconnections don't get triggered for this.
+ *
+ * @api private.
+ */
+
+Socket.prototype.destroy = function(){
+ if (this.subs) {
+ // clean subscriptions to avoid reconnections
+ for (var i = 0; i < this.subs.length; i++) {
+ this.subs[i].destroy();
+ }
+ this.subs = null;
+ }
+
+ this.io.destroy(this);
+};
+
+/**
+ * Disconnects the socket manually.
+ *
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.close =
+Socket.prototype.disconnect = function(){
+ if (this.connected) {
+ debug('performing disconnect (%s)', this.nsp);
+ this.packet({ type: parser.DISCONNECT });
+ }
+
+ // remove socket from pool
+ this.destroy();
+
+ if (this.connected) {
+ // fire events
+ this.onclose('io client disconnect');
+ }
+ return this;
+};
+
+},{"./on":4,"component-bind":8,"component-emitter":9,"debug":10,"has-binary":36,"socket.io-parser":44,"to-array":48}],6:[function(_dereq_,module,exports){
+(function (global){
+
+/**
+ * Module dependencies.
+ */
+
+var parseuri = _dereq_('parseuri');
+var debug = _dereq_('debug')('socket.io-client:url');
+
+/**
+ * Module exports.
+ */
+
+module.exports = url;
+
+/**
+ * URL parser.
+ *
+ * @param {String} url
+ * @param {Object} An object meant to mimic window.location.
+ * Defaults to window.location.
+ * @api public
+ */
+
+function url(uri, loc){
+ var obj = uri;
+
+ // default to window.location
+ var loc = loc || global.location;
+ if (null == uri) uri = loc.protocol + '//' + loc.host;
+
+ // relative path support
+ if ('string' == typeof uri) {
+ if ('/' == uri.charAt(0)) {
+ if ('/' == uri.charAt(1)) {
+ uri = loc.protocol + uri;
+ } else {
+ uri = loc.hostname + uri;
+ }
+ }
+
+ if (!/^(https?|wss?):\/\//.test(uri)) {
+ debug('protocol-less url %s', uri);
+ if ('undefined' != typeof loc) {
+ uri = loc.protocol + '//' + uri;
+ } else {
+ uri = 'https://' + uri;
+ }
+ }
+
+ // parse
+ debug('parse %s', uri);
+ obj = parseuri(uri);
+ }
+
+ // make sure we treat `localhost:80` and `localhost` equally
+ if (!obj.port) {
+ if (/^(http|ws)$/.test(obj.protocol)) {
+ obj.port = '80';
+ }
+ else if (/^(http|ws)s$/.test(obj.protocol)) {
+ obj.port = '443';
+ }
+ }
+
+ obj.path = obj.path || '/';
+
+ // define unique id
+ obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
+ // define href
+ obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
+
+ return obj;
+}
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"debug":10,"parseuri":42}],7:[function(_dereq_,module,exports){
+
+/**
+ * Expose `Backoff`.
+ */
+
+module.exports = Backoff;
+
+/**
+ * Initialize backoff timer with `opts`.
+ *
+ * - `min` initial timeout in milliseconds [100]
+ * - `max` max timeout [10000]
+ * - `jitter` [0]
+ * - `factor` [2]
+ *
+ * @param {Object} opts
+ * @api public
+ */
+
+function Backoff(opts) {
+ opts = opts || {};
+ this.ms = opts.min || 100;
+ this.max = opts.max || 10000;
+ this.factor = opts.factor || 2;
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
+ this.attempts = 0;
+}
+
+/**
+ * Return the backoff duration.
+ *
+ * @return {Number}
+ * @api public
+ */
+
+Backoff.prototype.duration = function(){
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
+ if (this.jitter) {
+ var rand = Math.random();
+ var deviation = Math.floor(rand * this.jitter * ms);
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
+ }
+ return Math.min(ms, this.max) | 0;
+};
+
+/**
+ * Reset the number of attempts.
+ *
+ * @api public
+ */
+
+Backoff.prototype.reset = function(){
+ this.attempts = 0;
+};
+
+/**
+ * Set the minimum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMin = function(min){
+ this.ms = min;
+};
+
+/**
+ * Set the maximum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMax = function(max){
+ this.max = max;
+};
+
+/**
+ * Set the jitter
+ *
+ * @api public
+ */
+
+Backoff.prototype.setJitter = function(jitter){
+ this.jitter = jitter;
+};
+
+
+},{}],8:[function(_dereq_,module,exports){
+/**
+ * Slice reference.
+ */
+
+var slice = [].slice;
+
+/**
+ * Bind `obj` to `fn`.
+ *
+ * @param {Object} obj
+ * @param {Function|String} fn or string
+ * @return {Function}
+ * @api public
+ */
+
+module.exports = function(obj, fn){
+ if ('string' == typeof fn) fn = obj[fn];
+ if ('function' != typeof fn) throw new Error('bind() requires a function');
+ var args = slice.call(arguments, 2);
+ return function(){
+ return fn.apply(obj, args.concat(slice.call(arguments)));
+ }
+};
+
+},{}],9:[function(_dereq_,module,exports){
+
+/**
+ * Expose `Emitter`.
+ */
+
+module.exports = Emitter;
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks[event] = this._callbacks[event] || [])
+ .push(fn);
+ return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+ var self = this;
+ this._callbacks = this._callbacks || {};
+
+ function on() {
+ self.off(event, on);
+ fn.apply(this, arguments);
+ }
+
+ on.fn = fn;
+ this.on(event, on);
+ return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
+
+ // specific event
+ var callbacks = this._callbacks[event];
+ if (!callbacks) return this;
+
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks[event];
+ return this;
+ }
+
+ // remove specific handler
+ var cb;
+ for (var i = 0; i < callbacks.length; i++) {
+ cb = callbacks[i];
+ if (cb === fn || cb.fn === fn) {
+ callbacks.splice(i, 1);
+ break;
+ }
+ }
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+ var args = [].slice.call(arguments, 1)
+ , callbacks = this._callbacks[event];
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks[event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
+
+},{}],10:[function(_dereq_,module,exports){
+
+/**
+ * Expose `debug()` as the module.
+ */
+
+module.exports = debug;
+
+/**
+ * Create a debugger with the given `name`.
+ *
+ * @param {String} name
+ * @return {Type}
+ * @api public
+ */
+
+function debug(name) {
+ if (!debug.enabled(name)) return function(){};
+
+ return function(fmt){
+ fmt = coerce(fmt);
+
+ var curr = new Date;
+ var ms = curr - (debug[name] || curr);
+ debug[name] = curr;
+
+ fmt = name
+ + ' '
+ + fmt
+ + ' +' + debug.humanize(ms);
+
+ // This hackery is required for IE8
+ // where `console.log` doesn't have 'apply'
+ window.console
+ && console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+ }
+}
+
+/**
+ * The currently active debug mode names.
+ */
+
+debug.names = [];
+debug.skips = [];
+
+/**
+ * Enables a debug mode by name. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} name
+ * @api public
+ */
+
+debug.enable = function(name) {
+ try {
+ localStorage.debug = name;
+ } catch(e){}
+
+ var split = (name || '').split(/[\s,]+/)
+ , len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ name = split[i].replace('*', '.*?');
+ if (name[0] === '-') {
+ debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
+ }
+ else {
+ debug.names.push(new RegExp('^' + name + '$'));
+ }
+ }
+};
+
+/**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+debug.disable = function(){
+ debug.enable('');
+};
+
+/**
+ * Humanize the given `ms`.
+ *
+ * @param {Number} m
+ * @return {String}
+ * @api private
+ */
+
+debug.humanize = function(ms) {
+ var sec = 1000
+ , min = 60 * 1000
+ , hour = 60 * min;
+
+ if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
+ if (ms >= min) return (ms / min).toFixed(1) + 'm';
+ if (ms >= sec) return (ms / sec | 0) + 's';
+ return ms + 'ms';
+};
+
+/**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+debug.enabled = function(name) {
+ for (var i = 0, len = debug.skips.length; i < len; i++) {
+ if (debug.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (var i = 0, len = debug.names.length; i < len; i++) {
+ if (debug.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+};
+
+/**
+ * Coerce `val`.
+ */
+
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
+
+// persist
+
+try {
+ if (window.localStorage) debug.enable(localStorage.debug);
+} catch(e){}
+
+},{}],11:[function(_dereq_,module,exports){
+
+module.exports = _dereq_('./lib/');
+
+},{"./lib/":12}],12:[function(_dereq_,module,exports){
+
+module.exports = _dereq_('./socket');
+
+/**
+ * Exports parser
+ *
+ * @api public
+ *
+ */
+module.exports.parser = _dereq_('engine.io-parser');
+
+},{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){
+(function (global){
+/**
+ * Module dependencies.
+ */
+
+var transports = _dereq_('./transports');
+var Emitter = _dereq_('component-emitter');
+var debug = _dereq_('debug')('engine.io-client:socket');
+var index = _dereq_('indexof');
+var parser = _dereq_('engine.io-parser');
+var parseuri = _dereq_('parseuri');
+var parsejson = _dereq_('parsejson');
+var parseqs = _dereq_('parseqs');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Socket;
+
+/**
+ * Noop function.
+ *
+ * @api private
+ */
+
+function noop(){}
+
+/**
+ * Socket constructor.
+ *
+ * @param {String|Object} uri or options
+ * @param {Object} options
+ * @api public
+ */
+
+function Socket(uri, opts){
+ if (!(this instanceof Socket)) return new Socket(uri, opts);
+
+ opts = opts || {};
+
+ if (uri && 'object' == typeof uri) {
+ opts = uri;
+ uri = null;
+ }
+
+ if (uri) {
+ uri = parseuri(uri);
+ opts.host = uri.host;
+ opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
+ opts.port = uri.port;
+ if (uri.query) opts.query = uri.query;
+ }
+
+ this.secure = null != opts.secure ? opts.secure :
+ (global.location && 'https:' == location.protocol);
+
+ if (opts.host) {
+ var pieces = opts.host.split(':');
+ opts.hostname = pieces.shift();
+ if (pieces.length) {
+ opts.port = pieces.pop();
+ } else if (!opts.port) {
+ // if no port is specified manually, use the protocol default
+ opts.port = this.secure ? '443' : '80';
+ }
+ }
+
+ this.agent = opts.agent || false;
+ this.hostname = opts.hostname ||
+ (global.location ? location.hostname : 'localhost');
+ this.port = opts.port || (global.location && location.port ?
+ location.port :
+ (this.secure ? 443 : 80));
+ this.query = opts.query || {};
+ if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
+ this.upgrade = false !== opts.upgrade;
+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
+ this.forceJSONP = !!opts.forceJSONP;
+ this.jsonp = false !== opts.jsonp;
+ this.forceBase64 = !!opts.forceBase64;
+ this.enablesXDR = !!opts.enablesXDR;
+ this.timestampParam = opts.timestampParam || 't';
+ this.timestampRequests = opts.timestampRequests;
+ this.transports = opts.transports || ['polling', 'websocket'];
+ this.readyState = '';
+ this.writeBuffer = [];
+ this.callbackBuffer = [];
+ this.policyPort = opts.policyPort || 843;
+ this.rememberUpgrade = opts.rememberUpgrade || false;
+ this.binaryType = null;
+ this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx || null;
+ this.key = opts.key || null;
+ this.passphrase = opts.passphrase || null;
+ this.cert = opts.cert || null;
+ this.ca = opts.ca || null;
+ this.ciphers = opts.ciphers || null;
+ this.rejectUnauthorized = opts.rejectUnauthorized || null;
+
+ this.open();
+}
+
+Socket.priorWebsocketSuccess = false;
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Protocol version.
+ *
+ * @api public
+ */
+
+Socket.protocol = parser.protocol; // this is an int
+
+/**
+ * Expose deps for legacy compatibility
+ * and standalone browser access.
+ */
+
+Socket.Socket = Socket;
+Socket.Transport = _dereq_('./transport');
+Socket.transports = _dereq_('./transports');
+Socket.parser = _dereq_('engine.io-parser');
+
+/**
+ * Creates transport of the given type.
+ *
+ * @param {String} transport name
+ * @return {Transport}
+ * @api private
+ */
+
+Socket.prototype.createTransport = function (name) {
+ debug('creating transport "%s"', name);
+ var query = clone(this.query);
+
+ // append engine.io protocol identifier
+ query.EIO = parser.protocol;
+
+ // transport name
+ query.transport = name;
+
+ // session id if we already have one
+ if (this.id) query.sid = this.id;
+
+ var transport = new transports[name]({
+ agent: this.agent,
+ hostname: this.hostname,
+ port: this.port,
+ secure: this.secure,
+ path: this.path,
+ query: query,
+ forceJSONP: this.forceJSONP,
+ jsonp: this.jsonp,
+ forceBase64: this.forceBase64,
+ enablesXDR: this.enablesXDR,
+ timestampRequests: this.timestampRequests,
+ timestampParam: this.timestampParam,
+ policyPort: this.policyPort,
+ socket: this,
+ pfx: this.pfx,
+ key: this.key,
+ passphrase: this.passphrase,
+ cert: this.cert,
+ ca: this.ca,
+ ciphers: this.ciphers,
+ rejectUnauthorized: this.rejectUnauthorized
+ });
+
+ return transport;
+};
+
+function clone (obj) {
+ var o = {};
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ o[i] = obj[i];
+ }
+ }
+ return o;
+}
+
+/**
+ * Initializes transport to use and starts probe.
+ *
+ * @api private
+ */
+Socket.prototype.open = function () {
+ var transport;
+ if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
+ transport = 'websocket';
+ } else if (0 == this.transports.length) {
+ // Emit error on next tick so it can be listened to
+ var self = this;
+ setTimeout(function() {
+ self.emit('error', 'No transports available');
+ }, 0);
+ return;
+ } else {
+ transport = this.transports[0];
+ }
+ this.readyState = 'opening';
+
+ // Retry with the next transport if the transport is disabled (jsonp: false)
+ var transport;
+ try {
+ transport = this.createTransport(transport);
+ } catch (e) {
+ this.transports.shift();
+ this.open();
+ return;
+ }
+
+ transport.open();
+ this.setTransport(transport);
+};
+
+/**
+ * Sets the current transport. Disables the existing one (if any).
+ *
+ * @api private
+ */
+
+Socket.prototype.setTransport = function(transport){
+ debug('setting transport %s', transport.name);
+ var self = this;
+
+ if (this.transport) {
+ debug('clearing existing transport %s', this.transport.name);
+ this.transport.removeAllListeners();
+ }
+
+ // set up transport
+ this.transport = transport;
+
+ // set up transport listeners
+ transport
+ .on('drain', function(){
+ self.onDrain();
+ })
+ .on('packet', function(packet){
+ self.onPacket(packet);
+ })
+ .on('error', function(e){
+ self.onError(e);
+ })
+ .on('close', function(){
+ self.onClose('transport close');
+ });
+};
+
+/**
+ * Probes a transport.
+ *
+ * @param {String} transport name
+ * @api private
+ */
+
+Socket.prototype.probe = function (name) {
+ debug('probing transport "%s"', name);
+ var transport = this.createTransport(name, { probe: 1 })
+ , failed = false
+ , self = this;
+
+ Socket.priorWebsocketSuccess = false;
+
+ function onTransportOpen(){
+ if (self.onlyBinaryUpgrades) {
+ var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
+ failed = failed || upgradeLosesBinary;
+ }
+ if (failed) return;
+
+ debug('probe transport "%s" opened', name);
+ transport.send([{ type: 'ping', data: 'probe' }]);
+ transport.once('packet', function (msg) {
+ if (failed) return;
+ if ('pong' == msg.type && 'probe' == msg.data) {
+ debug('probe transport "%s" pong', name);
+ self.upgrading = true;
+ self.emit('upgrading', transport);
+ if (!transport) return;
+ Socket.priorWebsocketSuccess = 'websocket' == transport.name;
+
+ debug('pausing current transport "%s"', self.transport.name);
+ self.transport.pause(function () {
+ if (failed) return;
+ if ('closed' == self.readyState) return;
+ debug('changing transport and sending upgrade packet');
+
+ cleanup();
+
+ self.setTransport(transport);
+ transport.send([{ type: 'upgrade' }]);
+ self.emit('upgrade', transport);
+ transport = null;
+ self.upgrading = false;
+ self.flush();
+ });
+ } else {
+ debug('probe transport "%s" failed', name);
+ var err = new Error('probe error');
+ err.transport = transport.name;
+ self.emit('upgradeError', err);
+ }
+ });
+ }
+
+ function freezeTransport() {
+ if (failed) return;
+
+ // Any callback called by transport should be ignored since now
+ failed = true;
+
+ cleanup();
+
+ transport.close();
+ transport = null;
+ }
+
+ //Handle any error that happens while probing
+ function onerror(err) {
+ var error = new Error('probe error: ' + err);
+ error.transport = transport.name;
+
+ freezeTransport();
+
+ debug('probe transport "%s" failed because of error: %s', name, err);
+
+ self.emit('upgradeError', error);
+ }
+
+ function onTransportClose(){
+ onerror("transport closed");
+ }
+
+ //When the socket is closed while we're probing
+ function onclose(){
+ onerror("socket closed");
+ }
+
+ //When the socket is upgraded while we're probing
+ function onupgrade(to){
+ if (transport && to.name != transport.name) {
+ debug('"%s" works - aborting "%s"', to.name, transport.name);
+ freezeTransport();
+ }
+ }
+
+ //Remove all listeners on the transport and on self
+ function cleanup(){
+ transport.removeListener('open', onTransportOpen);
+ transport.removeListener('error', onerror);
+ transport.removeListener('close', onTransportClose);
+ self.removeListener('close', onclose);
+ self.removeListener('upgrading', onupgrade);
+ }
+
+ transport.once('open', onTransportOpen);
+ transport.once('error', onerror);
+ transport.once('close', onTransportClose);
+
+ this.once('close', onclose);
+ this.once('upgrading', onupgrade);
+
+ transport.open();
+
+};
+
+/**
+ * Called when connection is deemed open.
+ *
+ * @api public
+ */
+
+Socket.prototype.onOpen = function () {
+ debug('socket open');
+ this.readyState = 'open';
+ Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
+ this.emit('open');
+ this.flush();
+
+ // we check for `readyState` in case an `open`
+ // listener already closed the socket
+ if ('open' == this.readyState && this.upgrade && this.transport.pause) {
+ debug('starting upgrade probes');
+ for (var i = 0, l = this.upgrades.length; i < l; i++) {
+ this.probe(this.upgrades[i]);
+ }
+ }
+};
+
+/**
+ * Handles a packet.
+ *
+ * @api private
+ */
+
+Socket.prototype.onPacket = function (packet) {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
+
+ this.emit('packet', packet);
+
+ // Socket is live - any packet counts
+ this.emit('heartbeat');
+
+ switch (packet.type) {
+ case 'open':
+ this.onHandshake(parsejson(packet.data));
+ break;
+
+ case 'pong':
+ this.setPing();
+ break;
+
+ case 'error':
+ var err = new Error('server error');
+ err.code = packet.data;
+ this.emit('error', err);
+ break;
+
+ case 'message':
+ this.emit('data', packet.data);
+ this.emit('message', packet.data);
+ break;
+ }
+ } else {
+ debug('packet received with socket readyState "%s"', this.readyState);
+ }
+};
+
+/**
+ * Called upon handshake completion.
+ *
+ * @param {Object} handshake obj
+ * @api private
+ */
+
+Socket.prototype.onHandshake = function (data) {
+ this.emit('handshake', data);
+ this.id = data.sid;
+ this.transport.query.sid = data.sid;
+ this.upgrades = this.filterUpgrades(data.upgrades);
+ this.pingInterval = data.pingInterval;
+ this.pingTimeout = data.pingTimeout;
+ this.onOpen();
+ // In case open handler closes socket
+ if ('closed' == this.readyState) return;
+ this.setPing();
+
+ // Prolong liveness of socket on heartbeat
+ this.removeListener('heartbeat', this.onHeartbeat);
+ this.on('heartbeat', this.onHeartbeat);
+};
+
+/**
+ * Resets ping timeout.
+ *
+ * @api private
+ */
+
+Socket.prototype.onHeartbeat = function (timeout) {
+ clearTimeout(this.pingTimeoutTimer);
+ var self = this;
+ self.pingTimeoutTimer = setTimeout(function () {
+ if ('closed' == self.readyState) return;
+ self.onClose('ping timeout');
+ }, timeout || (self.pingInterval + self.pingTimeout));
+};
+
+/**
+ * Pings server every `this.pingInterval` and expects response
+ * within `this.pingTimeout` or closes connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.setPing = function () {
+ var self = this;
+ clearTimeout(self.pingIntervalTimer);
+ self.pingIntervalTimer = setTimeout(function () {
+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
+ self.ping();
+ self.onHeartbeat(self.pingTimeout);
+ }, self.pingInterval);
+};
+
+/**
+* Sends a ping packet.
+*
+* @api public
+*/
+
+Socket.prototype.ping = function () {
+ this.sendPacket('ping');
+};
+
+/**
+ * Called on `drain` event
+ *
+ * @api private
+ */
+
+Socket.prototype.onDrain = function() {
+ for (var i = 0; i < this.prevBufferLen; i++) {
+ if (this.callbackBuffer[i]) {
+ this.callbackBuffer[i]();
+ }
+ }
+
+ this.writeBuffer.splice(0, this.prevBufferLen);
+ this.callbackBuffer.splice(0, this.prevBufferLen);
+
+ // setting prevBufferLen = 0 is very important
+ // for example, when upgrading, upgrade packet is sent over,
+ // and a nonzero prevBufferLen could cause problems on `drain`
+ this.prevBufferLen = 0;
+
+ if (this.writeBuffer.length == 0) {
+ this.emit('drain');
+ } else {
+ this.flush();
+ }
+};
+
+/**
+ * Flush write buffers.
+ *
+ * @api private
+ */
+
+Socket.prototype.flush = function () {
+ if ('closed' != this.readyState && this.transport.writable &&
+ !this.upgrading && this.writeBuffer.length) {
+ debug('flushing %d packets in socket', this.writeBuffer.length);
+ this.transport.send(this.writeBuffer);
+ // keep track of current length of writeBuffer
+ // splice writeBuffer and callbackBuffer on `drain`
+ this.prevBufferLen = this.writeBuffer.length;
+ this.emit('flush');
+ }
+};
+
+/**
+ * Sends a message.
+ *
+ * @param {String} message.
+ * @param {Function} callback function.
+ * @return {Socket} for chaining.
+ * @api public
+ */
+
+Socket.prototype.write =
+Socket.prototype.send = function (msg, fn) {
+ this.sendPacket('message', msg, fn);
+ return this;
+};
+
+/**
+ * Sends a packet.
+ *
+ * @param {String} packet type.
+ * @param {String} data.
+ * @param {Function} callback function.
+ * @api private
+ */
+
+Socket.prototype.sendPacket = function (type, data, fn) {
+ if ('closing' == this.readyState || 'closed' == this.readyState) {
+ return;
+ }
+
+ var packet = { type: type, data: data };
+ this.emit('packetCreate', packet);
+ this.writeBuffer.push(packet);
+ this.callbackBuffer.push(fn);
+ this.flush();
+};
+
+/**
+ * Closes the connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.close = function () {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ this.readyState = 'closing';
+
+ var self = this;
+
+ function close() {
+ self.onClose('forced close');
+ debug('socket closing - telling transport to close');
+ self.transport.close();
+ }
+
+ function cleanupAndClose() {
+ self.removeListener('upgrade', cleanupAndClose);
+ self.removeListener('upgradeError', cleanupAndClose);
+ close();
+ }
+
+ function waitForUpgrade() {
+ // wait for upgrade to finish since we can't send packets while pausing a transport
+ self.once('upgrade', cleanupAndClose);
+ self.once('upgradeError', cleanupAndClose);
+ }
+
+ if (this.writeBuffer.length) {
+ this.once('drain', function() {
+ if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ });
+ } else if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Called upon transport error
+ *
+ * @api private
+ */
+
+Socket.prototype.onError = function (err) {
+ debug('socket error %j', err);
+ Socket.priorWebsocketSuccess = false;
+ this.emit('error', err);
+ this.onClose('transport error', err);
+};
+
+/**
+ * Called upon transport close.
+ *
+ * @api private
+ */
+
+Socket.prototype.onClose = function (reason, desc) {
+ if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
+ debug('socket close with reason: "%s"', reason);
+ var self = this;
+
+ // clear timers
+ clearTimeout(this.pingIntervalTimer);
+ clearTimeout(this.pingTimeoutTimer);
+
+ // clean buffers in next tick, so developers can still
+ // grab the buffers on `close` event
+ setTimeout(function() {
+ self.writeBuffer = [];
+ self.callbackBuffer = [];
+ self.prevBufferLen = 0;
+ }, 0);
+
+ // stop event from firing again for transport
+ this.transport.removeAllListeners('close');
+
+ // ensure transport won't stay open
+ this.transport.close();
+
+ // ignore further transport communication
+ this.transport.removeAllListeners();
+
+ // set ready state
+ this.readyState = 'closed';
+
+ // clear session id
+ this.id = null;
+
+ // emit close event
+ this.emit('close', reason, desc);
+ }
+};
+
+/**
+ * Filters upgrades, returning only those matching client transports.
+ *
+ * @param {Array} server upgrades
+ * @api private
+ *
+ */
+
+Socket.prototype.filterUpgrades = function (upgrades) {
+ var filteredUpgrades = [];
+ for (var i = 0, j = upgrades.length; i';
+ iframe = document.createElement(html);
+ } catch (e) {
+ iframe = document.createElement('iframe');
+ iframe.name = self.iframeId;
+ iframe.src = 'javascript:0';
+ }
+
+ iframe.id = self.iframeId;
+
+ self.form.appendChild(iframe);
+ self.iframe = iframe;
+ }
+
+ initIframe();
+
+ // escape \n to prevent it from being converted into \r\n by some UAs
+ // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
+ data = data.replace(rEscapedNewline, '\\\n');
+ this.area.value = data.replace(rNewline, '\\n');
+
+ try {
+ this.form.submit();
+ } catch(e) {}
+
+ if (this.iframe.attachEvent) {
+ this.iframe.onreadystatechange = function(){
+ if (self.iframe.readyState == 'complete') {
+ complete();
+ }
+ };
+ } else {
+ this.iframe.onload = complete;
+ }
+};
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){
+(function (global){
+/**
+ * Module requirements.
+ */
+
+var XMLHttpRequest = _dereq_('xmlhttprequest');
+var Polling = _dereq_('./polling');
+var Emitter = _dereq_('component-emitter');
+var inherit = _dereq_('component-inherit');
+var debug = _dereq_('debug')('engine.io-client:polling-xhr');
+
+/**
+ * Module exports.
+ */
+
+module.exports = XHR;
+module.exports.Request = Request;
+
+/**
+ * Empty function
+ */
+
+function empty(){}
+
+/**
+ * XHR Polling constructor.
+ *
+ * @param {Object} opts
+ * @api public
+ */
+
+function XHR(opts){
+ Polling.call(this, opts);
+
+ if (global.location) {
+ var isSSL = 'https:' == location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (!port) {
+ port = isSSL ? 443 : 80;
+ }
+
+ this.xd = opts.hostname != global.location.hostname ||
+ port != opts.port;
+ this.xs = opts.secure != isSSL;
+ }
+}
+
+/**
+ * Inherits from Polling.
+ */
+
+inherit(XHR, Polling);
+
+/**
+ * XHR supports binary
+ */
+
+XHR.prototype.supportsBinary = true;
+
+/**
+ * Creates a request.
+ *
+ * @param {String} method
+ * @api private
+ */
+
+XHR.prototype.request = function(opts){
+ opts = opts || {};
+ opts.uri = this.uri();
+ opts.xd = this.xd;
+ opts.xs = this.xs;
+ opts.agent = this.agent || false;
+ opts.supportsBinary = this.supportsBinary;
+ opts.enablesXDR = this.enablesXDR;
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ return new Request(opts);
+};
+
+/**
+ * Sends data.
+ *
+ * @param {String} data to send.
+ * @param {Function} called upon flush.
+ * @api private
+ */
+
+XHR.prototype.doWrite = function(data, fn){
+ var isBinary = typeof data !== 'string' && data !== undefined;
+ var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
+ var self = this;
+ req.on('success', fn);
+ req.on('error', function(err){
+ self.onError('xhr post error', err);
+ });
+ this.sendXhr = req;
+};
+
+/**
+ * Starts a poll cycle.
+ *
+ * @api private
+ */
+
+XHR.prototype.doPoll = function(){
+ debug('xhr poll');
+ var req = this.request();
+ var self = this;
+ req.on('data', function(data){
+ self.onData(data);
+ });
+ req.on('error', function(err){
+ self.onError('xhr poll error', err);
+ });
+ this.pollXhr = req;
+};
+
+/**
+ * Request constructor
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+function Request(opts){
+ this.method = opts.method || 'GET';
+ this.uri = opts.uri;
+ this.xd = !!opts.xd;
+ this.xs = !!opts.xs;
+ this.async = false !== opts.async;
+ this.data = undefined != opts.data ? opts.data : null;
+ this.agent = opts.agent;
+ this.isBinary = opts.isBinary;
+ this.supportsBinary = opts.supportsBinary;
+ this.enablesXDR = opts.enablesXDR;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx;
+ this.key = opts.key;
+ this.passphrase = opts.passphrase;
+ this.cert = opts.cert;
+ this.ca = opts.ca;
+ this.ciphers = opts.ciphers;
+ this.rejectUnauthorized = opts.rejectUnauthorized;
+
+ this.create();
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Request.prototype);
+
+/**
+ * Creates the XHR object and sends the request.
+ *
+ * @api private
+ */
+
+Request.prototype.create = function(){
+ var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ var xhr = this.xhr = new XMLHttpRequest(opts);
+ var self = this;
+
+ try {
+ debug('xhr open %s: %s', this.method, this.uri);
+ xhr.open(this.method, this.uri, this.async);
+ if (this.supportsBinary) {
+ // This has to be done after open because Firefox is stupid
+ // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
+ xhr.responseType = 'arraybuffer';
+ }
+
+ if ('POST' == this.method) {
+ try {
+ if (this.isBinary) {
+ xhr.setRequestHeader('Content-type', 'application/octet-stream');
+ } else {
+ xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
+ }
+ } catch (e) {}
+ }
+
+ // ie6 check
+ if ('withCredentials' in xhr) {
+ xhr.withCredentials = true;
+ }
+
+ if (this.hasXDR()) {
+ xhr.onload = function(){
+ self.onLoad();
+ };
+ xhr.onerror = function(){
+ self.onError(xhr.responseText);
+ };
+ } else {
+ xhr.onreadystatechange = function(){
+ if (4 != xhr.readyState) return;
+ if (200 == xhr.status || 1223 == xhr.status) {
+ self.onLoad();
+ } else {
+ // make sure the `error` event handler that's user-set
+ // does not throw in the same tick and gets caught here
+ setTimeout(function(){
+ self.onError(xhr.status);
+ }, 0);
+ }
+ };
+ }
+
+ debug('xhr data %s', this.data);
+ // xhr.send(this.data);
+ } catch (e) {
+ // Need to defer since .create() is called directly fhrom the constructor
+ // and thus the 'error' event can only be only bound *after* this exception
+ // occurs. Therefore, also, we cannot throw here at all.
+ setTimeout(function() {
+ self.onError(e);
+ }, 0);
+ return;
+ }
+
+ if (global.document) {
+ this.index = Request.requestsCount++;
+ Request.requests[this.index] = this;
+ }
+};
+
+/**
+ * Called upon successful response.
+ *
+ * @api private
+ */
+
+Request.prototype.onSuccess = function(){
+ this.emit('success');
+ this.cleanup();
+};
+
+/**
+ * Called if we have data.
+ *
+ * @api private
+ */
+
+Request.prototype.onData = function(data){
+ this.emit('data', data);
+ this.onSuccess();
+};
+
+/**
+ * Called upon error.
+ *
+ * @api private
+ */
+
+Request.prototype.onError = function(err){
+ this.emit('error', err);
+ this.cleanup(true);
+};
+
+/**
+ * Cleans up house.
+ *
+ * @api private
+ */
+
+Request.prototype.cleanup = function(fromError){
+ if ('undefined' == typeof this.xhr || null === this.xhr) {
+ return;
+ }
+ // xmlhttprequest
+ if (this.hasXDR()) {
+ this.xhr.onload = this.xhr.onerror = empty;
+ } else {
+ this.xhr.onreadystatechange = empty;
+ }
+
+ if (fromError) {
+ try {
+ this.xhr.abort();
+ } catch(e) {}
+ }
+
+ if (global.document) {
+ delete Request.requests[this.index];
+ }
+
+ this.xhr = null;
+};
+
+/**
+ * Called upon load.
+ *
+ * @api private
+ */
+
+Request.prototype.onLoad = function(){
+ var data;
+ try {
+ var contentType;
+ try {
+ contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
+ } catch (e) {}
+ if (contentType === 'application/octet-stream') {
+ data = this.xhr.response;
+ } else {
+ if (!this.supportsBinary) {
+ data = this.xhr.responseText;
+ } else {
+ data = 'ok';
+ }
+ }
+ } catch (e) {
+ this.onError(e);
+ }
+ if (null != data) {
+ this.onData(data);
+ }
+};
+
+/**
+ * Check if it has XDomainRequest.
+ *
+ * @api private
+ */
+
+Request.prototype.hasXDR = function(){
+ return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
+};
+
+/**
+ * Aborts the request.
+ *
+ * @api public
+ */
+
+Request.prototype.abort = function(){
+ this.cleanup();
+};
+
+/**
+ * Aborts pending requests when unloading the window. This is needed to prevent
+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is
+ * emitted.
+ */
+
+if (global.document) {
+ Request.requestsCount = 0;
+ Request.requests = {};
+ if (global.attachEvent) {
+ global.attachEvent('onunload', unloadHandler);
+ } else if (global.addEventListener) {
+ global.addEventListener('beforeunload', unloadHandler, false);
+ }
+}
+
+function unloadHandler() {
+ for (var i in Request.requests) {
+ if (Request.requests.hasOwnProperty(i)) {
+ Request.requests[i].abort();
+ }
+ }
+}
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling":18,"component-emitter":9,"component-inherit":21,"debug":22,"xmlhttprequest":20}],18:[function(_dereq_,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var Transport = _dereq_('../transport');
+var parseqs = _dereq_('parseqs');
+var parser = _dereq_('engine.io-parser');
+var inherit = _dereq_('component-inherit');
+var debug = _dereq_('debug')('engine.io-client:polling');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Polling;
+
+/**
+ * Is XHR2 supported?
+ */
+
+var hasXHR2 = (function() {
+ var XMLHttpRequest = _dereq_('xmlhttprequest');
+ var xhr = new XMLHttpRequest({ xdomain: false });
+ return null != xhr.responseType;
+})();
+
+/**
+ * Polling interface.
+ *
+ * @param {Object} opts
+ * @api private
+ */
+
+function Polling(opts){
+ var forceBase64 = (opts && opts.forceBase64);
+ if (!hasXHR2 || forceBase64) {
+ this.supportsBinary = false;
+ }
+ Transport.call(this, opts);
+}
+
+/**
+ * Inherits from Transport.
+ */
+
+inherit(Polling, Transport);
+
+/**
+ * Transport name.
+ */
+
+Polling.prototype.name = 'polling';
+
+/**
+ * Opens the socket (triggers polling). We write a PING message to determine
+ * when the transport is open.
+ *
+ * @api private
+ */
+
+Polling.prototype.doOpen = function(){
+ this.poll();
+};
+
+/**
+ * Pauses polling.
+ *
+ * @param {Function} callback upon buffers are flushed and transport is paused
+ * @api private
+ */
+
+Polling.prototype.pause = function(onPause){
+ var pending = 0;
+ var self = this;
+
+ this.readyState = 'pausing';
+
+ function pause(){
+ debug('paused');
+ self.readyState = 'paused';
+ onPause();
+ }
+
+ if (this.polling || !this.writable) {
+ var total = 0;
+
+ if (this.polling) {
+ debug('we are currently polling - waiting to pause');
+ total++;
+ this.once('pollComplete', function(){
+ debug('pre-pause polling complete');
+ --total || pause();
+ });
+ }
+
+ if (!this.writable) {
+ debug('we are currently writing - waiting to pause');
+ total++;
+ this.once('drain', function(){
+ debug('pre-pause writing complete');
+ --total || pause();
+ });
+ }
+ } else {
+ pause();
+ }
+};
+
+/**
+ * Starts polling cycle.
+ *
+ * @api public
+ */
+
+Polling.prototype.poll = function(){
+ debug('polling');
+ this.polling = true;
+ this.doPoll();
+ this.emit('poll');
+};
+
+/**
+ * Overloads onData to detect payloads.
+ *
+ * @api private
+ */
+
+Polling.prototype.onData = function(data){
+ var self = this;
+ debug('polling got data %s', data);
+ var callback = function(packet, index, total) {
+ // if its the first message we consider the transport open
+ if ('opening' == self.readyState) {
+ self.onOpen();
+ }
+
+ // if its a close packet, we close the ongoing requests
+ if ('close' == packet.type) {
+ self.onClose();
+ return false;
+ }
+
+ // otherwise bypass onData and handle the message
+ self.onPacket(packet);
+ };
+
+ // decode payload
+ parser.decodePayload(data, this.socket.binaryType, callback);
+
+ // if an event did not trigger closing
+ if ('closed' != this.readyState) {
+ // if we got data we're not polling
+ this.polling = false;
+ this.emit('pollComplete');
+
+ if ('open' == this.readyState) {
+ this.poll();
+ } else {
+ debug('ignoring poll - transport state "%s"', this.readyState);
+ }
+ }
+};
+
+/**
+ * For polling, send a close packet.
+ *
+ * @api private
+ */
+
+Polling.prototype.doClose = function(){
+ var self = this;
+
+ function close(){
+ debug('writing close packet');
+ self.write([{ type: 'close' }]);
+ }
+
+ if ('open' == this.readyState) {
+ debug('transport open - closing');
+ close();
+ } else {
+ // in case we're trying to close while
+ // handshaking is in progress (GH-164)
+ debug('transport not open - deferring close');
+ this.once('open', close);
+ }
+};
+
+/**
+ * Writes a packets payload.
+ *
+ * @param {Array} data packets
+ * @param {Function} drain callback
+ * @api private
+ */
+
+Polling.prototype.write = function(packets){
+ var self = this;
+ this.writable = false;
+ var callbackfn = function() {
+ self.writable = true;
+ self.emit('drain');
+ };
+
+ var self = this;
+ parser.encodePayload(packets, this.supportsBinary, function(data) {
+ self.doWrite(data, callbackfn);
+ });
+};
+
+/**
+ * Generates uri for connection.
+ *
+ * @api private
+ */
+
+Polling.prototype.uri = function(){
+ var query = this.query || {};
+ var schema = this.secure ? 'https' : 'http';
+ var port = '';
+
+ // cache busting is forced
+ if (false !== this.timestampRequests) {
+ query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
+ }
+
+ if (!this.supportsBinary && !query.sid) {
+ query.b64 = 1;
+ }
+
+ query = parseqs.encode(query);
+
+ // avoid port if default for schema
+ if (this.port && (('https' == schema && this.port != 443) ||
+ ('http' == schema && this.port != 80))) {
+ port = ':' + this.port;
+ }
+
+ // prepend ? to query
+ if (query.length) {
+ query = '?' + query;
+ }
+
+ return schema + '://' + this.hostname + port + this.path + query;
+};
+
+},{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"xmlhttprequest":20}],19:[function(_dereq_,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var Transport = _dereq_('../transport');
+var parser = _dereq_('engine.io-parser');
+var parseqs = _dereq_('parseqs');
+var inherit = _dereq_('component-inherit');
+var debug = _dereq_('debug')('engine.io-client:websocket');
+
+/**
+ * `ws` exposes a WebSocket-compatible interface in
+ * Node, or the `WebSocket` or `MozWebSocket` globals
+ * in the browser.
+ */
+
+var WebSocket = _dereq_('ws');
+
+/**
+ * Module exports.
+ */
+
+module.exports = WS;
+
+/**
+ * WebSocket transport constructor.
+ *
+ * @api {Object} connection options
+ * @api public
+ */
+
+function WS(opts){
+ var forceBase64 = (opts && opts.forceBase64);
+ if (forceBase64) {
+ this.supportsBinary = false;
+ }
+ Transport.call(this, opts);
+}
+
+/**
+ * Inherits from Transport.
+ */
+
+inherit(WS, Transport);
+
+/**
+ * Transport name.
+ *
+ * @api public
+ */
+
+WS.prototype.name = 'websocket';
+
+/*
+ * WebSockets support binary
+ */
+
+WS.prototype.supportsBinary = true;
+
+/**
+ * Opens socket.
+ *
+ * @api private
+ */
+
+WS.prototype.doOpen = function(){
+ if (!this.check()) {
+ // let probe timeout
+ return;
+ }
+
+ var self = this;
+ var uri = this.uri();
+ var protocols = void(0);
+ var opts = { agent: this.agent };
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ this.ws = new WebSocket(uri, protocols, opts);
+
+ if (this.ws.binaryType === undefined) {
+ this.supportsBinary = false;
+ }
+
+ this.ws.binaryType = 'arraybuffer';
+ this.addEventListeners();
+};
+
+/**
+ * Adds event listeners to the socket
+ *
+ * @api private
+ */
+
+WS.prototype.addEventListeners = function(){
+ var self = this;
+
+ this.ws.onopen = function(){
+ self.onOpen();
+ };
+ this.ws.onclose = function(){
+ self.onClose();
+ };
+ this.ws.onmessage = function(ev){
+ self.onData(ev.data);
+ };
+ this.ws.onerror = function(e){
+ self.onError('websocket error', e);
+ };
+};
+
+/**
+ * Override `onData` to use a timer on iOS.
+ * See: https://gist.github.com/mloughran/2052006
+ *
+ * @api private
+ */
+
+if ('undefined' != typeof navigator
+ && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
+ WS.prototype.onData = function(data){
+ var self = this;
+ setTimeout(function(){
+ Transport.prototype.onData.call(self, data);
+ }, 0);
+ };
+}
+
+/**
+ * Writes data to socket.
+ *
+ * @param {Array} array of packets.
+ * @api private
+ */
+
+WS.prototype.write = function(packets){
+ var self = this;
+ this.writable = false;
+ // encodePacket efficient as it uses WS framing
+ // no need for encodePayload
+ for (var i = 0, l = packets.length; i < l; i++) {
+ parser.encodePacket(packets[i], this.supportsBinary, function(data) {
+ //Sometimes the websocket has already been closed but the browser didn't
+ //have a chance of informing us about it yet, in that case send will
+ //throw an error
+ try {
+ self.ws.send(data);
+ } catch (e){
+ debug('websocket closed before onclose event');
+ }
+ });
+ }
+
+ function ondrain() {
+ self.writable = true;
+ self.emit('drain');
+ }
+ // fake drain
+ // defer to next tick to allow Socket to clear writeBuffer
+ setTimeout(ondrain, 0);
+};
+
+/**
+ * Called upon close
+ *
+ * @api private
+ */
+
+WS.prototype.onClose = function(){
+ Transport.prototype.onClose.call(this);
+};
+
+/**
+ * Closes socket.
+ *
+ * @api private
+ */
+
+WS.prototype.doClose = function(){
+ if (typeof this.ws !== 'undefined') {
+ this.ws.close();
+ }
+};
+
+/**
+ * Generates uri for connection.
+ *
+ * @api private
+ */
+
+WS.prototype.uri = function(){
+ var query = this.query || {};
+ var schema = this.secure ? 'wss' : 'ws';
+ var port = '';
+
+ // avoid port if default for schema
+ if (this.port && (('wss' == schema && this.port != 443)
+ || ('ws' == schema && this.port != 80))) {
+ port = ':' + this.port;
+ }
+
+ // append timestamp to URI
+ if (this.timestampRequests) {
+ query[this.timestampParam] = +new Date;
+ }
+
+ // communicate binary support capabilities
+ if (!this.supportsBinary) {
+ query.b64 = 1;
+ }
+
+ query = parseqs.encode(query);
+
+ // prepend ? to query
+ if (query.length) {
+ query = '?' + query;
+ }
+
+ return schema + '://' + this.hostname + port + this.path + query;
+};
+
+/**
+ * Feature detection for WebSocket.
+ *
+ * @return {Boolean} whether this transport is available.
+ * @api public
+ */
+
+WS.prototype.check = function(){
+ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
+};
+
+},{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"ws":35}],20:[function(_dereq_,module,exports){
+// browser shim for xmlhttprequest module
+var hasCORS = _dereq_('has-cors');
+
+module.exports = function(opts) {
+ var xdomain = opts.xdomain;
+
+ // scheme must be same when usign XDomainRequest
+ // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
+ var xscheme = opts.xscheme;
+
+ // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
+ // https://github.com/Automattic/engine.io-client/pull/217
+ var enablesXDR = opts.enablesXDR;
+
+ // XMLHttpRequest can be disabled on IE
+ try {
+ if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
+ return new XMLHttpRequest();
+ }
+ } catch (e) { }
+
+ // Use XDomainRequest for IE8 if enablesXDR is true
+ // because loading bar keeps flashing when using jsonp-polling
+ // https://github.com/yujiosaka/socke.io-ie8-loading-example
+ try {
+ if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
+ return new XDomainRequest();
+ }
+ } catch (e) { }
+
+ if (!xdomain) {
+ try {
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ } catch(e) { }
+ }
+}
+
+},{"has-cors":38}],21:[function(_dereq_,module,exports){
+
+module.exports = function(a, b){
+ var fn = function(){};
+ fn.prototype = b.prototype;
+ a.prototype = new fn;
+ a.prototype.constructor = a;
+};
+},{}],22:[function(_dereq_,module,exports){
+
+/**
+ * This is the web browser implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = _dereq_('./debug');
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+
+/**
+ * Colors.
+ */
+
+exports.colors = [
+ 'lightseagreen',
+ 'forestgreen',
+ 'goldenrod',
+ 'dodgerblue',
+ 'darkorchid',
+ 'crimson'
+];
+
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+function useColors() {
+ // is webkit? http://stackoverflow.com/a/16459606/376773
+ return ('WebkitAppearance' in document.documentElement.style) ||
+ // is firebug? http://stackoverflow.com/a/398120/376773
+ (window.console && (console.firebug || (console.exception && console.table))) ||
+ // is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
+}
+
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+exports.formatters.j = function(v) {
+ return JSON.stringify(v);
+};
+
+
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+function formatArgs() {
+ var args = arguments;
+ var useColors = this.useColors;
+
+ args[0] = (useColors ? '%c' : '')
+ + this.namespace
+ + (useColors ? ' %c' : ' ')
+ + args[0]
+ + (useColors ? '%c ' : ' ')
+ + '+' + exports.humanize(this.diff);
+
+ if (!useColors) return args;
+
+ var c = 'color: ' + this.color;
+ args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
+
+ // the final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ var index = 0;
+ var lastC = 0;
+ args[0].replace(/%[a-z%]/g, function(match) {
+ if ('%%' === match) return;
+ index++;
+ if ('%c' === match) {
+ // we only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+
+ args.splice(lastC, 0, c);
+ return args;
+}
+
+/**
+ * Invokes `console.log()` when available.
+ * No-op when `console.log` is not a "function".
+ *
+ * @api public
+ */
+
+function log() {
+ // This hackery is required for IE8,
+ // where the `console.log` function doesn't have 'apply'
+ return 'object' == typeof console
+ && 'function' == typeof console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+}
+
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+function save(namespaces) {
+ try {
+ if (null == namespaces) {
+ localStorage.removeItem('debug');
+ } else {
+ localStorage.debug = namespaces;
+ }
+ } catch(e) {}
+}
+
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+function load() {
+ var r;
+ try {
+ r = localStorage.debug;
+ } catch(e) {}
+ return r;
+}
+
+/**
+ * Enable namespaces listed in `localStorage.debug` initially.
+ */
+
+exports.enable(load());
+
+},{"./debug":23}],23:[function(_dereq_,module,exports){
+
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = debug;
+exports.coerce = coerce;
+exports.disable = disable;
+exports.enable = enable;
+exports.enabled = enabled;
+exports.humanize = _dereq_('ms');
+
+/**
+ * The currently active debug mode names, and names to skip.
+ */
+
+exports.names = [];
+exports.skips = [];
+
+/**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lowercased letter, i.e. "n".
+ */
+
+exports.formatters = {};
+
+/**
+ * Previously assigned color.
+ */
+
+var prevColor = 0;
+
+/**
+ * Previous log timestamp.
+ */
+
+var prevTime;
+
+/**
+ * Select a color.
+ *
+ * @return {Number}
+ * @api private
+ */
+
+function selectColor() {
+ return exports.colors[prevColor++ % exports.colors.length];
+}
+
+/**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+function debug(namespace) {
+
+ // define the `disabled` version
+ function disabled() {
+ }
+ disabled.enabled = false;
+
+ // define the `enabled` version
+ function enabled() {
+
+ var self = enabled;
+
+ // set `diff` timestamp
+ var curr = +new Date();
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ // add the `color` if not set
+ if (null == self.useColors) self.useColors = exports.useColors();
+ if (null == self.color && self.useColors) self.color = selectColor();
+
+ var args = Array.prototype.slice.call(arguments);
+
+ args[0] = exports.coerce(args[0]);
+
+ if ('string' !== typeof args[0]) {
+ // anything else let's inspect with %o
+ args = ['%o'].concat(args);
+ }
+
+ // apply any `formatters` transformations
+ var index = 0;
+ args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
+ // if we encounter an escaped % then don't increase the array index
+ if (match === '%%') return match;
+ index++;
+ var formatter = exports.formatters[format];
+ if ('function' === typeof formatter) {
+ var val = args[index];
+ match = formatter.call(self, val);
+
+ // now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
+
+ if ('function' === typeof exports.formatArgs) {
+ args = exports.formatArgs.apply(self, args);
+ }
+ var logFn = enabled.log || exports.log || console.log.bind(console);
+ logFn.apply(self, args);
+ }
+ enabled.enabled = true;
+
+ var fn = exports.enabled(namespace) ? enabled : disabled;
+
+ fn.namespace = namespace;
+
+ return fn;
+}
+
+/**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+function enable(namespaces) {
+ exports.save(namespaces);
+
+ var split = (namespaces || '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ if (!split[i]) continue; // ignore empty strings
+ namespaces = split[i].replace(/\*/g, '.*?');
+ if (namespaces[0] === '-') {
+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ exports.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+}
+
+/**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+function disable() {
+ exports.enable('');
+}
+
+/**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+function enabled(name) {
+ var i, len;
+ for (i = 0, len = exports.skips.length; i < len; i++) {
+ if (exports.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (i = 0, len = exports.names.length; i < len; i++) {
+ if (exports.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
+
+},{"ms":24}],24:[function(_dereq_,module,exports){
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} options
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options){
+ options = options || {};
+ if ('string' == typeof val) return parse(val);
+ return options.long
+ ? long(val)
+ : short(val);
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
+ if (!match) return;
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'y':
+ return n * y;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 's':
+ return n * s;
+ case 'ms':
+ return n;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function short(ms) {
+ if (ms >= d) return Math.round(ms / d) + 'd';
+ if (ms >= h) return Math.round(ms / h) + 'h';
+ if (ms >= m) return Math.round(ms / m) + 'm';
+ if (ms >= s) return Math.round(ms / s) + 's';
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function long(ms) {
+ return plural(ms, d, 'day')
+ || plural(ms, h, 'hour')
+ || plural(ms, m, 'minute')
+ || plural(ms, s, 'second')
+ || ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, n, name) {
+ if (ms < n) return;
+ if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
+ return Math.ceil(ms / n) + ' ' + name + 's';
+}
+
+},{}],25:[function(_dereq_,module,exports){
+(function (global){
+/**
+ * Module dependencies.
+ */
+
+var keys = _dereq_('./keys');
+var hasBinary = _dereq_('has-binary');
+var sliceBuffer = _dereq_('arraybuffer.slice');
+var base64encoder = _dereq_('base64-arraybuffer');
+var after = _dereq_('after');
+var utf8 = _dereq_('utf8');
+
+/**
+ * Check if we are running an android browser. That requires us to use
+ * ArrayBuffer with polling transports...
+ *
+ * http://ghinda.net/jpeg-blob-ajax-android/
+ */
+
+var isAndroid = navigator.userAgent.match(/Android/i);
+
+/**
+ * Check if we are running in PhantomJS.
+ * Uploading a Blob with PhantomJS does not work correctly, as reported here:
+ * https://github.com/ariya/phantomjs/issues/11395
+ * @type boolean
+ */
+var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
+
+/**
+ * When true, avoids using Blobs to encode payloads.
+ * @type boolean
+ */
+var dontSendBlobs = isAndroid || isPhantomJS;
+
+/**
+ * Current protocol version.
+ */
+
+exports.protocol = 3;
+
+/**
+ * Packet types.
+ */
+
+var packets = exports.packets = {
+ open: 0 // non-ws
+ , close: 1 // non-ws
+ , ping: 2
+ , pong: 3
+ , message: 4
+ , upgrade: 5
+ , noop: 6
+};
+
+var packetslist = keys(packets);
+
+/**
+ * Premade error packet.
+ */
+
+var err = { type: 'error', data: 'parser error' };
+
+/**
+ * Create a blob api even for blob builder when vendor prefixes exist
+ */
+
+var Blob = _dereq_('blob');
+
+/**
+ * Encodes a packet.
+ *
+ * [ ]
+ *
+ * Example:
+ *
+ * 5hello world
+ * 3
+ * 4
+ *
+ * Binary is encoded in an identical principle
+ *
+ * @api private
+ */
+
+exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
+ if ('function' == typeof supportsBinary) {
+ callback = supportsBinary;
+ supportsBinary = false;
+ }
+
+ if ('function' == typeof utf8encode) {
+ callback = utf8encode;
+ utf8encode = null;
+ }
+
+ var data = (packet.data === undefined)
+ ? undefined
+ : packet.data.buffer || packet.data;
+
+ if (global.ArrayBuffer && data instanceof ArrayBuffer) {
+ return encodeArrayBuffer(packet, supportsBinary, callback);
+ } else if (Blob && data instanceof global.Blob) {
+ return encodeBlob(packet, supportsBinary, callback);
+ }
+
+ // might be an object with { base64: true, data: dataAsBase64String }
+ if (data && data.base64) {
+ return encodeBase64Object(packet, callback);
+ }
+
+ // Sending data as a utf-8 string
+ var encoded = packets[packet.type];
+
+ // data fragment is optional
+ if (undefined !== packet.data) {
+ encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
+ }
+
+ return callback('' + encoded);
+
+};
+
+function encodeBase64Object(packet, callback) {
+ // packet data is an object { base64: true, data: dataAsBase64String }
+ var message = 'b' + exports.packets[packet.type] + packet.data.data;
+ return callback(message);
+}
+
+/**
+ * Encode packet helpers for binary types
+ */
+
+function encodeArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ var data = packet.data;
+ var contentArray = new Uint8Array(data);
+ var resultBuffer = new Uint8Array(1 + data.byteLength);
+
+ resultBuffer[0] = packets[packet.type];
+ for (var i = 0; i < contentArray.length; i++) {
+ resultBuffer[i+1] = contentArray[i];
+ }
+
+ return callback(resultBuffer.buffer);
+}
+
+function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ var fr = new FileReader();
+ fr.onload = function() {
+ packet.data = fr.result;
+ exports.encodePacket(packet, supportsBinary, true, callback);
+ };
+ return fr.readAsArrayBuffer(packet.data);
+}
+
+function encodeBlob(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ if (dontSendBlobs) {
+ return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
+ }
+
+ var length = new Uint8Array(1);
+ length[0] = packets[packet.type];
+ var blob = new Blob([length.buffer, packet.data]);
+
+ return callback(blob);
+}
+
+/**
+ * Encodes a packet with binary data in a base64 string
+ *
+ * @param {Object} packet, has `type` and `data`
+ * @return {String} base64 encoded message
+ */
+
+exports.encodeBase64Packet = function(packet, callback) {
+ var message = 'b' + exports.packets[packet.type];
+ if (Blob && packet.data instanceof Blob) {
+ var fr = new FileReader();
+ fr.onload = function() {
+ var b64 = fr.result.split(',')[1];
+ callback(message + b64);
+ };
+ return fr.readAsDataURL(packet.data);
+ }
+
+ var b64data;
+ try {
+ b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply with typed arrays
+ var typed = new Uint8Array(packet.data);
+ var basic = new Array(typed.length);
+ for (var i = 0; i < typed.length; i++) {
+ basic[i] = typed[i];
+ }
+ b64data = String.fromCharCode.apply(null, basic);
+ }
+ message += global.btoa(b64data);
+ return callback(message);
+};
+
+/**
+ * Decodes a packet. Changes format to Blob if requested.
+ *
+ * @return {Object} with `type` and `data` (if any)
+ * @api private
+ */
+
+exports.decodePacket = function (data, binaryType, utf8decode) {
+ // String data
+ if (typeof data == 'string' || data === undefined) {
+ if (data.charAt(0) == 'b') {
+ return exports.decodeBase64Packet(data.substr(1), binaryType);
+ }
+
+ if (utf8decode) {
+ try {
+ data = utf8.decode(data);
+ } catch (e) {
+ return err;
+ }
+ }
+ var type = data.charAt(0);
+
+ if (Number(type) != type || !packetslist[type]) {
+ return err;
+ }
+
+ if (data.length > 1) {
+ return { type: packetslist[type], data: data.substring(1) };
+ } else {
+ return { type: packetslist[type] };
+ }
+ }
+
+ var asArray = new Uint8Array(data);
+ var type = asArray[0];
+ var rest = sliceBuffer(data, 1);
+ if (Blob && binaryType === 'blob') {
+ rest = new Blob([rest]);
+ }
+ return { type: packetslist[type], data: rest };
+};
+
+/**
+ * Decodes a packet encoded in a base64 string
+ *
+ * @param {String} base64 encoded message
+ * @return {Object} with `type` and `data` (if any)
+ */
+
+exports.decodeBase64Packet = function(msg, binaryType) {
+ var type = packetslist[msg.charAt(0)];
+ if (!global.ArrayBuffer) {
+ return { type: type, data: { base64: true, data: msg.substr(1) } };
+ }
+
+ var data = base64encoder.decode(msg.substr(1));
+
+ if (binaryType === 'blob' && Blob) {
+ data = new Blob([data]);
+ }
+
+ return { type: type, data: data };
+};
+
+/**
+ * Encodes multiple messages (payload).
+ *
+ * :data
+ *
+ * Example:
+ *
+ * 11:hello world2:hi
+ *
+ * If any contents are binary, they will be encoded as base64 strings. Base64
+ * encoded strings are marked with a b before the length specifier
+ *
+ * @param {Array} packets
+ * @api private
+ */
+
+exports.encodePayload = function (packets, supportsBinary, callback) {
+ if (typeof supportsBinary == 'function') {
+ callback = supportsBinary;
+ supportsBinary = null;
+ }
+
+ var isBinary = hasBinary(packets);
+
+ if (supportsBinary && isBinary) {
+ if (Blob && !dontSendBlobs) {
+ return exports.encodePayloadAsBlob(packets, callback);
+ }
+
+ return exports.encodePayloadAsArrayBuffer(packets, callback);
+ }
+
+ if (!packets.length) {
+ return callback('0:');
+ }
+
+ function setLengthHeader(message) {
+ return message.length + ':' + message;
+ }
+
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
+ doneCallback(null, setLengthHeader(message));
+ });
+ }
+
+ map(packets, encodeOne, function(err, results) {
+ return callback(results.join(''));
+ });
+};
+
+/**
+ * Async array map using after
+ */
+
+function map(ary, each, done) {
+ var result = new Array(ary.length);
+ var next = after(ary.length, done);
+
+ var eachWithIndex = function(i, el, cb) {
+ each(el, function(error, msg) {
+ result[i] = msg;
+ cb(error, result);
+ });
+ };
+
+ for (var i = 0; i < ary.length; i++) {
+ eachWithIndex(i, ary[i], next);
+ }
+}
+
+/*
+ * Decodes data when a payload is maybe expected. Possible binary contents are
+ * decoded from their base64 representation
+ *
+ * @param {String} data, callback method
+ * @api public
+ */
+
+exports.decodePayload = function (data, binaryType, callback) {
+ if (typeof data != 'string') {
+ return exports.decodePayloadAsBinary(data, binaryType, callback);
+ }
+
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
+
+ var packet;
+ if (data == '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var length = ''
+ , n, msg;
+
+ for (var i = 0, l = data.length; i < l; i++) {
+ var chr = data.charAt(i);
+
+ if (':' != chr) {
+ length += chr;
+ } else {
+ if ('' == length || (length != (n = Number(length)))) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ msg = data.substr(i + 1, n);
+
+ if (length != msg.length) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ if (msg.length) {
+ packet = exports.decodePacket(msg, binaryType, true);
+
+ if (err.type == packet.type && err.data == packet.data) {
+ // parser error in individual packet - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var ret = callback(packet, i + n, l);
+ if (false === ret) return;
+ }
+
+ // advance cursor
+ i += n;
+ length = '';
+ }
+ }
+
+ if (length != '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+};
+
+/**
+ * Encodes multiple messages (payload) as binary.
+ *
+ * <1 = binary, 0 = string>[...]
+ *
+ * Example:
+ * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
+ *
+ * @param {Array} packets
+ * @return {ArrayBuffer} encoded payload
+ * @api private
+ */
+
+exports.encodePayloadAsArrayBuffer = function(packets, callback) {
+ if (!packets.length) {
+ return callback(new ArrayBuffer(0));
+ }
+
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(data) {
+ return doneCallback(null, data);
+ });
+ }
+
+ map(packets, encodeOne, function(err, encodedPackets) {
+ var totalLength = encodedPackets.reduce(function(acc, p) {
+ var len;
+ if (typeof p === 'string'){
+ len = p.length;
+ } else {
+ len = p.byteLength;
+ }
+ return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
+ }, 0);
+
+ var resultArray = new Uint8Array(totalLength);
+
+ var bufferIndex = 0;
+ encodedPackets.forEach(function(p) {
+ var isString = typeof p === 'string';
+ var ab = p;
+ if (isString) {
+ var view = new Uint8Array(p.length);
+ for (var i = 0; i < p.length; i++) {
+ view[i] = p.charCodeAt(i);
+ }
+ ab = view.buffer;
+ }
+
+ if (isString) { // not true binary
+ resultArray[bufferIndex++] = 0;
+ } else { // true binary
+ resultArray[bufferIndex++] = 1;
+ }
+
+ var lenStr = ab.byteLength.toString();
+ for (var i = 0; i < lenStr.length; i++) {
+ resultArray[bufferIndex++] = parseInt(lenStr[i]);
+ }
+ resultArray[bufferIndex++] = 255;
+
+ var view = new Uint8Array(ab);
+ for (var i = 0; i < view.length; i++) {
+ resultArray[bufferIndex++] = view[i];
+ }
+ });
+
+ return callback(resultArray.buffer);
+ });
+};
+
+/**
+ * Encode as Blob
+ */
+
+exports.encodePayloadAsBlob = function(packets, callback) {
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(encoded) {
+ var binaryIdentifier = new Uint8Array(1);
+ binaryIdentifier[0] = 1;
+ if (typeof encoded === 'string') {
+ var view = new Uint8Array(encoded.length);
+ for (var i = 0; i < encoded.length; i++) {
+ view[i] = encoded.charCodeAt(i);
+ }
+ encoded = view.buffer;
+ binaryIdentifier[0] = 0;
+ }
+
+ var len = (encoded instanceof ArrayBuffer)
+ ? encoded.byteLength
+ : encoded.size;
+
+ var lenStr = len.toString();
+ var lengthAry = new Uint8Array(lenStr.length + 1);
+ for (var i = 0; i < lenStr.length; i++) {
+ lengthAry[i] = parseInt(lenStr[i]);
+ }
+ lengthAry[lenStr.length] = 255;
+
+ if (Blob) {
+ var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
+ doneCallback(null, blob);
+ }
+ });
+ }
+
+ map(packets, encodeOne, function(err, results) {
+ return callback(new Blob(results));
+ });
+};
+
+/*
+ * Decodes data when a payload is maybe expected. Strings are decoded by
+ * interpreting each byte as a key code for entries marked to start with 0. See
+ * description of encodePayloadAsBinary
+ *
+ * @param {ArrayBuffer} data, callback method
+ * @api public
+ */
+
+exports.decodePayloadAsBinary = function (data, binaryType, callback) {
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
+
+ var bufferTail = data;
+ var buffers = [];
+
+ var numberTooLong = false;
+ while (bufferTail.byteLength > 0) {
+ var tailArray = new Uint8Array(bufferTail);
+ var isString = tailArray[0] === 0;
+ var msgLength = '';
+
+ for (var i = 1; ; i++) {
+ if (tailArray[i] == 255) break;
+
+ if (msgLength.length > 310) {
+ numberTooLong = true;
+ break;
+ }
+
+ msgLength += tailArray[i];
+ }
+
+ if(numberTooLong) return callback(err, 0, 1);
+
+ bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
+ msgLength = parseInt(msgLength);
+
+ var msg = sliceBuffer(bufferTail, 0, msgLength);
+ if (isString) {
+ try {
+ msg = String.fromCharCode.apply(null, new Uint8Array(msg));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply to typed arrays
+ var typed = new Uint8Array(msg);
+ msg = '';
+ for (var i = 0; i < typed.length; i++) {
+ msg += String.fromCharCode(typed[i]);
+ }
+ }
+ }
+
+ buffers.push(msg);
+ bufferTail = sliceBuffer(bufferTail, msgLength);
+ }
+
+ var total = buffers.length;
+ buffers.forEach(function(buffer, i) {
+ callback(exports.decodePacket(buffer, binaryType, true), i, total);
+ });
+};
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./keys":26,"after":27,"arraybuffer.slice":28,"base64-arraybuffer":29,"blob":30,"has-binary":36,"utf8":31}],26:[function(_dereq_,module,exports){
+
+/**
+ * Gets the keys for an object.
+ *
+ * @return {Array} keys
+ * @api private
+ */
+
+module.exports = Object.keys || function keys (obj){
+ var arr = [];
+ var has = Object.prototype.hasOwnProperty;
+
+ for (var i in obj) {
+ if (has.call(obj, i)) {
+ arr.push(i);
+ }
+ }
+ return arr;
+};
+
+},{}],27:[function(_dereq_,module,exports){
+module.exports = after
+
+function after(count, callback, err_cb) {
+ var bail = false
+ err_cb = err_cb || noop
+ proxy.count = count
+
+ return (count === 0) ? callback() : proxy
+
+ function proxy(err, result) {
+ if (proxy.count <= 0) {
+ throw new Error('after called too many times')
+ }
+ --proxy.count
+
+ // after first error, rest are passed to err_cb
+ if (err) {
+ bail = true
+ callback(err)
+ // future error callbacks will go to error handler
+ callback = err_cb
+ } else if (proxy.count === 0 && !bail) {
+ callback(null, result)
+ }
+ }
+}
+
+function noop() {}
+
+},{}],28:[function(_dereq_,module,exports){
+/**
+ * An abstraction for slicing an arraybuffer even when
+ * ArrayBuffer.prototype.slice is not supported
+ *
+ * @api public
+ */
+
+module.exports = function(arraybuffer, start, end) {
+ var bytes = arraybuffer.byteLength;
+ start = start || 0;
+ end = end || bytes;
+
+ if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
+
+ if (start < 0) { start += bytes; }
+ if (end < 0) { end += bytes; }
+ if (end > bytes) { end = bytes; }
+
+ if (start >= bytes || start >= end || bytes === 0) {
+ return new ArrayBuffer(0);
+ }
+
+ var abv = new Uint8Array(arraybuffer);
+ var result = new Uint8Array(end - start);
+ for (var i = start, ii = 0; i < end; i++, ii++) {
+ result[ii] = abv[i];
+ }
+ return result.buffer;
+};
+
+},{}],29:[function(_dereq_,module,exports){
+/*
+ * base64-arraybuffer
+ * https://github.com/niklasvh/base64-arraybuffer
+ *
+ * Copyright (c) 2012 Niklas von Hertzen
+ * Licensed under the MIT license.
+ */
+(function(chars){
+ "use strict";
+
+ exports.encode = function(arraybuffer) {
+ var bytes = new Uint8Array(arraybuffer),
+ i, len = bytes.length, base64 = "";
+
+ for (i = 0; i < len; i+=3) {
+ base64 += chars[bytes[i] >> 2];
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
+ base64 += chars[bytes[i + 2] & 63];
+ }
+
+ if ((len % 3) === 2) {
+ base64 = base64.substring(0, base64.length - 1) + "=";
+ } else if (len % 3 === 1) {
+ base64 = base64.substring(0, base64.length - 2) + "==";
+ }
+
+ return base64;
+ };
+
+ exports.decode = function(base64) {
+ var bufferLength = base64.length * 0.75,
+ len = base64.length, i, p = 0,
+ encoded1, encoded2, encoded3, encoded4;
+
+ if (base64[base64.length - 1] === "=") {
+ bufferLength--;
+ if (base64[base64.length - 2] === "=") {
+ bufferLength--;
+ }
+ }
+
+ var arraybuffer = new ArrayBuffer(bufferLength),
+ bytes = new Uint8Array(arraybuffer);
+
+ for (i = 0; i < len; i+=4) {
+ encoded1 = chars.indexOf(base64[i]);
+ encoded2 = chars.indexOf(base64[i+1]);
+ encoded3 = chars.indexOf(base64[i+2]);
+ encoded4 = chars.indexOf(base64[i+3]);
+
+ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
+ }
+
+ return arraybuffer;
+ };
+})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
+
+},{}],30:[function(_dereq_,module,exports){
+(function (global){
+/**
+ * Create a blob builder even when vendor prefixes exist
+ */
+
+var BlobBuilder = global.BlobBuilder
+ || global.WebKitBlobBuilder
+ || global.MSBlobBuilder
+ || global.MozBlobBuilder;
+
+/**
+ * Check if Blob constructor is supported
+ */
+
+var blobSupported = (function() {
+ try {
+ var a = new Blob(['hi']);
+ return a.size === 2;
+ } catch(e) {
+ return false;
+ }
+})();
+
+/**
+ * Check if Blob constructor supports ArrayBufferViews
+ * Fails in Safari 6, so we need to map to ArrayBuffers there.
+ */
+
+var blobSupportsArrayBufferView = blobSupported && (function() {
+ try {
+ var b = new Blob([new Uint8Array([1,2])]);
+ return b.size === 2;
+ } catch(e) {
+ return false;
+ }
+})();
+
+/**
+ * Check if BlobBuilder is supported
+ */
+
+var blobBuilderSupported = BlobBuilder
+ && BlobBuilder.prototype.append
+ && BlobBuilder.prototype.getBlob;
+
+/**
+ * Helper function that maps ArrayBufferViews to ArrayBuffers
+ * Used by BlobBuilder constructor and old browsers that didn't
+ * support it in the Blob constructor.
+ */
+
+function mapArrayBufferViews(ary) {
+ for (var i = 0; i < ary.length; i++) {
+ var chunk = ary[i];
+ if (chunk.buffer instanceof ArrayBuffer) {
+ var buf = chunk.buffer;
+
+ // if this is a subarray, make a copy so we only
+ // include the subarray region from the underlying buffer
+ if (chunk.byteLength !== buf.byteLength) {
+ var copy = new Uint8Array(chunk.byteLength);
+ copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
+ buf = copy.buffer;
+ }
+
+ ary[i] = buf;
+ }
+ }
+}
+
+function BlobBuilderConstructor(ary, options) {
+ options = options || {};
+
+ var bb = new BlobBuilder();
+ mapArrayBufferViews(ary);
+
+ for (var i = 0; i < ary.length; i++) {
+ bb.append(ary[i]);
+ }
+
+ return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
+};
+
+function BlobConstructor(ary, options) {
+ mapArrayBufferViews(ary);
+ return new Blob(ary, options || {});
+};
+
+module.exports = (function() {
+ if (blobSupported) {
+ return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
+ } else if (blobBuilderSupported) {
+ return BlobBuilderConstructor;
+ } else {
+ return undefined;
+ }
+})();
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],31:[function(_dereq_,module,exports){
+(function (global){
+/*! https://mths.be/utf8js v2.0.0 by @mathias */
+;(function(root) {
+
+ // Detect free variables `exports`
+ var freeExports = typeof exports == 'object' && exports;
+
+ // Detect free variable `module`
+ var freeModule = typeof module == 'object' && module &&
+ module.exports == freeExports && module;
+
+ // Detect free variable `global`, from Node.js or Browserified code,
+ // and use it as `root`
+ var freeGlobal = typeof global == 'object' && global;
+ if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
+ root = freeGlobal;
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ var stringFromCharCode = String.fromCharCode;
+
+ // Taken from https://mths.be/punycode
+ function ucs2decode(string) {
+ var output = [];
+ var counter = 0;
+ var length = string.length;
+ var value;
+ var extra;
+ while (counter < length) {
+ value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // high surrogate, and there is a next character
+ extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // unmatched surrogate; only append this code unit, in case the next
+ // code unit is the high surrogate of a surrogate pair
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
+
+ // Taken from https://mths.be/punycode
+ function ucs2encode(array) {
+ var length = array.length;
+ var index = -1;
+ var value;
+ var output = '';
+ while (++index < length) {
+ value = array[index];
+ if (value > 0xFFFF) {
+ value -= 0x10000;
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+ value = 0xDC00 | value & 0x3FF;
+ }
+ output += stringFromCharCode(value);
+ }
+ return output;
+ }
+
+ function checkScalarValue(codePoint) {
+ if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
+ throw Error(
+ 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
+ ' is not a scalar value'
+ );
+ }
+ }
+ /*--------------------------------------------------------------------------*/
+
+ function createByte(codePoint, shift) {
+ return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
+ }
+
+ function encodeCodePoint(codePoint) {
+ if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
+ return stringFromCharCode(codePoint);
+ }
+ var symbol = '';
+ if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
+ symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
+ }
+ else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
+ checkScalarValue(codePoint);
+ symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
+ symbol += createByte(codePoint, 6);
+ }
+ else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
+ symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
+ symbol += createByte(codePoint, 12);
+ symbol += createByte(codePoint, 6);
+ }
+ symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
+ return symbol;
+ }
+
+ function utf8encode(string) {
+ var codePoints = ucs2decode(string);
+ var length = codePoints.length;
+ var index = -1;
+ var codePoint;
+ var byteString = '';
+ while (++index < length) {
+ codePoint = codePoints[index];
+ byteString += encodeCodePoint(codePoint);
+ }
+ return byteString;
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ function readContinuationByte() {
+ if (byteIndex >= byteCount) {
+ throw Error('Invalid byte index');
+ }
+
+ var continuationByte = byteArray[byteIndex] & 0xFF;
+ byteIndex++;
+
+ if ((continuationByte & 0xC0) == 0x80) {
+ return continuationByte & 0x3F;
+ }
+
+ // If we end up here, it’s not a continuation byte
+ throw Error('Invalid continuation byte');
+ }
+
+ function decodeSymbol() {
+ var byte1;
+ var byte2;
+ var byte3;
+ var byte4;
+ var codePoint;
+
+ if (byteIndex > byteCount) {
+ throw Error('Invalid byte index');
+ }
+
+ if (byteIndex == byteCount) {
+ return false;
+ }
+
+ // Read first byte
+ byte1 = byteArray[byteIndex] & 0xFF;
+ byteIndex++;
+
+ // 1-byte sequence (no continuation bytes)
+ if ((byte1 & 0x80) == 0) {
+ return byte1;
+ }
+
+ // 2-byte sequence
+ if ((byte1 & 0xE0) == 0xC0) {
+ var byte2 = readContinuationByte();
+ codePoint = ((byte1 & 0x1F) << 6) | byte2;
+ if (codePoint >= 0x80) {
+ return codePoint;
+ } else {
+ throw Error('Invalid continuation byte');
+ }
+ }
+
+ // 3-byte sequence (may include unpaired surrogates)
+ if ((byte1 & 0xF0) == 0xE0) {
+ byte2 = readContinuationByte();
+ byte3 = readContinuationByte();
+ codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
+ if (codePoint >= 0x0800) {
+ checkScalarValue(codePoint);
+ return codePoint;
+ } else {
+ throw Error('Invalid continuation byte');
+ }
+ }
+
+ // 4-byte sequence
+ if ((byte1 & 0xF8) == 0xF0) {
+ byte2 = readContinuationByte();
+ byte3 = readContinuationByte();
+ byte4 = readContinuationByte();
+ codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
+ (byte3 << 0x06) | byte4;
+ if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
+ return codePoint;
+ }
+ }
+
+ throw Error('Invalid UTF-8 detected');
+ }
+
+ var byteArray;
+ var byteCount;
+ var byteIndex;
+ function utf8decode(byteString) {
+ byteArray = ucs2decode(byteString);
+ byteCount = byteArray.length;
+ byteIndex = 0;
+ var codePoints = [];
+ var tmp;
+ while ((tmp = decodeSymbol()) !== false) {
+ codePoints.push(tmp);
+ }
+ return ucs2encode(codePoints);
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ var utf8 = {
+ 'version': '2.0.0',
+ 'encode': utf8encode,
+ 'decode': utf8decode
+ };
+
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+ if (
+ typeof define == 'function' &&
+ typeof define.amd == 'object' &&
+ define.amd
+ ) {
+ define(function() {
+ return utf8;
+ });
+ } else if (freeExports && !freeExports.nodeType) {
+ if (freeModule) { // in Node.js or RingoJS v0.8.0+
+ freeModule.exports = utf8;
+ } else { // in Narwhal or RingoJS v0.7.0-
+ var object = {};
+ var hasOwnProperty = object.hasOwnProperty;
+ for (var key in utf8) {
+ hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
+ }
+ }
+ } else { // in Rhino or a web browser
+ root.utf8 = utf8;
+ }
+
+}(this));
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],32:[function(_dereq_,module,exports){
+(function (global){
+/**
+ * JSON parse.
+ *
+ * @see Based on jQuery#parseJSON (MIT) and JSON2
+ * @api private
+ */
+
+var rvalidchars = /^[\],:{}\s]*$/;
+var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
+var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
+var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
+var rtrimLeft = /^\s+/;
+var rtrimRight = /\s+$/;
+
+module.exports = function parsejson(data) {
+ if ('string' != typeof data || !data) {
+ return null;
+ }
+
+ data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
+
+ // Attempt to parse using the native JSON parser first
+ if (global.JSON && JSON.parse) {
+ return JSON.parse(data);
+ }
+
+ if (rvalidchars.test(data.replace(rvalidescape, '@')
+ .replace(rvalidtokens, ']')
+ .replace(rvalidbraces, ''))) {
+ return (new Function('return ' + data))();
+ }
+};
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],33:[function(_dereq_,module,exports){
+/**
+ * Compiles a querystring
+ * Returns string representation of the object
+ *
+ * @param {Object}
+ * @api private
+ */
+
+exports.encode = function (obj) {
+ var str = '';
+
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (str.length) str += '&';
+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
+ }
+ }
+
+ return str;
+};
+
+/**
+ * Parses a simple querystring into an object
+ *
+ * @param {String} qs
+ * @api private
+ */
+
+exports.decode = function(qs){
+ var qry = {};
+ var pairs = qs.split('&');
+ for (var i = 0, l = pairs.length; i < l; i++) {
+ var pair = pairs[i].split('=');
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
+ }
+ return qry;
+};
+
+},{}],34:[function(_dereq_,module,exports){
+/**
+ * Parses an URI
+ *
+ * @author Steven Levithan (MIT license)
+ * @api private
+ */
+
+var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
+
+var parts = [
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
+];
+
+module.exports = function parseuri(str) {
+ var src = str,
+ b = str.indexOf('['),
+ e = str.indexOf(']');
+
+ if (b != -1 && e != -1) {
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
+ }
+
+ var m = re.exec(str || ''),
+ uri = {},
+ i = 14;
+
+ while (i--) {
+ uri[parts[i]] = m[i] || '';
+ }
+
+ if (b != -1 && e != -1) {
+ uri.source = src;
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
+ uri.ipv6uri = true;
+ }
+
+ return uri;
+};
+
+},{}],35:[function(_dereq_,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var global = (function() { return this; })();
+
+/**
+ * WebSocket constructor.
+ */
+
+var WebSocket = global.WebSocket || global.MozWebSocket;
+
+/**
+ * Module exports.
+ */
+
+module.exports = WebSocket ? ws : null;
+
+/**
+ * WebSocket constructor.
+ *
+ * The third `opts` options object gets ignored in web browsers, since it's
+ * non-standard, and throws a TypeError if passed to the constructor.
+ * See: https://github.com/einaros/ws/issues/227
+ *
+ * @param {String} uri
+ * @param {Array} protocols (optional)
+ * @param {Object) opts (optional)
+ * @api public
+ */
+
+function ws(uri, protocols, opts) {
+ var instance;
+ if (protocols) {
+ instance = new WebSocket(uri, protocols);
+ } else {
+ instance = new WebSocket(uri);
+ }
+ return instance;
+}
+
+if (WebSocket) ws.prototype = WebSocket.prototype;
+
+},{}],36:[function(_dereq_,module,exports){
+(function (global){
+
+/*
+ * Module requirements.
+ */
+
+var isArray = _dereq_('isarray');
+
+/**
+ * Module exports.
+ */
+
+module.exports = hasBinary;
+
+/**
+ * Checks for binary data.
+ *
+ * Right now only Buffer and ArrayBuffer are supported..
+ *
+ * @param {Object} anything
+ * @api public
+ */
+
+function hasBinary(data) {
+
+ function _hasBinary(obj) {
+ if (!obj) return false;
+
+ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
+ (global.Blob && obj instanceof Blob) ||
+ (global.File && obj instanceof File)
+ ) {
+ return true;
+ }
+
+ if (isArray(obj)) {
+ for (var i = 0; i < obj.length; i++) {
+ if (_hasBinary(obj[i])) {
+ return true;
+ }
+ }
+ } else if (obj && 'object' == typeof obj) {
+ if (obj.toJSON) {
+ obj = obj.toJSON();
+ }
+
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ return _hasBinary(data);
+}
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"isarray":37}],37:[function(_dereq_,module,exports){
+module.exports = Array.isArray || function (arr) {
+ return Object.prototype.toString.call(arr) == '[object Array]';
+};
+
+},{}],38:[function(_dereq_,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var global = _dereq_('global');
+
+/**
+ * Module exports.
+ *
+ * Logic borrowed from Modernizr:
+ *
+ * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
+ */
+
+try {
+ module.exports = 'XMLHttpRequest' in global &&
+ 'withCredentials' in new global.XMLHttpRequest();
+} catch (err) {
+ // if XMLHttp support is disabled in IE then it will throw
+ // when trying to create
+ module.exports = false;
+}
+
+},{"global":39}],39:[function(_dereq_,module,exports){
+
+/**
+ * Returns `this`. Execute this without a "context" (i.e. without it being
+ * attached to an object of the left-hand side), and `this` points to the
+ * "global" scope of the current JS execution.
+ */
+
+module.exports = (function () { return this; })();
+
+},{}],40:[function(_dereq_,module,exports){
+
+var indexOf = [].indexOf;
+
+module.exports = function(arr, obj){
+ if (indexOf) return arr.indexOf(obj);
+ for (var i = 0; i < arr.length; ++i) {
+ if (arr[i] === obj) return i;
+ }
+ return -1;
+};
+},{}],41:[function(_dereq_,module,exports){
+
+/**
+ * HOP ref.
+ */
+
+var has = Object.prototype.hasOwnProperty;
+
+/**
+ * Return own keys in `obj`.
+ *
+ * @param {Object} obj
+ * @return {Array}
+ * @api public
+ */
+
+exports.keys = Object.keys || function(obj){
+ var keys = [];
+ for (var key in obj) {
+ if (has.call(obj, key)) {
+ keys.push(key);
+ }
+ }
+ return keys;
+};
+
+/**
+ * Return own values in `obj`.
+ *
+ * @param {Object} obj
+ * @return {Array}
+ * @api public
+ */
+
+exports.values = function(obj){
+ var vals = [];
+ for (var key in obj) {
+ if (has.call(obj, key)) {
+ vals.push(obj[key]);
+ }
+ }
+ return vals;
+};
+
+/**
+ * Merge `b` into `a`.
+ *
+ * @param {Object} a
+ * @param {Object} b
+ * @return {Object} a
+ * @api public
+ */
+
+exports.merge = function(a, b){
+ for (var key in b) {
+ if (has.call(b, key)) {
+ a[key] = b[key];
+ }
+ }
+ return a;
+};
+
+/**
+ * Return length of `obj`.
+ *
+ * @param {Object} obj
+ * @return {Number}
+ * @api public
+ */
+
+exports.length = function(obj){
+ return exports.keys(obj).length;
+};
+
+/**
+ * Check if `obj` is empty.
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api public
+ */
+
+exports.isEmpty = function(obj){
+ return 0 == exports.length(obj);
+};
+},{}],42:[function(_dereq_,module,exports){
+/**
+ * Parses an URI
+ *
+ * @author Steven Levithan (MIT license)
+ * @api private
+ */
+
+var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
+
+var parts = [
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
+ , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
+];
+
+module.exports = function parseuri(str) {
+ var m = re.exec(str || '')
+ , uri = {}
+ , i = 14;
+
+ while (i--) {
+ uri[parts[i]] = m[i] || '';
+ }
+
+ return uri;
+};
+
+},{}],43:[function(_dereq_,module,exports){
+(function (global){
+/*global Blob,File*/
+
+/**
+ * Module requirements
+ */
+
+var isArray = _dereq_('isarray');
+var isBuf = _dereq_('./is-buffer');
+
+/**
+ * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
+ * Anything with blobs or files should be fed through removeBlobs before coming
+ * here.
+ *
+ * @param {Object} packet - socket.io event packet
+ * @return {Object} with deconstructed packet and list of buffers
+ * @api public
+ */
+
+exports.deconstructPacket = function(packet){
+ var buffers = [];
+ var packetData = packet.data;
+
+ function _deconstructPacket(data) {
+ if (!data) return data;
+
+ if (isBuf(data)) {
+ var placeholder = { _placeholder: true, num: buffers.length };
+ buffers.push(data);
+ return placeholder;
+ } else if (isArray(data)) {
+ var newData = new Array(data.length);
+ for (var i = 0; i < data.length; i++) {
+ newData[i] = _deconstructPacket(data[i]);
+ }
+ return newData;
+ } else if ('object' == typeof data && !(data instanceof Date)) {
+ var newData = {};
+ for (var key in data) {
+ newData[key] = _deconstructPacket(data[key]);
+ }
+ return newData;
+ }
+ return data;
+ }
+
+ var pack = packet;
+ pack.data = _deconstructPacket(packetData);
+ pack.attachments = buffers.length; // number of binary 'attachments'
+ return {packet: pack, buffers: buffers};
+};
+
+/**
+ * Reconstructs a binary packet from its placeholder packet and buffers
+ *
+ * @param {Object} packet - event packet with placeholders
+ * @param {Array} buffers - binary buffers to put in placeholder positions
+ * @return {Object} reconstructed packet
+ * @api public
+ */
+
+exports.reconstructPacket = function(packet, buffers) {
+ var curPlaceHolder = 0;
+
+ function _reconstructPacket(data) {
+ if (data && data._placeholder) {
+ var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
+ return buf;
+ } else if (isArray(data)) {
+ for (var i = 0; i < data.length; i++) {
+ data[i] = _reconstructPacket(data[i]);
+ }
+ return data;
+ } else if (data && 'object' == typeof data) {
+ for (var key in data) {
+ data[key] = _reconstructPacket(data[key]);
+ }
+ return data;
+ }
+ return data;
+ }
+
+ packet.data = _reconstructPacket(packet.data);
+ packet.attachments = undefined; // no longer useful
+ return packet;
+};
+
+/**
+ * Asynchronously removes Blobs or Files from data via
+ * FileReader's readAsArrayBuffer method. Used before encoding
+ * data as msgpack. Calls callback with the blobless data.
+ *
+ * @param {Object} data
+ * @param {Function} callback
+ * @api private
+ */
+
+exports.removeBlobs = function(data, callback) {
+ function _removeBlobs(obj, curKey, containingObject) {
+ if (!obj) return obj;
+
+ // convert any blob
+ if ((global.Blob && obj instanceof Blob) ||
+ (global.File && obj instanceof File)) {
+ pendingBlobs++;
+
+ // async filereader
+ var fileReader = new FileReader();
+ fileReader.onload = function() { // this.result == arraybuffer
+ if (containingObject) {
+ containingObject[curKey] = this.result;
+ }
+ else {
+ bloblessData = this.result;
+ }
+
+ // if nothing pending its callback time
+ if(! --pendingBlobs) {
+ callback(bloblessData);
+ }
+ };
+
+ fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
+ } else if (isArray(obj)) { // handle array
+ for (var i = 0; i < obj.length; i++) {
+ _removeBlobs(obj[i], i, obj);
+ }
+ } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
+ for (var key in obj) {
+ _removeBlobs(obj[key], key, obj);
+ }
+ }
+ }
+
+ var pendingBlobs = 0;
+ var bloblessData = data;
+ _removeBlobs(bloblessData);
+ if (!pendingBlobs) {
+ callback(bloblessData);
+ }
+};
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./is-buffer":45,"isarray":46}],44:[function(_dereq_,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var debug = _dereq_('debug')('socket.io-parser');
+var json = _dereq_('json3');
+var isArray = _dereq_('isarray');
+var Emitter = _dereq_('component-emitter');
+var binary = _dereq_('./binary');
+var isBuf = _dereq_('./is-buffer');
+
+/**
+ * Protocol version.
+ *
+ * @api public
+ */
+
+exports.protocol = 4;
+
+/**
+ * Packet types.
+ *
+ * @api public
+ */
+
+exports.types = [
+ 'CONNECT',
+ 'DISCONNECT',
+ 'EVENT',
+ 'BINARY_EVENT',
+ 'ACK',
+ 'BINARY_ACK',
+ 'ERROR'
+];
+
+/**
+ * Packet type `connect`.
+ *
+ * @api public
+ */
+
+exports.CONNECT = 0;
+
+/**
+ * Packet type `disconnect`.
+ *
+ * @api public
+ */
+
+exports.DISCONNECT = 1;
+
+/**
+ * Packet type `event`.
+ *
+ * @api public
+ */
+
+exports.EVENT = 2;
+
+/**
+ * Packet type `ack`.
+ *
+ * @api public
+ */
+
+exports.ACK = 3;
+
+/**
+ * Packet type `error`.
+ *
+ * @api public
+ */
+
+exports.ERROR = 4;
+
+/**
+ * Packet type 'binary event'
+ *
+ * @api public
+ */
+
+exports.BINARY_EVENT = 5;
+
+/**
+ * Packet type `binary ack`. For acks with binary arguments.
+ *
+ * @api public
+ */
+
+exports.BINARY_ACK = 6;
+
+/**
+ * Encoder constructor.
+ *
+ * @api public
+ */
+
+exports.Encoder = Encoder;
+
+/**
+ * Decoder constructor.
+ *
+ * @api public
+ */
+
+exports.Decoder = Decoder;
+
+/**
+ * A socket.io Encoder instance
+ *
+ * @api public
+ */
+
+function Encoder() {}
+
+/**
+ * Encode a packet as a single string if non-binary, or as a
+ * buffer sequence, depending on packet type.
+ *
+ * @param {Object} obj - packet object
+ * @param {Function} callback - function to handle encodings (likely engine.write)
+ * @return Calls callback with Array of encodings
+ * @api public
+ */
+
+Encoder.prototype.encode = function(obj, callback){
+ debug('encoding packet %j', obj);
+
+ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
+ encodeAsBinary(obj, callback);
+ }
+ else {
+ var encoding = encodeAsString(obj);
+ callback([encoding]);
+ }
+};
+
+/**
+ * Encode packet as string.
+ *
+ * @param {Object} packet
+ * @return {String} encoded
+ * @api private
+ */
+
+function encodeAsString(obj) {
+ var str = '';
+ var nsp = false;
+
+ // first is type
+ str += obj.type;
+
+ // attachments if we have them
+ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
+ str += obj.attachments;
+ str += '-';
+ }
+
+ // if we have a namespace other than `/`
+ // we append it followed by a comma `,`
+ if (obj.nsp && '/' != obj.nsp) {
+ nsp = true;
+ str += obj.nsp;
+ }
+
+ // immediately followed by the id
+ if (null != obj.id) {
+ if (nsp) {
+ str += ',';
+ nsp = false;
+ }
+ str += obj.id;
+ }
+
+ // json data
+ if (null != obj.data) {
+ if (nsp) str += ',';
+ str += json.stringify(obj.data);
+ }
+
+ debug('encoded %j as %s', obj, str);
+ return str;
+}
+
+/**
+ * Encode packet as 'buffer sequence' by removing blobs, and
+ * deconstructing packet into object with placeholders and
+ * a list of buffers.
+ *
+ * @param {Object} packet
+ * @return {Buffer} encoded
+ * @api private
+ */
+
+function encodeAsBinary(obj, callback) {
+
+ function writeEncoding(bloblessData) {
+ var deconstruction = binary.deconstructPacket(bloblessData);
+ var pack = encodeAsString(deconstruction.packet);
+ var buffers = deconstruction.buffers;
+
+ buffers.unshift(pack); // add packet info to beginning of data list
+ callback(buffers); // write all the buffers
+ }
+
+ binary.removeBlobs(obj, writeEncoding);
+}
+
+/**
+ * A socket.io Decoder instance
+ *
+ * @return {Object} decoder
+ * @api public
+ */
+
+function Decoder() {
+ this.reconstructor = null;
+}
+
+/**
+ * Mix in `Emitter` with Decoder.
+ */
+
+Emitter(Decoder.prototype);
+
+/**
+ * Decodes an ecoded packet string into packet JSON.
+ *
+ * @param {String} obj - encoded packet
+ * @return {Object} packet
+ * @api public
+ */
+
+Decoder.prototype.add = function(obj) {
+ var packet;
+ if ('string' == typeof obj) {
+ packet = decodeString(obj);
+ if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
+ this.reconstructor = new BinaryReconstructor(packet);
+
+ // no attachments, labeled binary but no binary data to follow
+ if (this.reconstructor.reconPack.attachments === 0) {
+ this.emit('decoded', packet);
+ }
+ } else { // non-binary full packet
+ this.emit('decoded', packet);
+ }
+ }
+ else if (isBuf(obj) || obj.base64) { // raw binary data
+ if (!this.reconstructor) {
+ throw new Error('got binary data when not reconstructing a packet');
+ } else {
+ packet = this.reconstructor.takeBinaryData(obj);
+ if (packet) { // received final buffer
+ this.reconstructor = null;
+ this.emit('decoded', packet);
+ }
+ }
+ }
+ else {
+ throw new Error('Unknown type: ' + obj);
+ }
+};
+
+/**
+ * Decode a packet String (JSON data)
+ *
+ * @param {String} str
+ * @return {Object} packet
+ * @api private
+ */
+
+function decodeString(str) {
+ var p = {};
+ var i = 0;
+
+ // look up type
+ p.type = Number(str.charAt(0));
+ if (null == exports.types[p.type]) return error();
+
+ // look up attachments if type binary
+ if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
+ var buf = '';
+ while (str.charAt(++i) != '-') {
+ buf += str.charAt(i);
+ if (i == str.length) break;
+ }
+ if (buf != Number(buf) || str.charAt(i) != '-') {
+ throw new Error('Illegal attachments');
+ }
+ p.attachments = Number(buf);
+ }
+
+ // look up namespace (if any)
+ if ('/' == str.charAt(i + 1)) {
+ p.nsp = '';
+ while (++i) {
+ var c = str.charAt(i);
+ if (',' == c) break;
+ p.nsp += c;
+ if (i == str.length) break;
+ }
+ } else {
+ p.nsp = '/';
+ }
+
+ // look up id
+ var next = str.charAt(i + 1);
+ if ('' !== next && Number(next) == next) {
+ p.id = '';
+ while (++i) {
+ var c = str.charAt(i);
+ if (null == c || Number(c) != c) {
+ --i;
+ break;
+ }
+ p.id += str.charAt(i);
+ if (i == str.length) break;
+ }
+ p.id = Number(p.id);
+ }
+
+ // look up json data
+ if (str.charAt(++i)) {
+ try {
+ p.data = json.parse(str.substr(i));
+ } catch(e){
+ return error();
+ }
+ }
+
+ debug('decoded %s as %j', str, p);
+ return p;
+}
+
+/**
+ * Deallocates a parser's resources
+ *
+ * @api public
+ */
+
+Decoder.prototype.destroy = function() {
+ if (this.reconstructor) {
+ this.reconstructor.finishedReconstruction();
+ }
+};
+
+/**
+ * A manager of a binary event's 'buffer sequence'. Should
+ * be constructed whenever a packet of type BINARY_EVENT is
+ * decoded.
+ *
+ * @param {Object} packet
+ * @return {BinaryReconstructor} initialized reconstructor
+ * @api private
+ */
+
+function BinaryReconstructor(packet) {
+ this.reconPack = packet;
+ this.buffers = [];
+}
+
+/**
+ * Method to be called when binary data received from connection
+ * after a BINARY_EVENT packet.
+ *
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
+ * @return {null | Object} returns null if more binary data is expected or
+ * a reconstructed packet object if all buffers have been received.
+ * @api private
+ */
+
+BinaryReconstructor.prototype.takeBinaryData = function(binData) {
+ this.buffers.push(binData);
+ if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
+ var packet = binary.reconstructPacket(this.reconPack, this.buffers);
+ this.finishedReconstruction();
+ return packet;
+ }
+ return null;
+};
+
+/**
+ * Cleans up binary packet reconstruction variables.
+ *
+ * @api private
+ */
+
+BinaryReconstructor.prototype.finishedReconstruction = function() {
+ this.reconPack = null;
+ this.buffers = [];
+};
+
+function error(data){
+ return {
+ type: exports.ERROR,
+ data: 'parser error'
+ };
+}
+
+},{"./binary":43,"./is-buffer":45,"component-emitter":9,"debug":10,"isarray":46,"json3":47}],45:[function(_dereq_,module,exports){
+(function (global){
+
+module.exports = isBuf;
+
+/**
+ * Returns true if obj is a buffer or an arraybuffer.
+ *
+ * @api private
+ */
+
+function isBuf(obj) {
+ return (global.Buffer && global.Buffer.isBuffer(obj)) ||
+ (global.ArrayBuffer && obj instanceof ArrayBuffer);
+}
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],46:[function(_dereq_,module,exports){
+module.exports=_dereq_(37)
+},{}],47:[function(_dereq_,module,exports){
+/*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
+;(function (window) {
+ // Convenience aliases.
+ var getClass = {}.toString, isProperty, forEach, undef;
+
+ // Detect the `define` function exposed by asynchronous module loaders. The
+ // strict `define` check is necessary for compatibility with `r.js`.
+ var isLoader = typeof define === "function" && define.amd;
+
+ // Detect native implementations.
+ var nativeJSON = typeof JSON == "object" && JSON;
+
+ // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
+ // available.
+ var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
+
+ if (JSON3 && nativeJSON) {
+ // Explicitly delegate to the native `stringify` and `parse`
+ // implementations in CommonJS environments.
+ JSON3.stringify = nativeJSON.stringify;
+ JSON3.parse = nativeJSON.parse;
+ } else {
+ // Export for web browsers, JavaScript engines, and asynchronous module
+ // loaders, using the global `JSON` object if available.
+ JSON3 = window.JSON = nativeJSON || {};
+ }
+
+ // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
+ var isExtended = new Date(-3509827334573292);
+ try {
+ // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
+ // results for certain dates in Opera >= 10.53.
+ isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
+ // Safari < 2.0.2 stores the internal millisecond time value correctly,
+ // but clips the values returned by the date methods to the range of
+ // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
+ isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
+ } catch (exception) {}
+
+ // Internal: Determines whether the native `JSON.stringify` and `parse`
+ // implementations are spec-compliant. Based on work by Ken Snyder.
+ function has(name) {
+ if (has[name] !== undef) {
+ // Return cached feature test result.
+ return has[name];
+ }
+
+ var isSupported;
+ if (name == "bug-string-char-index") {
+ // IE <= 7 doesn't support accessing string characters using square
+ // bracket notation. IE 8 only supports this for primitives.
+ isSupported = "a"[0] != "a";
+ } else if (name == "json") {
+ // Indicates whether both `JSON.stringify` and `JSON.parse` are
+ // supported.
+ isSupported = has("json-stringify") && has("json-parse");
+ } else {
+ var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
+ // Test `JSON.stringify`.
+ if (name == "json-stringify") {
+ var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
+ if (stringifySupported) {
+ // A test function object with a custom `toJSON` method.
+ (value = function () {
+ return 1;
+ }).toJSON = value;
+ try {
+ stringifySupported =
+ // Firefox 3.1b1 and b2 serialize string, number, and boolean
+ // primitives as object literals.
+ stringify(0) === "0" &&
+ // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
+ // literals.
+ stringify(new Number()) === "0" &&
+ stringify(new String()) == '""' &&
+ // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
+ // does not define a canonical JSON representation (this applies to
+ // objects with `toJSON` properties as well, *unless* they are nested
+ // within an object or array).
+ stringify(getClass) === undef &&
+ // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
+ // FF 3.1b3 pass this test.
+ stringify(undef) === undef &&
+ // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
+ // respectively, if the value is omitted entirely.
+ stringify() === undef &&
+ // FF 3.1b1, 2 throw an error if the given value is not a number,
+ // string, array, object, Boolean, or `null` literal. This applies to
+ // objects with custom `toJSON` methods as well, unless they are nested
+ // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
+ // methods entirely.
+ stringify(value) === "1" &&
+ stringify([value]) == "[1]" &&
+ // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
+ // `"[null]"`.
+ stringify([undef]) == "[null]" &&
+ // YUI 3.0.0b1 fails to serialize `null` literals.
+ stringify(null) == "null" &&
+ // FF 3.1b1, 2 halts serialization if an array contains a function:
+ // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
+ // elides non-JSON values from objects and arrays, unless they
+ // define custom `toJSON` methods.
+ stringify([undef, getClass, null]) == "[null,null,null]" &&
+ // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
+ // where character escape codes are expected (e.g., `\b` => `\u0008`).
+ stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
+ // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
+ stringify(null, value) === "1" &&
+ stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
+ // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
+ // serialize extended years.
+ stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
+ // The milliseconds are optional in ES 5, but required in 5.1.
+ stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
+ // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
+ // four-digit years instead of six-digit years. Credits: @Yaffle.
+ stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
+ // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
+ // values less than 1000. Credits: @Yaffle.
+ stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
+ } catch (exception) {
+ stringifySupported = false;
+ }
+ }
+ isSupported = stringifySupported;
+ }
+ // Test `JSON.parse`.
+ if (name == "json-parse") {
+ var parse = JSON3.parse;
+ if (typeof parse == "function") {
+ try {
+ // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
+ // Conforming implementations should also coerce the initial argument to
+ // a string prior to parsing.
+ if (parse("0") === 0 && !parse(false)) {
+ // Simple parsing test.
+ value = parse(serialized);
+ var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
+ if (parseSupported) {
+ try {
+ // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
+ parseSupported = !parse('"\t"');
+ } catch (exception) {}
+ if (parseSupported) {
+ try {
+ // FF 4.0 and 4.0.1 allow leading `+` signs and leading
+ // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
+ // certain octal literals.
+ parseSupported = parse("01") !== 1;
+ } catch (exception) {}
+ }
+ if (parseSupported) {
+ try {
+ // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
+ // points. These environments, along with FF 3.1b1 and 2,
+ // also allow trailing commas in JSON objects and arrays.
+ parseSupported = parse("1.") !== 1;
+ } catch (exception) {}
+ }
+ }
+ }
+ } catch (exception) {
+ parseSupported = false;
+ }
+ }
+ isSupported = parseSupported;
+ }
+ }
+ return has[name] = !!isSupported;
+ }
+
+ if (!has("json")) {
+ // Common `[[Class]]` name aliases.
+ var functionClass = "[object Function]";
+ var dateClass = "[object Date]";
+ var numberClass = "[object Number]";
+ var stringClass = "[object String]";
+ var arrayClass = "[object Array]";
+ var booleanClass = "[object Boolean]";
+
+ // Detect incomplete support for accessing string characters by index.
+ var charIndexBuggy = has("bug-string-char-index");
+
+ // Define additional utility methods if the `Date` methods are buggy.
+ if (!isExtended) {
+ var floor = Math.floor;
+ // A mapping between the months of the year and the number of days between
+ // January 1st and the first of the respective month.
+ var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
+ // Internal: Calculates the number of days between the Unix epoch and the
+ // first day of the given month.
+ var getDay = function (year, month) {
+ return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
+ };
+ }
+
+ // Internal: Determines if a property is a direct property of the given
+ // object. Delegates to the native `Object#hasOwnProperty` method.
+ if (!(isProperty = {}.hasOwnProperty)) {
+ isProperty = function (property) {
+ var members = {}, constructor;
+ if ((members.__proto__ = null, members.__proto__ = {
+ // The *proto* property cannot be set multiple times in recent
+ // versions of Firefox and SeaMonkey.
+ "toString": 1
+ }, members).toString != getClass) {
+ // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
+ // supports the mutable *proto* property.
+ isProperty = function (property) {
+ // Capture and break the object's prototype chain (see section 8.6.2
+ // of the ES 5.1 spec). The parenthesized expression prevents an
+ // unsafe transformation by the Closure Compiler.
+ var original = this.__proto__, result = property in (this.__proto__ = null, this);
+ // Restore the original prototype chain.
+ this.__proto__ = original;
+ return result;
+ };
+ } else {
+ // Capture a reference to the top-level `Object` constructor.
+ constructor = members.constructor;
+ // Use the `constructor` property to simulate `Object#hasOwnProperty` in
+ // other environments.
+ isProperty = function (property) {
+ var parent = (this.constructor || constructor).prototype;
+ return property in this && !(property in parent && this[property] === parent[property]);
+ };
+ }
+ members = null;
+ return isProperty.call(this, property);
+ };
+ }
+
+ // Internal: A set of primitive types used by `isHostType`.
+ var PrimitiveTypes = {
+ 'boolean': 1,
+ 'number': 1,
+ 'string': 1,
+ 'undefined': 1
+ };
+
+ // Internal: Determines if the given object `property` value is a
+ // non-primitive.
+ var isHostType = function (object, property) {
+ var type = typeof object[property];
+ return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
+ };
+
+ // Internal: Normalizes the `for...in` iteration algorithm across
+ // environments. Each enumerated key is yielded to a `callback` function.
+ forEach = function (object, callback) {
+ var size = 0, Properties, members, property;
+
+ // Tests for bugs in the current environment's `for...in` algorithm. The
+ // `valueOf` property inherits the non-enumerable flag from
+ // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
+ (Properties = function () {
+ this.valueOf = 0;
+ }).prototype.valueOf = 0;
+
+ // Iterate over a new instance of the `Properties` class.
+ members = new Properties();
+ for (property in members) {
+ // Ignore all properties inherited from `Object.prototype`.
+ if (isProperty.call(members, property)) {
+ size++;
+ }
+ }
+ Properties = members = null;
+
+ // Normalize the iteration algorithm.
+ if (!size) {
+ // A list of non-enumerable properties inherited from `Object.prototype`.
+ members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
+ // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
+ // properties.
+ forEach = function (object, callback) {
+ var isFunction = getClass.call(object) == functionClass, property, length;
+ var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
+ for (property in object) {
+ // Gecko <= 1.0 enumerates the `prototype` property of functions under
+ // certain conditions; IE does not.
+ if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
+ callback(property);
+ }
+ }
+ // Manually invoke the callback for each non-enumerable property.
+ for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
+ };
+ } else if (size == 2) {
+ // Safari <= 2.0.4 enumerates shadowed properties twice.
+ forEach = function (object, callback) {
+ // Create a set of iterated properties.
+ var members = {}, isFunction = getClass.call(object) == functionClass, property;
+ for (property in object) {
+ // Store each property name to prevent double enumeration. The
+ // `prototype` property of functions is not enumerated due to cross-
+ // environment inconsistencies.
+ if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
+ callback(property);
+ }
+ }
+ };
+ } else {
+ // No bugs detected; use the standard `for...in` algorithm.
+ forEach = function (object, callback) {
+ var isFunction = getClass.call(object) == functionClass, property, isConstructor;
+ for (property in object) {
+ if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
+ callback(property);
+ }
+ }
+ // Manually invoke the callback for the `constructor` property due to
+ // cross-environment inconsistencies.
+ if (isConstructor || isProperty.call(object, (property = "constructor"))) {
+ callback(property);
+ }
+ };
+ }
+ return forEach(object, callback);
+ };
+
+ // Public: Serializes a JavaScript `value` as a JSON string. The optional
+ // `filter` argument may specify either a function that alters how object and
+ // array members are serialized, or an array of strings and numbers that
+ // indicates which properties should be serialized. The optional `width`
+ // argument may be either a string or number that specifies the indentation
+ // level of the output.
+ if (!has("json-stringify")) {
+ // Internal: A map of control characters and their escaped equivalents.
+ var Escapes = {
+ 92: "\\\\",
+ 34: '\\"',
+ 8: "\\b",
+ 12: "\\f",
+ 10: "\\n",
+ 13: "\\r",
+ 9: "\\t"
+ };
+
+ // Internal: Converts `value` into a zero-padded string such that its
+ // length is at least equal to `width`. The `width` must be <= 6.
+ var leadingZeroes = "000000";
+ var toPaddedString = function (width, value) {
+ // The `|| 0` expression is necessary to work around a bug in
+ // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
+ return (leadingZeroes + (value || 0)).slice(-width);
+ };
+
+ // Internal: Double-quotes a string `value`, replacing all ASCII control
+ // characters (characters with code unit values between 0 and 31) with
+ // their escaped equivalents. This is an implementation of the
+ // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
+ var unicodePrefix = "\\u00";
+ var quote = function (value) {
+ var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
+ if (isLarge) {
+ symbols = value.split("");
+ }
+ for (; index < length; index++) {
+ var charCode = value.charCodeAt(index);
+ // If the character is a control character, append its Unicode or
+ // shorthand escape sequence; otherwise, append the character as-is.
+ switch (charCode) {
+ case 8: case 9: case 10: case 12: case 13: case 34: case 92:
+ result += Escapes[charCode];
+ break;
+ default:
+ if (charCode < 32) {
+ result += unicodePrefix + toPaddedString(2, charCode.toString(16));
+ break;
+ }
+ result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
+ }
+ }
+ return result + '"';
+ };
+
+ // Internal: Recursively serializes an object. Implements the
+ // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
+ var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
+ var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
+ try {
+ // Necessary for host object support.
+ value = object[property];
+ } catch (exception) {}
+ if (typeof value == "object" && value) {
+ className = getClass.call(value);
+ if (className == dateClass && !isProperty.call(value, "toJSON")) {
+ if (value > -1 / 0 && value < 1 / 0) {
+ // Dates are serialized according to the `Date#toJSON` method
+ // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
+ // for the ISO 8601 date time string format.
+ if (getDay) {
+ // Manually compute the year, month, date, hours, minutes,
+ // seconds, and milliseconds if the `getUTC*` methods are
+ // buggy. Adapted from @Yaffle's `date-shim` project.
+ date = floor(value / 864e5);
+ for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
+ for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
+ date = 1 + date - getDay(year, month);
+ // The `time` value specifies the time within the day (see ES
+ // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
+ // to compute `A modulo B`, as the `%` operator does not
+ // correspond to the `modulo` operation for negative numbers.
+ time = (value % 864e5 + 864e5) % 864e5;
+ // The hours, minutes, seconds, and milliseconds are obtained by
+ // decomposing the time within the day. See section 15.9.1.10.
+ hours = floor(time / 36e5) % 24;
+ minutes = floor(time / 6e4) % 60;
+ seconds = floor(time / 1e3) % 60;
+ milliseconds = time % 1e3;
+ } else {
+ year = value.getUTCFullYear();
+ month = value.getUTCMonth();
+ date = value.getUTCDate();
+ hours = value.getUTCHours();
+ minutes = value.getUTCMinutes();
+ seconds = value.getUTCSeconds();
+ milliseconds = value.getUTCMilliseconds();
+ }
+ // Serialize extended years correctly.
+ value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
+ "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
+ // Months, dates, hours, minutes, and seconds should have two
+ // digits; milliseconds should have three.
+ "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
+ // Milliseconds are optional in ES 5.0, but required in 5.1.
+ "." + toPaddedString(3, milliseconds) + "Z";
+ } else {
+ value = null;
+ }
+ } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
+ // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
+ // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
+ // ignores all `toJSON` methods on these objects unless they are
+ // defined directly on an instance.
+ value = value.toJSON(property);
+ }
+ }
+ if (callback) {
+ // If a replacement function was provided, call it to obtain the value
+ // for serialization.
+ value = callback.call(object, property, value);
+ }
+ if (value === null) {
+ return "null";
+ }
+ className = getClass.call(value);
+ if (className == booleanClass) {
+ // Booleans are represented literally.
+ return "" + value;
+ } else if (className == numberClass) {
+ // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
+ // `"null"`.
+ return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
+ } else if (className == stringClass) {
+ // Strings are double-quoted and escaped.
+ return quote("" + value);
+ }
+ // Recursively serialize objects and arrays.
+ if (typeof value == "object") {
+ // Check for cyclic structures. This is a linear search; performance
+ // is inversely proportional to the number of unique nested objects.
+ for (length = stack.length; length--;) {
+ if (stack[length] === value) {
+ // Cyclic structures cannot be serialized by `JSON.stringify`.
+ throw TypeError();
+ }
+ }
+ // Add the object to the stack of traversed objects.
+ stack.push(value);
+ results = [];
+ // Save the current indentation level and indent one additional level.
+ prefix = indentation;
+ indentation += whitespace;
+ if (className == arrayClass) {
+ // Recursively serialize array elements.
+ for (index = 0, length = value.length; index < length; index++) {
+ element = serialize(index, value, callback, properties, whitespace, indentation, stack);
+ results.push(element === undef ? "null" : element);
+ }
+ result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
+ } else {
+ // Recursively serialize object members. Members are selected from
+ // either a user-specified list of property names, or the object
+ // itself.
+ forEach(properties || value, function (property) {
+ var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
+ if (element !== undef) {
+ // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
+ // is not the empty string, let `member` {quote(property) + ":"}
+ // be the concatenation of `member` and the `space` character."
+ // The "`space` character" refers to the literal space
+ // character, not the `space` {width} argument provided to
+ // `JSON.stringify`.
+ results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
+ }
+ });
+ result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
+ }
+ // Remove the object from the traversed object stack.
+ stack.pop();
+ return result;
+ }
+ };
+
+ // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
+ JSON3.stringify = function (source, filter, width) {
+ var whitespace, callback, properties, className;
+ if (typeof filter == "function" || typeof filter == "object" && filter) {
+ if ((className = getClass.call(filter)) == functionClass) {
+ callback = filter;
+ } else if (className == arrayClass) {
+ // Convert the property names array into a makeshift set.
+ properties = {};
+ for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
+ }
+ }
+ if (width) {
+ if ((className = getClass.call(width)) == numberClass) {
+ // Convert the `width` to an integer and create a string containing
+ // `width` number of space characters.
+ if ((width -= width % 1) > 0) {
+ for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
+ }
+ } else if (className == stringClass) {
+ whitespace = width.length <= 10 ? width : width.slice(0, 10);
+ }
+ }
+ // Opera <= 7.54u2 discards the values associated with empty string keys
+ // (`""`) only if they are used directly within an object member list
+ // (e.g., `!("" in { "": 1})`).
+ return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
+ };
+ }
+
+ // Public: Parses a JSON source string.
+ if (!has("json-parse")) {
+ var fromCharCode = String.fromCharCode;
+
+ // Internal: A map of escaped control characters and their unescaped
+ // equivalents.
+ var Unescapes = {
+ 92: "\\",
+ 34: '"',
+ 47: "/",
+ 98: "\b",
+ 116: "\t",
+ 110: "\n",
+ 102: "\f",
+ 114: "\r"
+ };
+
+ // Internal: Stores the parser state.
+ var Index, Source;
+
+ // Internal: Resets the parser state and throws a `SyntaxError`.
+ var abort = function() {
+ Index = Source = null;
+ throw SyntaxError();
+ };
+
+ // Internal: Returns the next token, or `"$"` if the parser has reached
+ // the end of the source string. A token may be a string, number, `null`
+ // literal, or Boolean literal.
+ var lex = function () {
+ var source = Source, length = source.length, value, begin, position, isSigned, charCode;
+ while (Index < length) {
+ charCode = source.charCodeAt(Index);
+ switch (charCode) {
+ case 9: case 10: case 13: case 32:
+ // Skip whitespace tokens, including tabs, carriage returns, line
+ // feeds, and space characters.
+ Index++;
+ break;
+ case 123: case 125: case 91: case 93: case 58: case 44:
+ // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
+ // the current position.
+ value = charIndexBuggy ? source.charAt(Index) : source[Index];
+ Index++;
+ return value;
+ case 34:
+ // `"` delimits a JSON string; advance to the next character and
+ // begin parsing the string. String tokens are prefixed with the
+ // sentinel `@` character to distinguish them from punctuators and
+ // end-of-string tokens.
+ for (value = "@", Index++; Index < length;) {
+ charCode = source.charCodeAt(Index);
+ if (charCode < 32) {
+ // Unescaped ASCII control characters (those with a code unit
+ // less than the space character) are not permitted.
+ abort();
+ } else if (charCode == 92) {
+ // A reverse solidus (`\`) marks the beginning of an escaped
+ // control character (including `"`, `\`, and `/`) or Unicode
+ // escape sequence.
+ charCode = source.charCodeAt(++Index);
+ switch (charCode) {
+ case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
+ // Revive escaped control characters.
+ value += Unescapes[charCode];
+ Index++;
+ break;
+ case 117:
+ // `\u` marks the beginning of a Unicode escape sequence.
+ // Advance to the first character and validate the
+ // four-digit code point.
+ begin = ++Index;
+ for (position = Index + 4; Index < position; Index++) {
+ charCode = source.charCodeAt(Index);
+ // A valid sequence comprises four hexdigits (case-
+ // insensitive) that form a single hexadecimal value.
+ if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
+ // Invalid Unicode escape sequence.
+ abort();
+ }
+ }
+ // Revive the escaped character.
+ value += fromCharCode("0x" + source.slice(begin, Index));
+ break;
+ default:
+ // Invalid escape sequence.
+ abort();
+ }
+ } else {
+ if (charCode == 34) {
+ // An unescaped double-quote character marks the end of the
+ // string.
+ break;
+ }
+ charCode = source.charCodeAt(Index);
+ begin = Index;
+ // Optimize for the common case where a string is valid.
+ while (charCode >= 32 && charCode != 92 && charCode != 34) {
+ charCode = source.charCodeAt(++Index);
+ }
+ // Append the string as-is.
+ value += source.slice(begin, Index);
+ }
+ }
+ if (source.charCodeAt(Index) == 34) {
+ // Advance to the next character and return the revived string.
+ Index++;
+ return value;
+ }
+ // Unterminated string.
+ abort();
+ default:
+ // Parse numbers and literals.
+ begin = Index;
+ // Advance past the negative sign, if one is specified.
+ if (charCode == 45) {
+ isSigned = true;
+ charCode = source.charCodeAt(++Index);
+ }
+ // Parse an integer or floating-point value.
+ if (charCode >= 48 && charCode <= 57) {
+ // Leading zeroes are interpreted as octal literals.
+ if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
+ // Illegal octal literal.
+ abort();
+ }
+ isSigned = false;
+ // Parse the integer component.
+ for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
+ // Floats cannot contain a leading decimal point; however, this
+ // case is already accounted for by the parser.
+ if (source.charCodeAt(Index) == 46) {
+ position = ++Index;
+ // Parse the decimal component.
+ for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
+ if (position == Index) {
+ // Illegal trailing decimal.
+ abort();
+ }
+ Index = position;
+ }
+ // Parse exponents. The `e` denoting the exponent is
+ // case-insensitive.
+ charCode = source.charCodeAt(Index);
+ if (charCode == 101 || charCode == 69) {
+ charCode = source.charCodeAt(++Index);
+ // Skip past the sign following the exponent, if one is
+ // specified.
+ if (charCode == 43 || charCode == 45) {
+ Index++;
+ }
+ // Parse the exponential component.
+ for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
+ if (position == Index) {
+ // Illegal empty exponent.
+ abort();
+ }
+ Index = position;
+ }
+ // Coerce the parsed value to a JavaScript number.
+ return +source.slice(begin, Index);
+ }
+ // A negative sign may only precede numbers.
+ if (isSigned) {
+ abort();
+ }
+ // `true`, `false`, and `null` literals.
+ if (source.slice(Index, Index + 4) == "true") {
+ Index += 4;
+ return true;
+ } else if (source.slice(Index, Index + 5) == "false") {
+ Index += 5;
+ return false;
+ } else if (source.slice(Index, Index + 4) == "null") {
+ Index += 4;
+ return null;
+ }
+ // Unrecognized token.
+ abort();
+ }
+ }
+ // Return the sentinel `$` character if the parser has reached the end
+ // of the source string.
+ return "$";
+ };
+
+ // Internal: Parses a JSON `value` token.
+ var get = function (value) {
+ var results, hasMembers;
+ if (value == "$") {
+ // Unexpected end of input.
+ abort();
+ }
+ if (typeof value == "string") {
+ if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
+ // Remove the sentinel `@` character.
+ return value.slice(1);
+ }
+ // Parse object and array literals.
+ if (value == "[") {
+ // Parses a JSON array, returning a new JavaScript array.
+ results = [];
+ for (;; hasMembers || (hasMembers = true)) {
+ value = lex();
+ // A closing square bracket marks the end of the array literal.
+ if (value == "]") {
+ break;
+ }
+ // If the array literal contains elements, the current token
+ // should be a comma separating the previous element from the
+ // next.
+ if (hasMembers) {
+ if (value == ",") {
+ value = lex();
+ if (value == "]") {
+ // Unexpected trailing `,` in array literal.
+ abort();
+ }
+ } else {
+ // A `,` must separate each array element.
+ abort();
+ }
+ }
+ // Elisions and leading commas are not permitted.
+ if (value == ",") {
+ abort();
+ }
+ results.push(get(value));
+ }
+ return results;
+ } else if (value == "{") {
+ // Parses a JSON object, returning a new JavaScript object.
+ results = {};
+ for (;; hasMembers || (hasMembers = true)) {
+ value = lex();
+ // A closing curly brace marks the end of the object literal.
+ if (value == "}") {
+ break;
+ }
+ // If the object literal contains members, the current token
+ // should be a comma separator.
+ if (hasMembers) {
+ if (value == ",") {
+ value = lex();
+ if (value == "}") {
+ // Unexpected trailing `,` in object literal.
+ abort();
+ }
+ } else {
+ // A `,` must separate each object member.
+ abort();
+ }
+ }
+ // Leading commas are not permitted, object property names must be
+ // double-quoted strings, and a `:` must separate each property
+ // name and value.
+ if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
+ abort();
+ }
+ results[value.slice(1)] = get(lex());
+ }
+ return results;
+ }
+ // Unexpected token encountered.
+ abort();
+ }
+ return value;
+ };
+
+ // Internal: Updates a traversed object member.
+ var update = function(source, property, callback) {
+ var element = walk(source, property, callback);
+ if (element === undef) {
+ delete source[property];
+ } else {
+ source[property] = element;
+ }
+ };
+
+ // Internal: Recursively traverses a parsed JSON object, invoking the
+ // `callback` function for each value. This is an implementation of the
+ // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
+ var walk = function (source, property, callback) {
+ var value = source[property], length;
+ if (typeof value == "object" && value) {
+ // `forEach` can't be used to traverse an array in Opera <= 8.54
+ // because its `Object#hasOwnProperty` implementation returns `false`
+ // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
+ if (getClass.call(value) == arrayClass) {
+ for (length = value.length; length--;) {
+ update(value, length, callback);
+ }
+ } else {
+ forEach(value, function (property) {
+ update(value, property, callback);
+ });
+ }
+ }
+ return callback.call(source, property, value);
+ };
+
+ // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
+ JSON3.parse = function (source, callback) {
+ var result, value;
+ Index = 0;
+ Source = "" + source;
+ result = get(lex());
+ // If a JSON string contains multiple tokens, it is invalid.
+ if (lex() != "$") {
+ abort();
+ }
+ // Reset the parser state.
+ Index = Source = null;
+ return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
+ };
+ }
+ }
+
+ // Export for asynchronous module loaders.
+ if (isLoader) {
+ define(function () {
+ return JSON3;
+ });
+ }
+}(this));
+
+},{}],48:[function(_dereq_,module,exports){
+module.exports = toArray
+
+function toArray(list, index) {
+ var array = []
+
+ index = index || 0
+
+ for (var i = index || 0; i < list.length; i++) {
+ array[i - index] = list[i]
+ }
+
+ return array
+}
+
+},{}]},{},[1])
+(1)
+});
diff --git a/hybrid/html/javascripts/uni.webview.1.5.2.js b/hybrid/html/javascripts/uni.webview.1.5.2.js
new file mode 100644
index 0000000000000000000000000000000000000000..c84188c23dbff55ebde1dde41d3519d8394c4861
--- /dev/null
+++ b/hybrid/html/javascripts/uni.webview.1.5.2.js
@@ -0,0 +1,152 @@
+! function(e, n) {
+ "object" == typeof exports && "undefined" != typeof module ? module.exports = n() : "function" == typeof define &&
+ define.amd ? define(n) : (e = e || self).uni = n()
+}(this, function() {
+ "use strict";
+
+ function i(e, n) {
+ var i = {
+ options: {
+ timestamp: +new Date
+ },
+ name: e,
+ arg: n
+ };
+ if (window.__dcloud_weex_postMessage || window.__dcloud_weex_) {
+ if ("postMessage" === e) {
+ var t = {
+ data: [n]
+ };
+ return window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessage(t) : window.__dcloud_weex_.postMessage(
+ JSON.stringify(t))
+ }
+ var o = {
+ type: c,
+ args: {
+ data: i,
+ webviewIds: w
+ }
+ };
+ window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessageToService(o) : window.__dcloud_weex_.postMessageToService(
+ JSON.stringify(o))
+ }
+ if (!window.plus) return window.parent.postMessage({
+ type: c,
+ data: i,
+ pageId: ""
+ }, "*");
+ if (0 === w.length) {
+ var a = plus.webview.currentWebview();
+ if (!a) throw new Error("plus.webview.currentWebview() is undefined");
+ var d = a.parent(),
+ r = "";
+ r = d ? d.id : a.id, w.push(r)
+ }
+ if (plus.webview.getWebviewById(u)) plus.webview.postMessageToUniNView({
+ type: c,
+ args: {
+ data: i,
+ webviewIds: w
+ }
+ }, u);
+ else {
+ var s = JSON.stringify(i);
+ plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat(c, '",').concat(s, ",").concat(
+ JSON.stringify(w), ");"))
+ }
+ }
+ var w = [],
+ u = "__uniapp__service",
+ c = "WEB_INVOKE_APPSERVICE",
+ n = {
+ navigateTo: function(e) {
+ var n = (0 < arguments.length && void 0 !== e ? e : {}).url;
+ i("navigateTo", {
+ url: encodeURI(n)
+ })
+ },
+ navigateBack: function(e) {
+ var n = (0 < arguments.length && void 0 !== e ? e : {}).delta;
+ i("navigateBack", {
+ delta: parseInt(n) || 1
+ })
+ },
+ switchTab: function(e) {
+ var n = (0 < arguments.length && void 0 !== e ? e : {}).url;
+ i("switchTab", {
+ url: encodeURI(n)
+ })
+ },
+ reLaunch: function(e) {
+ var n = (0 < arguments.length && void 0 !== e ? e : {}).url;
+ i("reLaunch", {
+ url: encodeURI(n)
+ })
+ },
+ redirectTo: function(e) {
+ var n = (0 < arguments.length && void 0 !== e ? e : {}).url;
+ i("redirectTo", {
+ url: encodeURI(n)
+ })
+ },
+ getEnv: function(e) {
+ window.plus ? e({
+ plus: !0
+ }) : e({
+ h5: !0
+ })
+ },
+ postMessage: function(e) {
+ i("postMessage", (0 < arguments.length && void 0 !== e ? e : {}).data || {})
+ }
+ },
+ t = /uni-app/i.test(navigator.userAgent),
+ o = /complete|loaded|interactive/;
+ var a = window.my && -1 < navigator.userAgent.indexOf("AlipayClient");
+ var d = window.swan && window.swan.webView && /swan/i.test(navigator.userAgent);
+ var r = window.qq && window.qq.miniProgram && /QQ/i.test(navigator.userAgent) && /miniProgram/i.test(navigator.userAgent);
+ var s = window.tt && window.tt.miniProgram && /toutiaomicroapp/i.test(navigator.userAgent);
+ var g = window.wx && window.wx.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i.test(
+ navigator.userAgent);
+ for (var e, v = function() {
+ window.UniAppJSBridge = !0, document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady", {
+ bubbles: !0,
+ cancelable: !0
+ }))
+ }, p = [function(e) {
+ if (t) return window.__dcloud_weex_postMessage || window.__dcloud_weex_ ? document.addEventListener(
+ "DOMContentLoaded", e) : window.plus && o.test(document.readyState) ? setTimeout(e, 0) : document.addEventListener(
+ "plusready", e), n
+ }, function(e) {
+ if (g) return window.WeixinJSBridge && window.WeixinJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener(
+ "WeixinJSBridgeReady", e), window.wx.miniProgram
+ }, function(e) {
+ if (r) return window.QQJSBridge && window.QQJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener(
+ "QQJSBridgeReady", e), window.qq.miniProgram
+ }, function(e) {
+ if (a) {
+ document.addEventListener("DOMContentLoaded", e);
+ var n = window.my;
+ return {
+ navigateTo: n.navigateTo,
+ navigateBack: n.navigateBack,
+ switchTab: n.switchTab,
+ reLaunch: n.reLaunch,
+ redirectTo: n.redirectTo,
+ postMessage: n.postMessage,
+ getEnv: n.getEnv
+ }
+ }
+ }, function(e) {
+ if (d) return document.addEventListener("DOMContentLoaded", e), window.swan.webView
+ }, function(e) {
+ if (s) return document.addEventListener("DOMContentLoaded", e), window.tt.miniProgram
+ }, function(e) {
+ return document.addEventListener("DOMContentLoaded", e), n
+ }], l = 0; l < p.length && !(e = p[l](v)); l++);
+ e = e || {};
+ var f = "undefined" != typeof uni ? uni : {};
+ return f.navigateTo ? f.webView = e : Object.assign(f, e, {
+ webView: e
+ }), f
+});
diff --git a/hybrid/html/javascripts/uni.webview.1.5.4.js b/hybrid/html/javascripts/uni.webview.1.5.4.js
new file mode 100644
index 0000000000000000000000000000000000000000..328b91e0f9efeabad859618e94ba00dbd7c6a1b5
--- /dev/null
+++ b/hybrid/html/javascripts/uni.webview.1.5.4.js
@@ -0,0 +1 @@
+!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function i(e,i){return n.call(e,i)}var t=[];function r(){return window.__dcloud_weex_postMessage||window.__dcloud_weex_}var o=function(e,n){var i={options:{timestamp:+new Date},name:e,arg:n};if(r()){if("postMessage"===e){var o={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(o):window.__dcloud_weex_.postMessage(JSON.stringify(o))}var a={type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(a):window.__dcloud_weex_.postMessageToService(JSON.stringify(a))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:i,pageId:""},"*");if(0===t.length){var d=plus.webview.currentWebview();if(!d)throw new Error("plus.webview.currentWebview() is undefined");var s=d.parent(),w="";w=s?s.id:d.id,t.push(w)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}},"__uniapp__service");else{var u=JSON.stringify(i);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(u,",").concat(JSON.stringify(t),");"))}},a={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;o("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;o("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;o("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;o("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;o("redirectTo",{url:encodeURI(n)})},getEnv:function(e){r()?e({nvue:!0}):window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};o("postMessage",e.data||{})}},d=/uni-app/i.test(navigator.userAgent),s=/Html5Plus/i.test(navigator.userAgent),w=/complete|loaded|interactive/;var u=window.my&&navigator.userAgent.indexOf(["t","n","e","i","l","C","y","a","p","i","l","A"].reverse().join(""))>-1;var g=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var v=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var c=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var m=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);var f=window.ks&&window.ks.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var l=window.tt&&window.tt.miniProgram&&/Lark|Feishu/i.test(navigator.userAgent);var _=window.jd&&window.jd.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var E=window.xhs&&window.xhs.miniProgram&&/xhsminiapp/i.test(navigator.userAgent);for(var h,P=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},b=[function(e){if(d||s)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&w.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),a},function(e){if(m)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(v)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(u){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(c)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(f)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.ks.miniProgram},function(e){if(l)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(_)return window.JDJSBridgeReady&&window.JDJSBridgeReady.invoke?setTimeout(e,0):document.addEventListener("JDJSBridgeReady",e),window.jd.miniProgram},function(e){if(E)return window.xhs.miniProgram},function(e){return document.addEventListener("DOMContentLoaded",e),a}],y=0;y= 0 && Math.floor(n) === n && isFinite(val)
+ }
+
+ function isPromise (val) {
+ return (
+ isDef(val) &&
+ typeof val.then === 'function' &&
+ typeof val.catch === 'function'
+ )
+ }
+
+ /**
+ * Convert a value to a string that is actually rendered.
+ */
+ function toString (val) {
+ return val == null
+ ? ''
+ : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
+ ? JSON.stringify(val, null, 2)
+ : String(val)
+ }
+
+ /**
+ * Convert an input value to a number for persistence.
+ * If the conversion fails, return original string.
+ */
+ function toNumber (val) {
+ var n = parseFloat(val);
+ return isNaN(n) ? val : n
+ }
+
+ /**
+ * Make a map and return a function for checking if a key
+ * is in that map.
+ */
+ function makeMap (
+ str,
+ expectsLowerCase
+ ) {
+ var map = Object.create(null);
+ var list = str.split(',');
+ for (var i = 0; i < list.length; i++) {
+ map[list[i]] = true;
+ }
+ return expectsLowerCase
+ ? function (val) { return map[val.toLowerCase()]; }
+ : function (val) { return map[val]; }
+ }
+
+ /**
+ * Check if a tag is a built-in tag.
+ */
+ var isBuiltInTag = makeMap('slot,component', true);
+
+ /**
+ * Check if an attribute is a reserved attribute.
+ */
+ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
+
+ /**
+ * Remove an item from an array.
+ */
+ function remove (arr, item) {
+ if (arr.length) {
+ var index = arr.indexOf(item);
+ if (index > -1) {
+ return arr.splice(index, 1)
+ }
+ }
+ }
+
+ /**
+ * Check whether an object has the property.
+ */
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ function hasOwn (obj, key) {
+ return hasOwnProperty.call(obj, key)
+ }
+
+ /**
+ * Create a cached version of a pure function.
+ */
+ function cached (fn) {
+ var cache = Object.create(null);
+ return (function cachedFn (str) {
+ var hit = cache[str];
+ return hit || (cache[str] = fn(str))
+ })
+ }
+
+ /**
+ * Camelize a hyphen-delimited string.
+ */
+ var camelizeRE = /-(\w)/g;
+ var camelize = cached(function (str) {
+ return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
+ });
+
+ /**
+ * Capitalize a string.
+ */
+ var capitalize = cached(function (str) {
+ return str.charAt(0).toUpperCase() + str.slice(1)
+ });
+
+ /**
+ * Hyphenate a camelCase string.
+ */
+ var hyphenateRE = /\B([A-Z])/g;
+ var hyphenate = cached(function (str) {
+ return str.replace(hyphenateRE, '-$1').toLowerCase()
+ });
+
+ /**
+ * Simple bind polyfill for environments that do not support it,
+ * e.g., PhantomJS 1.x. Technically, we don't need this anymore
+ * since native bind is now performant enough in most browsers.
+ * But removing it would mean breaking code that was able to run in
+ * PhantomJS 1.x, so this must be kept for backward compatibility.
+ */
+
+ /* istanbul ignore next */
+ function polyfillBind (fn, ctx) {
+ function boundFn (a) {
+ var l = arguments.length;
+ return l
+ ? l > 1
+ ? fn.apply(ctx, arguments)
+ : fn.call(ctx, a)
+ : fn.call(ctx)
+ }
+
+ boundFn._length = fn.length;
+ return boundFn
+ }
+
+ function nativeBind (fn, ctx) {
+ return fn.bind(ctx)
+ }
+
+ var bind = Function.prototype.bind
+ ? nativeBind
+ : polyfillBind;
+
+ /**
+ * Convert an Array-like object to a real Array.
+ */
+ function toArray (list, start) {
+ start = start || 0;
+ var i = list.length - start;
+ var ret = new Array(i);
+ while (i--) {
+ ret[i] = list[i + start];
+ }
+ return ret
+ }
+
+ /**
+ * Mix properties into target object.
+ */
+ function extend (to, _from) {
+ for (var key in _from) {
+ to[key] = _from[key];
+ }
+ return to
+ }
+
+ /**
+ * Merge an Array of Objects into a single Object.
+ */
+ function toObject (arr) {
+ var res = {};
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i]) {
+ extend(res, arr[i]);
+ }
+ }
+ return res
+ }
+
+ /* eslint-disable no-unused-vars */
+
+ /**
+ * Perform no operation.
+ * Stubbing args to make Flow happy without leaving useless transpiled code
+ * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
+ */
+ function noop (a, b, c) {}
+
+ /**
+ * Always return false.
+ */
+ var no = function (a, b, c) { return false; };
+
+ /* eslint-enable no-unused-vars */
+
+ /**
+ * Return the same value.
+ */
+ var identity = function (_) { return _; };
+
+ /**
+ * Generate a string containing static keys from compiler modules.
+ */
+ function genStaticKeys (modules) {
+ return modules.reduce(function (keys, m) {
+ return keys.concat(m.staticKeys || [])
+ }, []).join(',')
+ }
+
+ /**
+ * Check if two values are loosely equal - that is,
+ * if they are plain objects, do they have the same shape?
+ */
+ function looseEqual (a, b) {
+ if (a === b) { return true }
+ var isObjectA = isObject(a);
+ var isObjectB = isObject(b);
+ if (isObjectA && isObjectB) {
+ try {
+ var isArrayA = Array.isArray(a);
+ var isArrayB = Array.isArray(b);
+ if (isArrayA && isArrayB) {
+ return a.length === b.length && a.every(function (e, i) {
+ return looseEqual(e, b[i])
+ })
+ } else if (a instanceof Date && b instanceof Date) {
+ return a.getTime() === b.getTime()
+ } else if (!isArrayA && !isArrayB) {
+ var keysA = Object.keys(a);
+ var keysB = Object.keys(b);
+ return keysA.length === keysB.length && keysA.every(function (key) {
+ return looseEqual(a[key], b[key])
+ })
+ } else {
+ /* istanbul ignore next */
+ return false
+ }
+ } catch (e) {
+ /* istanbul ignore next */
+ return false
+ }
+ } else if (!isObjectA && !isObjectB) {
+ return String(a) === String(b)
+ } else {
+ return false
+ }
+ }
+
+ /**
+ * Return the first index at which a loosely equal value can be
+ * found in the array (if value is a plain object, the array must
+ * contain an object of the same shape), or -1 if it is not present.
+ */
+ function looseIndexOf (arr, val) {
+ for (var i = 0; i < arr.length; i++) {
+ if (looseEqual(arr[i], val)) { return i }
+ }
+ return -1
+ }
+
+ /**
+ * Ensure a function is called only once.
+ */
+ function once (fn) {
+ var called = false;
+ return function () {
+ if (!called) {
+ called = true;
+ fn.apply(this, arguments);
+ }
+ }
+ }
+
+ var SSR_ATTR = 'data-server-rendered';
+
+ var ASSET_TYPES = [
+ 'component',
+ 'directive',
+ 'filter'
+ ];
+
+ var LIFECYCLE_HOOKS = [
+ 'beforeCreate',
+ 'created',
+ 'beforeMount',
+ 'mounted',
+ 'beforeUpdate',
+ 'updated',
+ 'beforeDestroy',
+ 'destroyed',
+ 'activated',
+ 'deactivated',
+ 'errorCaptured',
+ 'serverPrefetch'
+ ];
+
+ /* */
+
+
+
+ var config = ({
+ /**
+ * Option merge strategies (used in core/util/options)
+ */
+ // $flow-disable-line
+ optionMergeStrategies: Object.create(null),
+
+ /**
+ * Whether to suppress warnings.
+ */
+ silent: false,
+
+ /**
+ * Show production mode tip message on boot?
+ */
+ productionTip: "development" !== 'production',
+
+ /**
+ * Whether to enable devtools
+ */
+ devtools: "development" !== 'production',
+
+ /**
+ * Whether to record perf
+ */
+ performance: false,
+
+ /**
+ * Error handler for watcher errors
+ */
+ errorHandler: null,
+
+ /**
+ * Warn handler for watcher warns
+ */
+ warnHandler: null,
+
+ /**
+ * Ignore certain custom elements
+ */
+ ignoredElements: [],
+
+ /**
+ * Custom user key aliases for v-on
+ */
+ // $flow-disable-line
+ keyCodes: Object.create(null),
+
+ /**
+ * Check if a tag is reserved so that it cannot be registered as a
+ * component. This is platform-dependent and may be overwritten.
+ */
+ isReservedTag: no,
+
+ /**
+ * Check if an attribute is reserved so that it cannot be used as a component
+ * prop. This is platform-dependent and may be overwritten.
+ */
+ isReservedAttr: no,
+
+ /**
+ * Check if a tag is an unknown element.
+ * Platform-dependent.
+ */
+ isUnknownElement: no,
+
+ /**
+ * Get the namespace of an element
+ */
+ getTagNamespace: noop,
+
+ /**
+ * Parse the real tag name for the specific platform.
+ */
+ parsePlatformTagName: identity,
+
+ /**
+ * Check if an attribute must be bound using property, e.g. value
+ * Platform-dependent.
+ */
+ mustUseProp: no,
+
+ /**
+ * Perform updates asynchronously. Intended to be used by Vue Test Utils
+ * This will significantly reduce performance if set to false.
+ */
+ async: true,
+
+ /**
+ * Exposed for legacy reasons
+ */
+ _lifecycleHooks: LIFECYCLE_HOOKS
+ });
+
+ /* */
+
+ /**
+ * unicode letters used for parsing html tags, component names and property paths.
+ * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname
+ * skipping \u10000-\uEFFFF due to it freezing up PhantomJS
+ */
+ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/;
+
+ /**
+ * Check if a string starts with $ or _
+ */
+ function isReserved (str) {
+ var c = (str + '').charCodeAt(0);
+ return c === 0x24 || c === 0x5F
+ }
+
+ /**
+ * Define a property.
+ */
+ function def (obj, key, val, enumerable) {
+ Object.defineProperty(obj, key, {
+ value: val,
+ enumerable: !!enumerable,
+ writable: true,
+ configurable: true
+ });
+ }
+
+ /**
+ * Parse simple path.
+ */
+ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]"));
+ function parsePath (path) {
+ if (bailRE.test(path)) {
+ return
+ }
+ var segments = path.split('.');
+ return function (obj) {
+ for (var i = 0; i < segments.length; i++) {
+ if (!obj) { return }
+ obj = obj[segments[i]];
+ }
+ return obj
+ }
+ }
+
+ /* */
+
+ // can we use __proto__?
+ var hasProto = '__proto__' in {};
+
+ // Browser environment sniffing
+ var inBrowser = typeof window !== 'undefined';
+ var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
+ var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
+ var UA = inBrowser && window.navigator.userAgent.toLowerCase();
+ var isIE = UA && /msie|trident/.test(UA);
+ var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
+ var isEdge = UA && UA.indexOf('edge/') > 0;
+ var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
+ var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
+ var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
+ var isPhantomJS = UA && /phantomjs/.test(UA);
+ var isFF = UA && UA.match(/firefox\/(\d+)/);
+
+ // Firefox has a "watch" function on Object.prototype...
+ var nativeWatch = ({}).watch;
+
+ var supportsPassive = false;
+ if (inBrowser) {
+ try {
+ var opts = {};
+ Object.defineProperty(opts, 'passive', ({
+ get: function get () {
+ /* istanbul ignore next */
+ supportsPassive = true;
+ }
+ })); // https://github.com/facebook/flow/issues/285
+ window.addEventListener('test-passive', null, opts);
+ } catch (e) {}
+ }
+
+ // this needs to be lazy-evaled because vue may be required before
+ // vue-server-renderer can set VUE_ENV
+ var _isServer;
+ var isServerRendering = function () {
+ if (_isServer === undefined) {
+ /* istanbul ignore if */
+ if (!inBrowser && !inWeex && typeof global !== 'undefined') {
+ // detect presence of vue-server-renderer and avoid
+ // Webpack shimming the process
+ _isServer = global['process'] && global['process'].env.VUE_ENV === 'server';
+ } else {
+ _isServer = false;
+ }
+ }
+ return _isServer
+ };
+
+ // detect devtools
+ var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
+
+ /* istanbul ignore next */
+ function isNative (Ctor) {
+ return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
+ }
+
+ var hasSymbol =
+ typeof Symbol !== 'undefined' && isNative(Symbol) &&
+ typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
+
+ var _Set;
+ /* istanbul ignore if */ // $flow-disable-line
+ if (typeof Set !== 'undefined' && isNative(Set)) {
+ // use native Set when available.
+ _Set = Set;
+ } else {
+ // a non-standard Set polyfill that only works with primitive keys.
+ _Set = /*@__PURE__*/(function () {
+ function Set () {
+ this.set = Object.create(null);
+ }
+ Set.prototype.has = function has (key) {
+ return this.set[key] === true
+ };
+ Set.prototype.add = function add (key) {
+ this.set[key] = true;
+ };
+ Set.prototype.clear = function clear () {
+ this.set = Object.create(null);
+ };
+
+ return Set;
+ }());
+ }
+
+ /* */
+
+ var warn = noop;
+ var tip = noop;
+ var generateComponentTrace = (noop); // work around flow check
+ var formatComponentName = (noop);
+
+ {
+ var hasConsole = typeof console !== 'undefined';
+ var classifyRE = /(?:^|[-_])(\w)/g;
+ var classify = function (str) { return str
+ .replace(classifyRE, function (c) { return c.toUpperCase(); })
+ .replace(/[-_]/g, ''); };
+
+ warn = function (msg, vm) {
+ var trace = vm ? generateComponentTrace(vm) : '';
+
+ if (config.warnHandler) {
+ config.warnHandler.call(null, msg, vm, trace);
+ } else if (hasConsole && (!config.silent)) {
+ console.error(("[Vue warn]: " + msg + trace));
+ }
+ };
+
+ tip = function (msg, vm) {
+ if (hasConsole && (!config.silent)) {
+ console.warn("[Vue tip]: " + msg + (
+ vm ? generateComponentTrace(vm) : ''
+ ));
+ }
+ };
+
+ formatComponentName = function (vm, includeFile) {
+ if (vm.$root === vm) {
+ return ''
+ }
+ var options = typeof vm === 'function' && vm.cid != null
+ ? vm.options
+ : vm._isVue
+ ? vm.$options || vm.constructor.options
+ : vm;
+ var name = options.name || options._componentTag;
+ var file = options.__file;
+ if (!name && file) {
+ var match = file.match(/([^/\\]+)\.vue$/);
+ name = match && match[1];
+ }
+
+ return (
+ (name ? ("<" + (classify(name)) + ">") : "") +
+ (file && includeFile !== false ? (" at " + file) : '')
+ )
+ };
+
+ var repeat = function (str, n) {
+ var res = '';
+ while (n) {
+ if (n % 2 === 1) { res += str; }
+ if (n > 1) { str += str; }
+ n >>= 1;
+ }
+ return res
+ };
+
+ generateComponentTrace = function (vm) {
+ if (vm._isVue && vm.$parent) {
+ var tree = [];
+ var currentRecursiveSequence = 0;
+ while (vm) {
+ if (tree.length > 0) {
+ var last = tree[tree.length - 1];
+ if (last.constructor === vm.constructor) {
+ currentRecursiveSequence++;
+ vm = vm.$parent;
+ continue
+ } else if (currentRecursiveSequence > 0) {
+ tree[tree.length - 1] = [last, currentRecursiveSequence];
+ currentRecursiveSequence = 0;
+ }
+ }
+ tree.push(vm);
+ vm = vm.$parent;
+ }
+ return '\n\nfound in\n\n' + tree
+ .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)
+ ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)")
+ : formatComponentName(vm))); })
+ .join('\n')
+ } else {
+ return ("\n\n(found in " + (formatComponentName(vm)) + ")")
+ }
+ };
+ }
+
+ /* */
+
+ var uid = 0;
+
+ /**
+ * A dep is an observable that can have multiple
+ * directives subscribing to it.
+ */
+ var Dep = function Dep () {
+ this.id = uid++;
+ this.subs = [];
+ };
+
+ Dep.prototype.addSub = function addSub (sub) {
+ this.subs.push(sub);
+ };
+
+ Dep.prototype.removeSub = function removeSub (sub) {
+ remove(this.subs, sub);
+ };
+
+ Dep.prototype.depend = function depend () {
+ if (Dep.target) {
+ Dep.target.addDep(this);
+ }
+ };
+
+ Dep.prototype.notify = function notify () {
+ // stabilize the subscriber list first
+ var subs = this.subs.slice();
+ if (!config.async) {
+ // subs aren't sorted in scheduler if not running async
+ // we need to sort them now to make sure they fire in correct
+ // order
+ subs.sort(function (a, b) { return a.id - b.id; });
+ }
+ for (var i = 0, l = subs.length; i < l; i++) {
+ subs[i].update();
+ }
+ };
+
+ // The current target watcher being evaluated.
+ // This is globally unique because only one watcher
+ // can be evaluated at a time.
+ Dep.target = null;
+ var targetStack = [];
+
+ function pushTarget (target) {
+ targetStack.push(target);
+ Dep.target = target;
+ }
+
+ function popTarget () {
+ targetStack.pop();
+ Dep.target = targetStack[targetStack.length - 1];
+ }
+
+ /* */
+
+ var VNode = function VNode (
+ tag,
+ data,
+ children,
+ text,
+ elm,
+ context,
+ componentOptions,
+ asyncFactory
+ ) {
+ this.tag = tag;
+ this.data = data;
+ this.children = children;
+ this.text = text;
+ this.elm = elm;
+ this.ns = undefined;
+ this.context = context;
+ this.fnContext = undefined;
+ this.fnOptions = undefined;
+ this.fnScopeId = undefined;
+ this.key = data && data.key;
+ this.componentOptions = componentOptions;
+ this.componentInstance = undefined;
+ this.parent = undefined;
+ this.raw = false;
+ this.isStatic = false;
+ this.isRootInsert = true;
+ this.isComment = false;
+ this.isCloned = false;
+ this.isOnce = false;
+ this.asyncFactory = asyncFactory;
+ this.asyncMeta = undefined;
+ this.isAsyncPlaceholder = false;
+ };
+
+ var prototypeAccessors = { child: { configurable: true } };
+
+ // DEPRECATED: alias for componentInstance for backwards compat.
+ /* istanbul ignore next */
+ prototypeAccessors.child.get = function () {
+ return this.componentInstance
+ };
+
+ Object.defineProperties( VNode.prototype, prototypeAccessors );
+
+ var createEmptyVNode = function (text) {
+ if ( text === void 0 ) text = '';
+
+ var node = new VNode();
+ node.text = text;
+ node.isComment = true;
+ return node
+ };
+
+ function createTextVNode (val) {
+ return new VNode(undefined, undefined, undefined, String(val))
+ }
+
+ // optimized shallow clone
+ // used for static nodes and slot nodes because they may be reused across
+ // multiple renders, cloning them avoids errors when DOM manipulations rely
+ // on their elm reference.
+ function cloneVNode (vnode) {
+ var cloned = new VNode(
+ vnode.tag,
+ vnode.data,
+ // #7975
+ // clone children array to avoid mutating original in case of cloning
+ // a child.
+ vnode.children && vnode.children.slice(),
+ vnode.text,
+ vnode.elm,
+ vnode.context,
+ vnode.componentOptions,
+ vnode.asyncFactory
+ );
+ cloned.ns = vnode.ns;
+ cloned.isStatic = vnode.isStatic;
+ cloned.key = vnode.key;
+ cloned.isComment = vnode.isComment;
+ cloned.fnContext = vnode.fnContext;
+ cloned.fnOptions = vnode.fnOptions;
+ cloned.fnScopeId = vnode.fnScopeId;
+ cloned.asyncMeta = vnode.asyncMeta;
+ cloned.isCloned = true;
+ return cloned
+ }
+
+ /*
+ * not type checking this file because flow doesn't play well with
+ * dynamically accessing methods on Array prototype
+ */
+
+ var arrayProto = Array.prototype;
+ var arrayMethods = Object.create(arrayProto);
+
+ var methodsToPatch = [
+ 'push',
+ 'pop',
+ 'shift',
+ 'unshift',
+ 'splice',
+ 'sort',
+ 'reverse'
+ ];
+
+ /**
+ * Intercept mutating methods and emit events
+ */
+ methodsToPatch.forEach(function (method) {
+ // cache original method
+ var original = arrayProto[method];
+ def(arrayMethods, method, function mutator () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ var result = original.apply(this, args);
+ var ob = this.__ob__;
+ var inserted;
+ switch (method) {
+ case 'push':
+ case 'unshift':
+ inserted = args;
+ break
+ case 'splice':
+ inserted = args.slice(2);
+ break
+ }
+ if (inserted) { ob.observeArray(inserted); }
+ // notify change
+ ob.dep.notify();
+ return result
+ });
+ });
+
+ /* */
+
+ var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
+
+ /**
+ * In some cases we may want to disable observation inside a component's
+ * update computation.
+ */
+ var shouldObserve = true;
+
+ function toggleObserving (value) {
+ shouldObserve = value;
+ }
+
+ /**
+ * Observer class that is attached to each observed
+ * object. Once attached, the observer converts the target
+ * object's property keys into getter/setters that
+ * collect dependencies and dispatch updates.
+ */
+ var Observer = function Observer (value) {
+ this.value = value;
+ this.dep = new Dep();
+ this.vmCount = 0;
+ def(value, '__ob__', this);
+ if (Array.isArray(value)) {
+ if (hasProto) {
+ protoAugment(value, arrayMethods);
+ } else {
+ copyAugment(value, arrayMethods, arrayKeys);
+ }
+ this.observeArray(value);
+ } else {
+ this.walk(value);
+ }
+ };
+
+ /**
+ * Walk through all properties and convert them into
+ * getter/setters. This method should only be called when
+ * value type is Object.
+ */
+ Observer.prototype.walk = function walk (obj) {
+ var keys = Object.keys(obj);
+ for (var i = 0; i < keys.length; i++) {
+ defineReactive$$1(obj, keys[i]);
+ }
+ };
+
+ /**
+ * Observe a list of Array items.
+ */
+ Observer.prototype.observeArray = function observeArray (items) {
+ for (var i = 0, l = items.length; i < l; i++) {
+ observe(items[i]);
+ }
+ };
+
+ // helpers
+
+ /**
+ * Augment a target Object or Array by intercepting
+ * the prototype chain using __proto__
+ */
+ function protoAugment (target, src) {
+ /* eslint-disable no-proto */
+ target.__proto__ = src;
+ /* eslint-enable no-proto */
+ }
+
+ /**
+ * Augment a target Object or Array by defining
+ * hidden properties.
+ */
+ /* istanbul ignore next */
+ function copyAugment (target, src, keys) {
+ for (var i = 0, l = keys.length; i < l; i++) {
+ var key = keys[i];
+ def(target, key, src[key]);
+ }
+ }
+
+ /**
+ * Attempt to create an observer instance for a value,
+ * returns the new observer if successfully observed,
+ * or the existing observer if the value already has one.
+ */
+ function observe (value, asRootData) {
+ if (!isObject(value) || value instanceof VNode) {
+ return
+ }
+ var ob;
+ if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
+ ob = value.__ob__;
+ } else if (
+ shouldObserve &&
+ !isServerRendering() &&
+ (Array.isArray(value) || isPlainObject(value)) &&
+ Object.isExtensible(value) &&
+ !value._isVue
+ ) {
+ ob = new Observer(value);
+ }
+ if (asRootData && ob) {
+ ob.vmCount++;
+ }
+ return ob
+ }
+
+ /**
+ * Define a reactive property on an Object.
+ */
+ function defineReactive$$1 (
+ obj,
+ key,
+ val,
+ customSetter,
+ shallow
+ ) {
+ var dep = new Dep();
+
+ var property = Object.getOwnPropertyDescriptor(obj, key);
+ if (property && property.configurable === false) {
+ return
+ }
+
+ // cater for pre-defined getter/setters
+ var getter = property && property.get;
+ var setter = property && property.set;
+ if ((!getter || setter) && arguments.length === 2) {
+ val = obj[key];
+ }
+
+ var childOb = !shallow && observe(val);
+ Object.defineProperty(obj, key, {
+ enumerable: true,
+ configurable: true,
+ get: function reactiveGetter () {
+ var value = getter ? getter.call(obj) : val;
+ if (Dep.target) {
+ dep.depend();
+ if (childOb) {
+ childOb.dep.depend();
+ if (Array.isArray(value)) {
+ dependArray(value);
+ }
+ }
+ }
+ return value
+ },
+ set: function reactiveSetter (newVal) {
+ var value = getter ? getter.call(obj) : val;
+ /* eslint-disable no-self-compare */
+ if (newVal === value || (newVal !== newVal && value !== value)) {
+ return
+ }
+ /* eslint-enable no-self-compare */
+ if (customSetter) {
+ customSetter();
+ }
+ // #7981: for accessor properties without setter
+ if (getter && !setter) { return }
+ if (setter) {
+ setter.call(obj, newVal);
+ } else {
+ val = newVal;
+ }
+ childOb = !shallow && observe(newVal);
+ dep.notify();
+ }
+ });
+ }
+
+ /**
+ * Set a property on an object. Adds the new property and
+ * triggers change notification if the property doesn't
+ * already exist.
+ */
+ function set (target, key, val) {
+ if (isUndef(target) || isPrimitive(target)
+ ) {
+ warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
+ }
+ if (Array.isArray(target) && isValidArrayIndex(key)) {
+ target.length = Math.max(target.length, key);
+ target.splice(key, 1, val);
+ return val
+ }
+ if (key in target && !(key in Object.prototype)) {
+ target[key] = val;
+ return val
+ }
+ var ob = (target).__ob__;
+ if (target._isVue || (ob && ob.vmCount)) {
+ warn(
+ 'Avoid adding reactive properties to a Vue instance or its root $data ' +
+ 'at runtime - declare it upfront in the data option.'
+ );
+ return val
+ }
+ if (!ob) {
+ target[key] = val;
+ return val
+ }
+ defineReactive$$1(ob.value, key, val);
+ ob.dep.notify();
+ return val
+ }
+
+ /**
+ * Delete a property and trigger change if necessary.
+ */
+ function del (target, key) {
+ if (isUndef(target) || isPrimitive(target)
+ ) {
+ warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target))));
+ }
+ if (Array.isArray(target) && isValidArrayIndex(key)) {
+ target.splice(key, 1);
+ return
+ }
+ var ob = (target).__ob__;
+ if (target._isVue || (ob && ob.vmCount)) {
+ warn(
+ 'Avoid deleting properties on a Vue instance or its root $data ' +
+ '- just set it to null.'
+ );
+ return
+ }
+ if (!hasOwn(target, key)) {
+ return
+ }
+ delete target[key];
+ if (!ob) {
+ return
+ }
+ ob.dep.notify();
+ }
+
+ /**
+ * Collect dependencies on array elements when the array is touched, since
+ * we cannot intercept array element access like property getters.
+ */
+ function dependArray (value) {
+ for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
+ e = value[i];
+ e && e.__ob__ && e.__ob__.dep.depend();
+ if (Array.isArray(e)) {
+ dependArray(e);
+ }
+ }
+ }
+
+ /* */
+
+ /**
+ * Option overwriting strategies are functions that handle
+ * how to merge a parent option value and a child option
+ * value into the final value.
+ */
+ var strats = config.optionMergeStrategies;
+
+ /**
+ * Options with restrictions
+ */
+ {
+ strats.el = strats.propsData = function (parent, child, vm, key) {
+ if (!vm) {
+ warn(
+ "option \"" + key + "\" can only be used during instance " +
+ 'creation with the `new` keyword.'
+ );
+ }
+ return defaultStrat(parent, child)
+ };
+ }
+
+ /**
+ * Helper that recursively merges two data objects together.
+ */
+ function mergeData (to, from) {
+ if (!from) { return to }
+ var key, toVal, fromVal;
+
+ var keys = hasSymbol
+ ? Reflect.ownKeys(from)
+ : Object.keys(from);
+
+ for (var i = 0; i < keys.length; i++) {
+ key = keys[i];
+ // in case the object is already observed...
+ if (key === '__ob__') { continue }
+ toVal = to[key];
+ fromVal = from[key];
+ if (!hasOwn(to, key)) {
+ set(to, key, fromVal);
+ } else if (
+ toVal !== fromVal &&
+ isPlainObject(toVal) &&
+ isPlainObject(fromVal)
+ ) {
+ mergeData(toVal, fromVal);
+ }
+ }
+ return to
+ }
+
+ /**
+ * Data
+ */
+ function mergeDataOrFn (
+ parentVal,
+ childVal,
+ vm
+ ) {
+ if (!vm) {
+ // in a Vue.extend merge, both should be functions
+ if (!childVal) {
+ return parentVal
+ }
+ if (!parentVal) {
+ return childVal
+ }
+ // when parentVal & childVal are both present,
+ // we need to return a function that returns the
+ // merged result of both functions... no need to
+ // check if parentVal is a function here because
+ // it has to be a function to pass previous merges.
+ return function mergedDataFn () {
+ return mergeData(
+ typeof childVal === 'function' ? childVal.call(this, this) : childVal,
+ typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
+ )
+ }
+ } else {
+ return function mergedInstanceDataFn () {
+ // instance merge
+ var instanceData = typeof childVal === 'function'
+ ? childVal.call(vm, vm)
+ : childVal;
+ var defaultData = typeof parentVal === 'function'
+ ? parentVal.call(vm, vm)
+ : parentVal;
+ if (instanceData) {
+ return mergeData(instanceData, defaultData)
+ } else {
+ return defaultData
+ }
+ }
+ }
+ }
+
+ strats.data = function (
+ parentVal,
+ childVal,
+ vm
+ ) {
+ if (!vm) {
+ if (childVal && typeof childVal !== 'function') {
+ warn(
+ 'The "data" option should be a function ' +
+ 'that returns a per-instance value in component ' +
+ 'definitions.',
+ vm
+ );
+
+ return parentVal
+ }
+ return mergeDataOrFn(parentVal, childVal)
+ }
+
+ return mergeDataOrFn(parentVal, childVal, vm)
+ };
+
+ /**
+ * Hooks and props are merged as arrays.
+ */
+ function mergeHook (
+ parentVal,
+ childVal
+ ) {
+ var res = childVal
+ ? parentVal
+ ? parentVal.concat(childVal)
+ : Array.isArray(childVal)
+ ? childVal
+ : [childVal]
+ : parentVal;
+ return res
+ ? dedupeHooks(res)
+ : res
+ }
+
+ function dedupeHooks (hooks) {
+ var res = [];
+ for (var i = 0; i < hooks.length; i++) {
+ if (res.indexOf(hooks[i]) === -1) {
+ res.push(hooks[i]);
+ }
+ }
+ return res
+ }
+
+ LIFECYCLE_HOOKS.forEach(function (hook) {
+ strats[hook] = mergeHook;
+ });
+
+ /**
+ * Assets
+ *
+ * When a vm is present (instance creation), we need to do
+ * a three-way merge between constructor options, instance
+ * options and parent options.
+ */
+ function mergeAssets (
+ parentVal,
+ childVal,
+ vm,
+ key
+ ) {
+ var res = Object.create(parentVal || null);
+ if (childVal) {
+ assertObjectType(key, childVal, vm);
+ return extend(res, childVal)
+ } else {
+ return res
+ }
+ }
+
+ ASSET_TYPES.forEach(function (type) {
+ strats[type + 's'] = mergeAssets;
+ });
+
+ /**
+ * Watchers.
+ *
+ * Watchers hashes should not overwrite one
+ * another, so we merge them as arrays.
+ */
+ strats.watch = function (
+ parentVal,
+ childVal,
+ vm,
+ key
+ ) {
+ // work around Firefox's Object.prototype.watch...
+ if (parentVal === nativeWatch) { parentVal = undefined; }
+ if (childVal === nativeWatch) { childVal = undefined; }
+ /* istanbul ignore if */
+ if (!childVal) { return Object.create(parentVal || null) }
+ {
+ assertObjectType(key, childVal, vm);
+ }
+ if (!parentVal) { return childVal }
+ var ret = {};
+ extend(ret, parentVal);
+ for (var key$1 in childVal) {
+ var parent = ret[key$1];
+ var child = childVal[key$1];
+ if (parent && !Array.isArray(parent)) {
+ parent = [parent];
+ }
+ ret[key$1] = parent
+ ? parent.concat(child)
+ : Array.isArray(child) ? child : [child];
+ }
+ return ret
+ };
+
+ /**
+ * Other object hashes.
+ */
+ strats.props =
+ strats.methods =
+ strats.inject =
+ strats.computed = function (
+ parentVal,
+ childVal,
+ vm,
+ key
+ ) {
+ if (childVal && "development" !== 'production') {
+ assertObjectType(key, childVal, vm);
+ }
+ if (!parentVal) { return childVal }
+ var ret = Object.create(null);
+ extend(ret, parentVal);
+ if (childVal) { extend(ret, childVal); }
+ return ret
+ };
+ strats.provide = mergeDataOrFn;
+
+ /**
+ * Default strategy.
+ */
+ var defaultStrat = function (parentVal, childVal) {
+ return childVal === undefined
+ ? parentVal
+ : childVal
+ };
+
+ /**
+ * Validate component names
+ */
+ function checkComponents (options) {
+ for (var key in options.components) {
+ validateComponentName(key);
+ }
+ }
+
+ function validateComponentName (name) {
+ if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) {
+ warn(
+ 'Invalid component name: "' + name + '". Component names ' +
+ 'should conform to valid custom element name in html5 specification.'
+ );
+ }
+ if (isBuiltInTag(name) || config.isReservedTag(name)) {
+ warn(
+ 'Do not use built-in or reserved HTML elements as component ' +
+ 'id: ' + name
+ );
+ }
+ }
+
+ /**
+ * Ensure all props option syntax are normalized into the
+ * Object-based format.
+ */
+ function normalizeProps (options, vm) {
+ var props = options.props;
+ if (!props) { return }
+ var res = {};
+ var i, val, name;
+ if (Array.isArray(props)) {
+ i = props.length;
+ while (i--) {
+ val = props[i];
+ if (typeof val === 'string') {
+ name = camelize(val);
+ res[name] = { type: null };
+ } else {
+ warn('props must be strings when using array syntax.');
+ }
+ }
+ } else if (isPlainObject(props)) {
+ for (var key in props) {
+ val = props[key];
+ name = camelize(key);
+ res[name] = isPlainObject(val)
+ ? val
+ : { type: val };
+ }
+ } else {
+ warn(
+ "Invalid value for option \"props\": expected an Array or an Object, " +
+ "but got " + (toRawType(props)) + ".",
+ vm
+ );
+ }
+ options.props = res;
+ }
+
+ /**
+ * Normalize all injections into Object-based format
+ */
+ function normalizeInject (options, vm) {
+ var inject = options.inject;
+ if (!inject) { return }
+ var normalized = options.inject = {};
+ if (Array.isArray(inject)) {
+ for (var i = 0; i < inject.length; i++) {
+ normalized[inject[i]] = { from: inject[i] };
+ }
+ } else if (isPlainObject(inject)) {
+ for (var key in inject) {
+ var val = inject[key];
+ normalized[key] = isPlainObject(val)
+ ? extend({ from: key }, val)
+ : { from: val };
+ }
+ } else {
+ warn(
+ "Invalid value for option \"inject\": expected an Array or an Object, " +
+ "but got " + (toRawType(inject)) + ".",
+ vm
+ );
+ }
+ }
+
+ /**
+ * Normalize raw function directives into object format.
+ */
+ function normalizeDirectives (options) {
+ var dirs = options.directives;
+ if (dirs) {
+ for (var key in dirs) {
+ var def$$1 = dirs[key];
+ if (typeof def$$1 === 'function') {
+ dirs[key] = { bind: def$$1, update: def$$1 };
+ }
+ }
+ }
+ }
+
+ function assertObjectType (name, value, vm) {
+ if (!isPlainObject(value)) {
+ warn(
+ "Invalid value for option \"" + name + "\": expected an Object, " +
+ "but got " + (toRawType(value)) + ".",
+ vm
+ );
+ }
+ }
+
+ /**
+ * Merge two option objects into a new one.
+ * Core utility used in both instantiation and inheritance.
+ */
+ function mergeOptions (
+ parent,
+ child,
+ vm
+ ) {
+ {
+ checkComponents(child);
+ }
+
+ if (typeof child === 'function') {
+ child = child.options;
+ }
+
+ normalizeProps(child, vm);
+ normalizeInject(child, vm);
+ normalizeDirectives(child);
+
+ // Apply extends and mixins on the child options,
+ // but only if it is a raw options object that isn't
+ // the result of another mergeOptions call.
+ // Only merged options has the _base property.
+ if (!child._base) {
+ if (child.extends) {
+ parent = mergeOptions(parent, child.extends, vm);
+ }
+ if (child.mixins) {
+ for (var i = 0, l = child.mixins.length; i < l; i++) {
+ parent = mergeOptions(parent, child.mixins[i], vm);
+ }
+ }
+ }
+
+ var options = {};
+ var key;
+ for (key in parent) {
+ mergeField(key);
+ }
+ for (key in child) {
+ if (!hasOwn(parent, key)) {
+ mergeField(key);
+ }
+ }
+ function mergeField (key) {
+ var strat = strats[key] || defaultStrat;
+ options[key] = strat(parent[key], child[key], vm, key);
+ }
+ return options
+ }
+
+ /**
+ * Resolve an asset.
+ * This function is used because child instances need access
+ * to assets defined in its ancestor chain.
+ */
+ function resolveAsset (
+ options,
+ type,
+ id,
+ warnMissing
+ ) {
+ /* istanbul ignore if */
+ if (typeof id !== 'string') {
+ return
+ }
+ var assets = options[type];
+ // check local registration variations first
+ if (hasOwn(assets, id)) { return assets[id] }
+ var camelizedId = camelize(id);
+ if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
+ var PascalCaseId = capitalize(camelizedId);
+ if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
+ // fallback to prototype chain
+ var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
+ if (warnMissing && !res) {
+ warn(
+ 'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
+ options
+ );
+ }
+ return res
+ }
+
+ /* */
+
+
+
+ function validateProp (
+ key,
+ propOptions,
+ propsData,
+ vm
+ ) {
+ var prop = propOptions[key];
+ var absent = !hasOwn(propsData, key);
+ var value = propsData[key];
+ // boolean casting
+ var booleanIndex = getTypeIndex(Boolean, prop.type);
+ if (booleanIndex > -1) {
+ if (absent && !hasOwn(prop, 'default')) {
+ value = false;
+ } else if (value === '' || value === hyphenate(key)) {
+ // only cast empty string / same name to boolean if
+ // boolean has higher priority
+ var stringIndex = getTypeIndex(String, prop.type);
+ if (stringIndex < 0 || booleanIndex < stringIndex) {
+ value = true;
+ }
+ }
+ }
+ // check default value
+ if (value === undefined) {
+ value = getPropDefaultValue(vm, prop, key);
+ // since the default value is a fresh copy,
+ // make sure to observe it.
+ var prevShouldObserve = shouldObserve;
+ toggleObserving(true);
+ observe(value);
+ toggleObserving(prevShouldObserve);
+ }
+ {
+ assertProp(prop, key, value, vm, absent);
+ }
+ return value
+ }
+
+ /**
+ * Get the default value of a prop.
+ */
+ function getPropDefaultValue (vm, prop, key) {
+ // no default, return undefined
+ if (!hasOwn(prop, 'default')) {
+ return undefined
+ }
+ var def = prop.default;
+ // warn against non-factory defaults for Object & Array
+ if (isObject(def)) {
+ warn(
+ 'Invalid default value for prop "' + key + '": ' +
+ 'Props with type Object/Array must use a factory function ' +
+ 'to return the default value.',
+ vm
+ );
+ }
+ // the raw prop value was also undefined from previous render,
+ // return previous default value to avoid unnecessary watcher trigger
+ if (vm && vm.$options.propsData &&
+ vm.$options.propsData[key] === undefined &&
+ vm._props[key] !== undefined
+ ) {
+ return vm._props[key]
+ }
+ // call factory function for non-Function types
+ // a value is Function if its prototype is function even across different execution context
+ return typeof def === 'function' && getType(prop.type) !== 'Function'
+ ? def.call(vm)
+ : def
+ }
+
+ /**
+ * Assert whether a prop is valid.
+ */
+ function assertProp (
+ prop,
+ name,
+ value,
+ vm,
+ absent
+ ) {
+ if (prop.required && absent) {
+ warn(
+ 'Missing required prop: "' + name + '"',
+ vm
+ );
+ return
+ }
+ if (value == null && !prop.required) {
+ return
+ }
+ var type = prop.type;
+ var valid = !type || type === true;
+ var expectedTypes = [];
+ if (type) {
+ if (!Array.isArray(type)) {
+ type = [type];
+ }
+ for (var i = 0; i < type.length && !valid; i++) {
+ var assertedType = assertType(value, type[i]);
+ expectedTypes.push(assertedType.expectedType || '');
+ valid = assertedType.valid;
+ }
+ }
+
+ if (!valid) {
+ warn(
+ getInvalidTypeMessage(name, value, expectedTypes),
+ vm
+ );
+ return
+ }
+ var validator = prop.validator;
+ if (validator) {
+ if (!validator(value)) {
+ warn(
+ 'Invalid prop: custom validator check failed for prop "' + name + '".',
+ vm
+ );
+ }
+ }
+ }
+
+ var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
+
+ function assertType (value, type) {
+ var valid;
+ var expectedType = getType(type);
+ if (simpleCheckRE.test(expectedType)) {
+ var t = typeof value;
+ valid = t === expectedType.toLowerCase();
+ // for primitive wrapper objects
+ if (!valid && t === 'object') {
+ valid = value instanceof type;
+ }
+ } else if (expectedType === 'Object') {
+ valid = isPlainObject(value);
+ } else if (expectedType === 'Array') {
+ valid = Array.isArray(value);
+ } else {
+ valid = value instanceof type;
+ }
+ return {
+ valid: valid,
+ expectedType: expectedType
+ }
+ }
+
+ /**
+ * Use function string name to check built-in types,
+ * because a simple equality check will fail when running
+ * across different vms / iframes.
+ */
+ function getType (fn) {
+ var match = fn && fn.toString().match(/^\s*function (\w+)/);
+ return match ? match[1] : ''
+ }
+
+ function isSameType (a, b) {
+ return getType(a) === getType(b)
+ }
+
+ function getTypeIndex (type, expectedTypes) {
+ if (!Array.isArray(expectedTypes)) {
+ return isSameType(expectedTypes, type) ? 0 : -1
+ }
+ for (var i = 0, len = expectedTypes.length; i < len; i++) {
+ if (isSameType(expectedTypes[i], type)) {
+ return i
+ }
+ }
+ return -1
+ }
+
+ function getInvalidTypeMessage (name, value, expectedTypes) {
+ var message = "Invalid prop: type check failed for prop \"" + name + "\"." +
+ " Expected " + (expectedTypes.map(capitalize).join(', '));
+ var expectedType = expectedTypes[0];
+ var receivedType = toRawType(value);
+ var expectedValue = styleValue(value, expectedType);
+ var receivedValue = styleValue(value, receivedType);
+ // check if we need to specify expected value
+ if (expectedTypes.length === 1 &&
+ isExplicable(expectedType) &&
+ !isBoolean(expectedType, receivedType)) {
+ message += " with value " + expectedValue;
+ }
+ message += ", got " + receivedType + " ";
+ // check if we need to specify received value
+ if (isExplicable(receivedType)) {
+ message += "with value " + receivedValue + ".";
+ }
+ return message
+ }
+
+ function styleValue (value, type) {
+ if (type === 'String') {
+ return ("\"" + value + "\"")
+ } else if (type === 'Number') {
+ return ("" + (Number(value)))
+ } else {
+ return ("" + value)
+ }
+ }
+
+ function isExplicable (value) {
+ var explicitTypes = ['string', 'number', 'boolean'];
+ return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; })
+ }
+
+ function isBoolean () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; })
+ }
+
+ /* */
+
+ function handleError (err, vm, info) {
+ // Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
+ // See: https://github.com/vuejs/vuex/issues/1505
+ pushTarget();
+ try {
+ if (vm) {
+ var cur = vm;
+ while ((cur = cur.$parent)) {
+ var hooks = cur.$options.errorCaptured;
+ if (hooks) {
+ for (var i = 0; i < hooks.length; i++) {
+ try {
+ var capture = hooks[i].call(cur, err, vm, info) === false;
+ if (capture) { return }
+ } catch (e) {
+ globalHandleError(e, cur, 'errorCaptured hook');
+ }
+ }
+ }
+ }
+ }
+ globalHandleError(err, vm, info);
+ } finally {
+ popTarget();
+ }
+ }
+
+ function invokeWithErrorHandling (
+ handler,
+ context,
+ args,
+ vm,
+ info
+ ) {
+ var res;
+ try {
+ res = args ? handler.apply(context, args) : handler.call(context);
+ if (res && !res._isVue && isPromise(res) && !res._handled) {
+ res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); });
+ // issue #9511
+ // avoid catch triggering multiple times when nested calls
+ res._handled = true;
+ }
+ } catch (e) {
+ handleError(e, vm, info);
+ }
+ return res
+ }
+
+ function globalHandleError (err, vm, info) {
+ if (config.errorHandler) {
+ try {
+ return config.errorHandler.call(null, err, vm, info)
+ } catch (e) {
+ // if the user intentionally throws the original error in the handler,
+ // do not log it twice
+ if (e !== err) {
+ logError(e, null, 'config.errorHandler');
+ }
+ }
+ }
+ logError(err, vm, info);
+ }
+
+ function logError (err, vm, info) {
+ {
+ warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
+ }
+ /* istanbul ignore else */
+ if ((inBrowser || inWeex) && typeof console !== 'undefined') {
+ console.error(err);
+ } else {
+ throw err
+ }
+ }
+
+ /* */
+
+ var isUsingMicroTask = false;
+
+ var callbacks = [];
+ var pending = false;
+
+ function flushCallbacks () {
+ pending = false;
+ var copies = callbacks.slice(0);
+ callbacks.length = 0;
+ for (var i = 0; i < copies.length; i++) {
+ copies[i]();
+ }
+ }
+
+ // Here we have async deferring wrappers using microtasks.
+ // In 2.5 we used (macro) tasks (in combination with microtasks).
+ // However, it has subtle problems when state is changed right before repaint
+ // (e.g. #6813, out-in transitions).
+ // Also, using (macro) tasks in event handler would cause some weird behaviors
+ // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
+ // So we now use microtasks everywhere, again.
+ // A major drawback of this tradeoff is that there are some scenarios
+ // where microtasks have too high a priority and fire in between supposedly
+ // sequential events (e.g. #4521, #6690, which have workarounds)
+ // or even between bubbling of the same event (#6566).
+ var timerFunc;
+
+ // The nextTick behavior leverages the microtask queue, which can be accessed
+ // via either native Promise.then or MutationObserver.
+ // MutationObserver has wider support, however it is seriously bugged in
+ // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
+ // completely stops working after triggering a few times... so, if native
+ // Promise is available, we will use it:
+ /* istanbul ignore next, $flow-disable-line */
+ if (typeof Promise !== 'undefined' && isNative(Promise)) {
+ var p = Promise.resolve();
+ timerFunc = function () {
+ p.then(flushCallbacks);
+ // In problematic UIWebViews, Promise.then doesn't completely break, but
+ // it can get stuck in a weird state where callbacks are pushed into the
+ // microtask queue but the queue isn't being flushed, until the browser
+ // needs to do some other work, e.g. handle a timer. Therefore we can
+ // "force" the microtask queue to be flushed by adding an empty timer.
+ if (isIOS) { setTimeout(noop); }
+ };
+ isUsingMicroTask = true;
+ } else if (!isIE && typeof MutationObserver !== 'undefined' && (
+ isNative(MutationObserver) ||
+ // PhantomJS and iOS 7.x
+ MutationObserver.toString() === '[object MutationObserverConstructor]'
+ )) {
+ // Use MutationObserver where native Promise is not available,
+ // e.g. PhantomJS, iOS7, Android 4.4
+ // (#6466 MutationObserver is unreliable in IE11)
+ var counter = 1;
+ var observer = new MutationObserver(flushCallbacks);
+ var textNode = document.createTextNode(String(counter));
+ observer.observe(textNode, {
+ characterData: true
+ });
+ timerFunc = function () {
+ counter = (counter + 1) % 2;
+ textNode.data = String(counter);
+ };
+ isUsingMicroTask = true;
+ } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
+ // Fallback to setImmediate.
+ // Technically it leverages the (macro) task queue,
+ // but it is still a better choice than setTimeout.
+ timerFunc = function () {
+ setImmediate(flushCallbacks);
+ };
+ } else {
+ // Fallback to setTimeout.
+ timerFunc = function () {
+ setTimeout(flushCallbacks, 0);
+ };
+ }
+
+ function nextTick (cb, ctx) {
+ var _resolve;
+ callbacks.push(function () {
+ if (cb) {
+ try {
+ cb.call(ctx);
+ } catch (e) {
+ handleError(e, ctx, 'nextTick');
+ }
+ } else if (_resolve) {
+ _resolve(ctx);
+ }
+ });
+ if (!pending) {
+ pending = true;
+ timerFunc();
+ }
+ // $flow-disable-line
+ if (!cb && typeof Promise !== 'undefined') {
+ return new Promise(function (resolve) {
+ _resolve = resolve;
+ })
+ }
+ }
+
+ /* */
+
+ var mark;
+ var measure;
+
+ {
+ var perf = inBrowser && window.performance;
+ /* istanbul ignore if */
+ if (
+ perf &&
+ perf.mark &&
+ perf.measure &&
+ perf.clearMarks &&
+ perf.clearMeasures
+ ) {
+ mark = function (tag) { return perf.mark(tag); };
+ measure = function (name, startTag, endTag) {
+ perf.measure(name, startTag, endTag);
+ perf.clearMarks(startTag);
+ perf.clearMarks(endTag);
+ // perf.clearMeasures(name)
+ };
+ }
+ }
+
+ /* not type checking this file because flow doesn't play well with Proxy */
+
+ var initProxy;
+
+ {
+ var allowedGlobals = makeMap(
+ 'Infinity,undefined,NaN,isFinite,isNaN,' +
+ 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
+ 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
+ 'require' // for Webpack/Browserify
+ );
+
+ var warnNonPresent = function (target, key) {
+ warn(
+ "Property or method \"" + key + "\" is not defined on the instance but " +
+ 'referenced during render. Make sure that this property is reactive, ' +
+ 'either in the data option, or for class-based components, by ' +
+ 'initializing the property. ' +
+ 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
+ target
+ );
+ };
+
+ var warnReservedPrefix = function (target, key) {
+ warn(
+ "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " +
+ 'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
+ 'prevent conflicts with Vue internals. ' +
+ 'See: https://vuejs.org/v2/api/#data',
+ target
+ );
+ };
+
+ var hasProxy =
+ typeof Proxy !== 'undefined' && isNative(Proxy);
+
+ if (hasProxy) {
+ var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
+ config.keyCodes = new Proxy(config.keyCodes, {
+ set: function set (target, key, value) {
+ if (isBuiltInModifier(key)) {
+ warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
+ return false
+ } else {
+ target[key] = value;
+ return true
+ }
+ }
+ });
+ }
+
+ var hasHandler = {
+ has: function has (target, key) {
+ var has = key in target;
+ var isAllowed = allowedGlobals(key) ||
+ (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));
+ if (!has && !isAllowed) {
+ if (key in target.$data) { warnReservedPrefix(target, key); }
+ else { warnNonPresent(target, key); }
+ }
+ return has || !isAllowed
+ }
+ };
+
+ var getHandler = {
+ get: function get (target, key) {
+ if (typeof key === 'string' && !(key in target)) {
+ if (key in target.$data) { warnReservedPrefix(target, key); }
+ else { warnNonPresent(target, key); }
+ }
+ return target[key]
+ }
+ };
+
+ initProxy = function initProxy (vm) {
+ if (hasProxy) {
+ // determine which proxy handler to use
+ var options = vm.$options;
+ var handlers = options.render && options.render._withStripped
+ ? getHandler
+ : hasHandler;
+ vm._renderProxy = new Proxy(vm, handlers);
+ } else {
+ vm._renderProxy = vm;
+ }
+ };
+ }
+
+ /* */
+
+ var seenObjects = new _Set();
+
+ /**
+ * Recursively traverse an object to evoke all converted
+ * getters, so that every nested property inside the object
+ * is collected as a "deep" dependency.
+ */
+ function traverse (val) {
+ _traverse(val, seenObjects);
+ seenObjects.clear();
+ }
+
+ function _traverse (val, seen) {
+ var i, keys;
+ var isA = Array.isArray(val);
+ if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
+ return
+ }
+ if (val.__ob__) {
+ var depId = val.__ob__.dep.id;
+ if (seen.has(depId)) {
+ return
+ }
+ seen.add(depId);
+ }
+ if (isA) {
+ i = val.length;
+ while (i--) { _traverse(val[i], seen); }
+ } else {
+ keys = Object.keys(val);
+ i = keys.length;
+ while (i--) { _traverse(val[keys[i]], seen); }
+ }
+ }
+
+ /* */
+
+ var normalizeEvent = cached(function (name) {
+ var passive = name.charAt(0) === '&';
+ name = passive ? name.slice(1) : name;
+ var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
+ name = once$$1 ? name.slice(1) : name;
+ var capture = name.charAt(0) === '!';
+ name = capture ? name.slice(1) : name;
+ return {
+ name: name,
+ once: once$$1,
+ capture: capture,
+ passive: passive
+ }
+ });
+
+ function createFnInvoker (fns, vm) {
+ function invoker () {
+ var arguments$1 = arguments;
+
+ var fns = invoker.fns;
+ if (Array.isArray(fns)) {
+ var cloned = fns.slice();
+ for (var i = 0; i < cloned.length; i++) {
+ invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler");
+ }
+ } else {
+ // return handler return value for single handlers
+ return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler")
+ }
+ }
+ invoker.fns = fns;
+ return invoker
+ }
+
+ function updateListeners (
+ on,
+ oldOn,
+ add,
+ remove$$1,
+ createOnceHandler,
+ vm
+ ) {
+ var name, def$$1, cur, old, event;
+ for (name in on) {
+ def$$1 = cur = on[name];
+ old = oldOn[name];
+ event = normalizeEvent(name);
+ if (isUndef(cur)) {
+ warn(
+ "Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
+ vm
+ );
+ } else if (isUndef(old)) {
+ if (isUndef(cur.fns)) {
+ cur = on[name] = createFnInvoker(cur, vm);
+ }
+ if (isTrue(event.once)) {
+ cur = on[name] = createOnceHandler(event.name, cur, event.capture);
+ }
+ add(event.name, cur, event.capture, event.passive, event.params);
+ } else if (cur !== old) {
+ old.fns = cur;
+ on[name] = old;
+ }
+ }
+ for (name in oldOn) {
+ if (isUndef(on[name])) {
+ event = normalizeEvent(name);
+ remove$$1(event.name, oldOn[name], event.capture);
+ }
+ }
+ }
+
+ /* */
+
+ function mergeVNodeHook (def, hookKey, hook) {
+ if (def instanceof VNode) {
+ def = def.data.hook || (def.data.hook = {});
+ }
+ var invoker;
+ var oldHook = def[hookKey];
+
+ function wrappedHook () {
+ hook.apply(this, arguments);
+ // important: remove merged hook to ensure it's called only once
+ // and prevent memory leak
+ remove(invoker.fns, wrappedHook);
+ }
+
+ if (isUndef(oldHook)) {
+ // no existing hook
+ invoker = createFnInvoker([wrappedHook]);
+ } else {
+ /* istanbul ignore if */
+ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {
+ // already a merged invoker
+ invoker = oldHook;
+ invoker.fns.push(wrappedHook);
+ } else {
+ // existing plain hook
+ invoker = createFnInvoker([oldHook, wrappedHook]);
+ }
+ }
+
+ invoker.merged = true;
+ def[hookKey] = invoker;
+ }
+
+ /* */
+
+ function extractPropsFromVNodeData (
+ data,
+ Ctor,
+ tag
+ ) {
+ // we are only extracting raw values here.
+ // validation and default values are handled in the child
+ // component itself.
+ var propOptions = Ctor.options.props;
+ if (isUndef(propOptions)) {
+ return
+ }
+ var res = {};
+ var attrs = data.attrs;
+ var props = data.props;
+ if (isDef(attrs) || isDef(props)) {
+ for (var key in propOptions) {
+ var altKey = hyphenate(key);
+ {
+ var keyInLowerCase = key.toLowerCase();
+ if (
+ key !== keyInLowerCase &&
+ attrs && hasOwn(attrs, keyInLowerCase)
+ ) {
+ tip(
+ "Prop \"" + keyInLowerCase + "\" is passed to component " +
+ (formatComponentName(tag || Ctor)) + ", but the declared prop name is" +
+ " \"" + key + "\". " +
+ "Note that HTML attributes are case-insensitive and camelCased " +
+ "props need to use their kebab-case equivalents when using in-DOM " +
+ "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."
+ );
+ }
+ }
+ checkProp(res, props, key, altKey, true) ||
+ checkProp(res, attrs, key, altKey, false);
+ }
+ }
+ return res
+ }
+
+ function checkProp (
+ res,
+ hash,
+ key,
+ altKey,
+ preserve
+ ) {
+ if (isDef(hash)) {
+ if (hasOwn(hash, key)) {
+ res[key] = hash[key];
+ if (!preserve) {
+ delete hash[key];
+ }
+ return true
+ } else if (hasOwn(hash, altKey)) {
+ res[key] = hash[altKey];
+ if (!preserve) {
+ delete hash[altKey];
+ }
+ return true
+ }
+ }
+ return false
+ }
+
+ /* */
+
+ // The template compiler attempts to minimize the need for normalization by
+ // statically analyzing the template at compile time.
+ //
+ // For plain HTML markup, normalization can be completely skipped because the
+ // generated render function is guaranteed to return Array. There are
+ // two cases where extra normalization is needed:
+
+ // 1. When the children contains components - because a functional component
+ // may return an Array instead of a single root. In this case, just a simple
+ // normalization is needed - if any child is an Array, we flatten the whole
+ // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
+ // because functional components already normalize their own children.
+ function simpleNormalizeChildren (children) {
+ for (var i = 0; i < children.length; i++) {
+ if (Array.isArray(children[i])) {
+ return Array.prototype.concat.apply([], children)
+ }
+ }
+ return children
+ }
+
+ // 2. When the children contains constructs that always generated nested Arrays,
+ // e.g. , , v-for, or when the children is provided by user
+ // with hand-written render functions / JSX. In such cases a full normalization
+ // is needed to cater to all possible types of children values.
+ function normalizeChildren (children) {
+ return isPrimitive(children)
+ ? [createTextVNode(children)]
+ : Array.isArray(children)
+ ? normalizeArrayChildren(children)
+ : undefined
+ }
+
+ function isTextNode (node) {
+ return isDef(node) && isDef(node.text) && isFalse(node.isComment)
+ }
+
+ function normalizeArrayChildren (children, nestedIndex) {
+ var res = [];
+ var i, c, lastIndex, last;
+ for (i = 0; i < children.length; i++) {
+ c = children[i];
+ if (isUndef(c) || typeof c === 'boolean') { continue }
+ lastIndex = res.length - 1;
+ last = res[lastIndex];
+ // nested
+ if (Array.isArray(c)) {
+ if (c.length > 0) {
+ c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i));
+ // merge adjacent text nodes
+ if (isTextNode(c[0]) && isTextNode(last)) {
+ res[lastIndex] = createTextVNode(last.text + (c[0]).text);
+ c.shift();
+ }
+ res.push.apply(res, c);
+ }
+ } else if (isPrimitive(c)) {
+ if (isTextNode(last)) {
+ // merge adjacent text nodes
+ // this is necessary for SSR hydration because text nodes are
+ // essentially merged when rendered to HTML strings
+ res[lastIndex] = createTextVNode(last.text + c);
+ } else if (c !== '') {
+ // convert primitive to vnode
+ res.push(createTextVNode(c));
+ }
+ } else {
+ if (isTextNode(c) && isTextNode(last)) {
+ // merge adjacent text nodes
+ res[lastIndex] = createTextVNode(last.text + c.text);
+ } else {
+ // default key for nested array children (likely generated by v-for)
+ if (isTrue(children._isVList) &&
+ isDef(c.tag) &&
+ isUndef(c.key) &&
+ isDef(nestedIndex)) {
+ c.key = "__vlist" + nestedIndex + "_" + i + "__";
+ }
+ res.push(c);
+ }
+ }
+ }
+ return res
+ }
+
+ /* */
+
+ function initProvide (vm) {
+ var provide = vm.$options.provide;
+ if (provide) {
+ vm._provided = typeof provide === 'function'
+ ? provide.call(vm)
+ : provide;
+ }
+ }
+
+ function initInjections (vm) {
+ var result = resolveInject(vm.$options.inject, vm);
+ if (result) {
+ toggleObserving(false);
+ Object.keys(result).forEach(function (key) {
+ /* istanbul ignore else */
+ {
+ defineReactive$$1(vm, key, result[key], function () {
+ warn(
+ "Avoid mutating an injected value directly since the changes will be " +
+ "overwritten whenever the provided component re-renders. " +
+ "injection being mutated: \"" + key + "\"",
+ vm
+ );
+ });
+ }
+ });
+ toggleObserving(true);
+ }
+ }
+
+ function resolveInject (inject, vm) {
+ if (inject) {
+ // inject is :any because flow is not smart enough to figure out cached
+ var result = Object.create(null);
+ var keys = hasSymbol
+ ? Reflect.ownKeys(inject)
+ : Object.keys(inject);
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ // #6574 in case the inject object is observed...
+ if (key === '__ob__') { continue }
+ var provideKey = inject[key].from;
+ var source = vm;
+ while (source) {
+ if (source._provided && hasOwn(source._provided, provideKey)) {
+ result[key] = source._provided[provideKey];
+ break
+ }
+ source = source.$parent;
+ }
+ if (!source) {
+ if ('default' in inject[key]) {
+ var provideDefault = inject[key].default;
+ result[key] = typeof provideDefault === 'function'
+ ? provideDefault.call(vm)
+ : provideDefault;
+ } else {
+ warn(("Injection \"" + key + "\" not found"), vm);
+ }
+ }
+ }
+ return result
+ }
+ }
+
+ /* */
+
+
+
+ /**
+ * Runtime helper for resolving raw children VNodes into a slot object.
+ */
+ function resolveSlots (
+ children,
+ context
+ ) {
+ if (!children || !children.length) {
+ return {}
+ }
+ var slots = {};
+ for (var i = 0, l = children.length; i < l; i++) {
+ var child = children[i];
+ var data = child.data;
+ // remove slot attribute if the node is resolved as a Vue slot node
+ if (data && data.attrs && data.attrs.slot) {
+ delete data.attrs.slot;
+ }
+ // named slots should only be respected if the vnode was rendered in the
+ // same context.
+ if ((child.context === context || child.fnContext === context) &&
+ data && data.slot != null
+ ) {
+ var name = data.slot;
+ var slot = (slots[name] || (slots[name] = []));
+ if (child.tag === 'template') {
+ slot.push.apply(slot, child.children || []);
+ } else {
+ slot.push(child);
+ }
+ } else {
+ (slots.default || (slots.default = [])).push(child);
+ }
+ }
+ // ignore slots that contains only whitespace
+ for (var name$1 in slots) {
+ if (slots[name$1].every(isWhitespace)) {
+ delete slots[name$1];
+ }
+ }
+ return slots
+ }
+
+ function isWhitespace (node) {
+ return (node.isComment && !node.asyncFactory) || node.text === ' '
+ }
+
+ /* */
+
+ function normalizeScopedSlots (
+ slots,
+ normalSlots,
+ prevSlots
+ ) {
+ var res;
+ var hasNormalSlots = Object.keys(normalSlots).length > 0;
+ var isStable = slots ? !!slots.$stable : !hasNormalSlots;
+ var key = slots && slots.$key;
+ if (!slots) {
+ res = {};
+ } else if (slots._normalized) {
+ // fast path 1: child component re-render only, parent did not change
+ return slots._normalized
+ } else if (
+ isStable &&
+ prevSlots &&
+ prevSlots !== emptyObject &&
+ key === prevSlots.$key &&
+ !hasNormalSlots &&
+ !prevSlots.$hasNormal
+ ) {
+ // fast path 2: stable scoped slots w/ no normal slots to proxy,
+ // only need to normalize once
+ return prevSlots
+ } else {
+ res = {};
+ for (var key$1 in slots) {
+ if (slots[key$1] && key$1[0] !== '$') {
+ res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]);
+ }
+ }
+ }
+ // expose normal slots on scopedSlots
+ for (var key$2 in normalSlots) {
+ if (!(key$2 in res)) {
+ res[key$2] = proxyNormalSlot(normalSlots, key$2);
+ }
+ }
+ // avoriaz seems to mock a non-extensible $scopedSlots object
+ // and when that is passed down this would cause an error
+ if (slots && Object.isExtensible(slots)) {
+ (slots)._normalized = res;
+ }
+ def(res, '$stable', isStable);
+ def(res, '$key', key);
+ def(res, '$hasNormal', hasNormalSlots);
+ return res
+ }
+
+ function normalizeScopedSlot(normalSlots, key, fn) {
+ var normalized = function () {
+ var res = arguments.length ? fn.apply(null, arguments) : fn({});
+ res = res && typeof res === 'object' && !Array.isArray(res)
+ ? [res] // single vnode
+ : normalizeChildren(res);
+ return res && (
+ res.length === 0 ||
+ (res.length === 1 && res[0].isComment) // #9658
+ ) ? undefined
+ : res
+ };
+ // this is a slot using the new v-slot syntax without scope. although it is
+ // compiled as a scoped slot, render fn users would expect it to be present
+ // on this.$slots because the usage is semantically a normal slot.
+ if (fn.proxy) {
+ Object.defineProperty(normalSlots, key, {
+ get: normalized,
+ enumerable: true,
+ configurable: true
+ });
+ }
+ return normalized
+ }
+
+ function proxyNormalSlot(slots, key) {
+ return function () { return slots[key]; }
+ }
+
+ /* */
+
+ /**
+ * Runtime helper for rendering v-for lists.
+ */
+ function renderList (
+ val,
+ render
+ ) {
+ var ret, i, l, keys, key;
+ if (Array.isArray(val) || typeof val === 'string') {
+ ret = new Array(val.length);
+ for (i = 0, l = val.length; i < l; i++) {
+ ret[i] = render(val[i], i);
+ }
+ } else if (typeof val === 'number') {
+ ret = new Array(val);
+ for (i = 0; i < val; i++) {
+ ret[i] = render(i + 1, i);
+ }
+ } else if (isObject(val)) {
+ if (hasSymbol && val[Symbol.iterator]) {
+ ret = [];
+ var iterator = val[Symbol.iterator]();
+ var result = iterator.next();
+ while (!result.done) {
+ ret.push(render(result.value, ret.length));
+ result = iterator.next();
+ }
+ } else {
+ keys = Object.keys(val);
+ ret = new Array(keys.length);
+ for (i = 0, l = keys.length; i < l; i++) {
+ key = keys[i];
+ ret[i] = render(val[key], key, i);
+ }
+ }
+ }
+ if (!isDef(ret)) {
+ ret = [];
+ }
+ (ret)._isVList = true;
+ return ret
+ }
+
+ /* */
+
+ /**
+ * Runtime helper for rendering
+ */
+ function renderSlot (
+ name,
+ fallback,
+ props,
+ bindObject
+ ) {
+ var scopedSlotFn = this.$scopedSlots[name];
+ var nodes;
+ if (scopedSlotFn) { // scoped slot
+ props = props || {};
+ if (bindObject) {
+ if (!isObject(bindObject)) {
+ warn(
+ 'slot v-bind without argument expects an Object',
+ this
+ );
+ }
+ props = extend(extend({}, bindObject), props);
+ }
+ nodes = scopedSlotFn(props) || fallback;
+ } else {
+ nodes = this.$slots[name] || fallback;
+ }
+
+ var target = props && props.slot;
+ if (target) {
+ return this.$createElement('template', { slot: target }, nodes)
+ } else {
+ return nodes
+ }
+ }
+
+ /* */
+
+ /**
+ * Runtime helper for resolving filters
+ */
+ function resolveFilter (id) {
+ return resolveAsset(this.$options, 'filters', id, true) || identity
+ }
+
+ /* */
+
+ function isKeyNotMatch (expect, actual) {
+ if (Array.isArray(expect)) {
+ return expect.indexOf(actual) === -1
+ } else {
+ return expect !== actual
+ }
+ }
+
+ /**
+ * Runtime helper for checking keyCodes from config.
+ * exposed as Vue.prototype._k
+ * passing in eventKeyName as last argument separately for backwards compat
+ */
+ function checkKeyCodes (
+ eventKeyCode,
+ key,
+ builtInKeyCode,
+ eventKeyName,
+ builtInKeyName
+ ) {
+ var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
+ if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
+ return isKeyNotMatch(builtInKeyName, eventKeyName)
+ } else if (mappedKeyCode) {
+ return isKeyNotMatch(mappedKeyCode, eventKeyCode)
+ } else if (eventKeyName) {
+ return hyphenate(eventKeyName) !== key
+ }
+ }
+
+ /* */
+
+ /**
+ * Runtime helper for merging v-bind="object" into a VNode's data.
+ */
+ function bindObjectProps (
+ data,
+ tag,
+ value,
+ asProp,
+ isSync
+ ) {
+ if (value) {
+ if (!isObject(value)) {
+ warn(
+ 'v-bind without argument expects an Object or Array value',
+ this
+ );
+ } else {
+ if (Array.isArray(value)) {
+ value = toObject(value);
+ }
+ var hash;
+ var loop = function ( key ) {
+ if (
+ key === 'class' ||
+ key === 'style' ||
+ isReservedAttribute(key)
+ ) {
+ hash = data;
+ } else {
+ var type = data.attrs && data.attrs.type;
+ hash = asProp || config.mustUseProp(tag, type, key)
+ ? data.domProps || (data.domProps = {})
+ : data.attrs || (data.attrs = {});
+ }
+ var camelizedKey = camelize(key);
+ var hyphenatedKey = hyphenate(key);
+ if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {
+ hash[key] = value[key];
+
+ if (isSync) {
+ var on = data.on || (data.on = {});
+ on[("update:" + key)] = function ($event) {
+ value[key] = $event;
+ };
+ }
+ }
+ };
+
+ for (var key in value) loop( key );
+ }
+ }
+ return data
+ }
+
+ /* */
+
+ /**
+ * Runtime helper for rendering static trees.
+ */
+ function renderStatic (
+ index,
+ isInFor
+ ) {
+ var cached = this._staticTrees || (this._staticTrees = []);
+ var tree = cached[index];
+ // if has already-rendered static tree and not inside v-for,
+ // we can reuse the same tree.
+ if (tree && !isInFor) {
+ return tree
+ }
+ // otherwise, render a fresh tree.
+ tree = cached[index] = this.$options.staticRenderFns[index].call(
+ this._renderProxy,
+ null,
+ this // for render fns generated for functional component templates
+ );
+ markStatic(tree, ("__static__" + index), false);
+ return tree
+ }
+
+ /**
+ * Runtime helper for v-once.
+ * Effectively it means marking the node as static with a unique key.
+ */
+ function markOnce (
+ tree,
+ index,
+ key
+ ) {
+ markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
+ return tree
+ }
+
+ function markStatic (
+ tree,
+ key,
+ isOnce
+ ) {
+ if (Array.isArray(tree)) {
+ for (var i = 0; i < tree.length; i++) {
+ if (tree[i] && typeof tree[i] !== 'string') {
+ markStaticNode(tree[i], (key + "_" + i), isOnce);
+ }
+ }
+ } else {
+ markStaticNode(tree, key, isOnce);
+ }
+ }
+
+ function markStaticNode (node, key, isOnce) {
+ node.isStatic = true;
+ node.key = key;
+ node.isOnce = isOnce;
+ }
+
+ /* */
+
+ function bindObjectListeners (data, value) {
+ if (value) {
+ if (!isPlainObject(value)) {
+ warn(
+ 'v-on without argument expects an Object value',
+ this
+ );
+ } else {
+ var on = data.on = data.on ? extend({}, data.on) : {};
+ for (var key in value) {
+ var existing = on[key];
+ var ours = value[key];
+ on[key] = existing ? [].concat(existing, ours) : ours;
+ }
+ }
+ }
+ return data
+ }
+
+ /* */
+
+ function resolveScopedSlots (
+ fns, // see flow/vnode
+ res,
+ // the following are added in 2.6
+ hasDynamicKeys,
+ contentHashKey
+ ) {
+ res = res || { $stable: !hasDynamicKeys };
+ for (var i = 0; i < fns.length; i++) {
+ var slot = fns[i];
+ if (Array.isArray(slot)) {
+ resolveScopedSlots(slot, res, hasDynamicKeys);
+ } else if (slot) {
+ // marker for reverse proxying v-slot without scope on this.$slots
+ if (slot.proxy) {
+ slot.fn.proxy = true;
+ }
+ res[slot.key] = slot.fn;
+ }
+ }
+ if (contentHashKey) {
+ (res).$key = contentHashKey;
+ }
+ return res
+ }
+
+ /* */
+
+ function bindDynamicKeys (baseObj, values) {
+ for (var i = 0; i < values.length; i += 2) {
+ var key = values[i];
+ if (typeof key === 'string' && key) {
+ baseObj[values[i]] = values[i + 1];
+ } else if (key !== '' && key !== null) {
+ // null is a special value for explicitly removing a binding
+ warn(
+ ("Invalid value for dynamic directive argument (expected string or null): " + key),
+ this
+ );
+ }
+ }
+ return baseObj
+ }
+
+ // helper to dynamically append modifier runtime markers to event names.
+ // ensure only append when value is already string, otherwise it will be cast
+ // to string and cause the type check to miss.
+ function prependModifier (value, symbol) {
+ return typeof value === 'string' ? symbol + value : value
+ }
+
+ /* */
+
+ function installRenderHelpers (target) {
+ target._o = markOnce;
+ target._n = toNumber;
+ target._s = toString;
+ target._l = renderList;
+ target._t = renderSlot;
+ target._q = looseEqual;
+ target._i = looseIndexOf;
+ target._m = renderStatic;
+ target._f = resolveFilter;
+ target._k = checkKeyCodes;
+ target._b = bindObjectProps;
+ target._v = createTextVNode;
+ target._e = createEmptyVNode;
+ target._u = resolveScopedSlots;
+ target._g = bindObjectListeners;
+ target._d = bindDynamicKeys;
+ target._p = prependModifier;
+ }
+
+ /* */
+
+ function FunctionalRenderContext (
+ data,
+ props,
+ children,
+ parent,
+ Ctor
+ ) {
+ var this$1 = this;
+
+ var options = Ctor.options;
+ // ensure the createElement function in functional components
+ // gets a unique context - this is necessary for correct named slot check
+ var contextVm;
+ if (hasOwn(parent, '_uid')) {
+ contextVm = Object.create(parent);
+ // $flow-disable-line
+ contextVm._original = parent;
+ } else {
+ // the context vm passed in is a functional context as well.
+ // in this case we want to make sure we are able to get a hold to the
+ // real context instance.
+ contextVm = parent;
+ // $flow-disable-line
+ parent = parent._original;
+ }
+ var isCompiled = isTrue(options._compiled);
+ var needNormalization = !isCompiled;
+
+ this.data = data;
+ this.props = props;
+ this.children = children;
+ this.parent = parent;
+ this.listeners = data.on || emptyObject;
+ this.injections = resolveInject(options.inject, parent);
+ this.slots = function () {
+ if (!this$1.$slots) {
+ normalizeScopedSlots(
+ data.scopedSlots,
+ this$1.$slots = resolveSlots(children, parent)
+ );
+ }
+ return this$1.$slots
+ };
+
+ Object.defineProperty(this, 'scopedSlots', ({
+ enumerable: true,
+ get: function get () {
+ return normalizeScopedSlots(data.scopedSlots, this.slots())
+ }
+ }));
+
+ // support for compiled functional template
+ if (isCompiled) {
+ // exposing $options for renderStatic()
+ this.$options = options;
+ // pre-resolve slots for renderSlot()
+ this.$slots = this.slots();
+ this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);
+ }
+
+ if (options._scopeId) {
+ this._c = function (a, b, c, d) {
+ var vnode = createElement(contextVm, a, b, c, d, needNormalization);
+ if (vnode && !Array.isArray(vnode)) {
+ vnode.fnScopeId = options._scopeId;
+ vnode.fnContext = parent;
+ }
+ return vnode
+ };
+ } else {
+ this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); };
+ }
+ }
+
+ installRenderHelpers(FunctionalRenderContext.prototype);
+
+ function createFunctionalComponent (
+ Ctor,
+ propsData,
+ data,
+ contextVm,
+ children
+ ) {
+ var options = Ctor.options;
+ var props = {};
+ var propOptions = options.props;
+ if (isDef(propOptions)) {
+ for (var key in propOptions) {
+ props[key] = validateProp(key, propOptions, propsData || emptyObject);
+ }
+ } else {
+ if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
+ if (isDef(data.props)) { mergeProps(props, data.props); }
+ }
+
+ var renderContext = new FunctionalRenderContext(
+ data,
+ props,
+ children,
+ contextVm,
+ Ctor
+ );
+
+ var vnode = options.render.call(null, renderContext._c, renderContext);
+
+ if (vnode instanceof VNode) {
+ return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)
+ } else if (Array.isArray(vnode)) {
+ var vnodes = normalizeChildren(vnode) || [];
+ var res = new Array(vnodes.length);
+ for (var i = 0; i < vnodes.length; i++) {
+ res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
+ }
+ return res
+ }
+ }
+
+ function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {
+ // #7817 clone node before setting fnContext, otherwise if the node is reused
+ // (e.g. it was from a cached normal slot) the fnContext causes named slots
+ // that should not be matched to match.
+ var clone = cloneVNode(vnode);
+ clone.fnContext = contextVm;
+ clone.fnOptions = options;
+ {
+ (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;
+ }
+ if (data.slot) {
+ (clone.data || (clone.data = {})).slot = data.slot;
+ }
+ return clone
+ }
+
+ function mergeProps (to, from) {
+ for (var key in from) {
+ to[camelize(key)] = from[key];
+ }
+ }
+
+ /* */
+
+ /* */
+
+ /* */
+
+ /* */
+
+ // inline hooks to be invoked on component VNodes during patch
+ var componentVNodeHooks = {
+ init: function init (vnode, hydrating) {
+ if (
+ vnode.componentInstance &&
+ !vnode.componentInstance._isDestroyed &&
+ vnode.data.keepAlive
+ ) {
+ // kept-alive components, treat as a patch
+ var mountedNode = vnode; // work around flow
+ componentVNodeHooks.prepatch(mountedNode, mountedNode);
+ } else {
+ var child = vnode.componentInstance = createComponentInstanceForVnode(
+ vnode,
+ activeInstance
+ );
+ child.$mount(hydrating ? vnode.elm : undefined, hydrating);
+ }
+ },
+
+ prepatch: function prepatch (oldVnode, vnode) {
+ var options = vnode.componentOptions;
+ var child = vnode.componentInstance = oldVnode.componentInstance;
+ updateChildComponent(
+ child,
+ options.propsData, // updated props
+ options.listeners, // updated listeners
+ vnode, // new parent vnode
+ options.children // new children
+ );
+ },
+
+ insert: function insert (vnode) {
+ var context = vnode.context;
+ var componentInstance = vnode.componentInstance;
+ if (!componentInstance._isMounted) {
+ componentInstance._isMounted = true;
+ callHook(componentInstance, 'mounted');
+ }
+ if (vnode.data.keepAlive) {
+ if (context._isMounted) {
+ // vue-router#1212
+ // During updates, a kept-alive component's child components may
+ // change, so directly walking the tree here may call activated hooks
+ // on incorrect children. Instead we push them into a queue which will
+ // be processed after the whole patch process ended.
+ queueActivatedComponent(componentInstance);
+ } else {
+ activateChildComponent(componentInstance, true /* direct */);
+ }
+ }
+ },
+
+ destroy: function destroy (vnode) {
+ var componentInstance = vnode.componentInstance;
+ if (!componentInstance._isDestroyed) {
+ if (!vnode.data.keepAlive) {
+ componentInstance.$destroy();
+ } else {
+ deactivateChildComponent(componentInstance, true /* direct */);
+ }
+ }
+ }
+ };
+
+ var hooksToMerge = Object.keys(componentVNodeHooks);
+
+ function createComponent (
+ Ctor,
+ data,
+ context,
+ children,
+ tag
+ ) {
+ if (isUndef(Ctor)) {
+ return
+ }
+
+ var baseCtor = context.$options._base;
+
+ // plain options object: turn it into a constructor
+ if (isObject(Ctor)) {
+ Ctor = baseCtor.extend(Ctor);
+ }
+
+ // if at this stage it's not a constructor or an async component factory,
+ // reject.
+ if (typeof Ctor !== 'function') {
+ {
+ warn(("Invalid Component definition: " + (String(Ctor))), context);
+ }
+ return
+ }
+
+ // async component
+ var asyncFactory;
+ if (isUndef(Ctor.cid)) {
+ asyncFactory = Ctor;
+ Ctor = resolveAsyncComponent(asyncFactory, baseCtor);
+ if (Ctor === undefined) {
+ // return a placeholder node for async component, which is rendered
+ // as a comment node but preserves all the raw information for the node.
+ // the information will be used for async server-rendering and hydration.
+ return createAsyncPlaceholder(
+ asyncFactory,
+ data,
+ context,
+ children,
+ tag
+ )
+ }
+ }
+
+ data = data || {};
+
+ // resolve constructor options in case global mixins are applied after
+ // component constructor creation
+ resolveConstructorOptions(Ctor);
+
+ // transform component v-model data into props & events
+ if (isDef(data.model)) {
+ transformModel(Ctor.options, data);
+ }
+
+ // extract props
+ var propsData = extractPropsFromVNodeData(data, Ctor, tag);
+
+ // functional component
+ if (isTrue(Ctor.options.functional)) {
+ return createFunctionalComponent(Ctor, propsData, data, context, children)
+ }
+
+ // extract listeners, since these needs to be treated as
+ // child component listeners instead of DOM listeners
+ var listeners = data.on;
+ // replace with listeners with .native modifier
+ // so it gets processed during parent component patch.
+ data.on = data.nativeOn;
+
+ if (isTrue(Ctor.options.abstract)) {
+ // abstract components do not keep anything
+ // other than props & listeners & slot
+
+ // work around flow
+ var slot = data.slot;
+ data = {};
+ if (slot) {
+ data.slot = slot;
+ }
+ }
+
+ // install component management hooks onto the placeholder node
+ installComponentHooks(data);
+
+ // return a placeholder vnode
+ var name = Ctor.options.name || tag;
+ var vnode = new VNode(
+ ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
+ data, undefined, undefined, undefined, context,
+ { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },
+ asyncFactory
+ );
+
+ return vnode
+ }
+
+ function createComponentInstanceForVnode (
+ vnode, // we know it's MountedComponentVNode but flow doesn't
+ parent // activeInstance in lifecycle state
+ ) {
+ var options = {
+ _isComponent: true,
+ _parentVnode: vnode,
+ parent: parent
+ };
+ // check inline-template render functions
+ var inlineTemplate = vnode.data.inlineTemplate;
+ if (isDef(inlineTemplate)) {
+ options.render = inlineTemplate.render;
+ options.staticRenderFns = inlineTemplate.staticRenderFns;
+ }
+ return new vnode.componentOptions.Ctor(options)
+ }
+
+ function installComponentHooks (data) {
+ var hooks = data.hook || (data.hook = {});
+ for (var i = 0; i < hooksToMerge.length; i++) {
+ var key = hooksToMerge[i];
+ var existing = hooks[key];
+ var toMerge = componentVNodeHooks[key];
+ if (existing !== toMerge && !(existing && existing._merged)) {
+ hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;
+ }
+ }
+ }
+
+ function mergeHook$1 (f1, f2) {
+ var merged = function (a, b) {
+ // flow complains about extra args which is why we use any
+ f1(a, b);
+ f2(a, b);
+ };
+ merged._merged = true;
+ return merged
+ }
+
+ // transform component v-model info (value and callback) into
+ // prop and event handler respectively.
+ function transformModel (options, data) {
+ var prop = (options.model && options.model.prop) || 'value';
+ var event = (options.model && options.model.event) || 'input'
+ ;(data.attrs || (data.attrs = {}))[prop] = data.model.value;
+ var on = data.on || (data.on = {});
+ var existing = on[event];
+ var callback = data.model.callback;
+ if (isDef(existing)) {
+ if (
+ Array.isArray(existing)
+ ? existing.indexOf(callback) === -1
+ : existing !== callback
+ ) {
+ on[event] = [callback].concat(existing);
+ }
+ } else {
+ on[event] = callback;
+ }
+ }
+
+ /* */
+
+ var SIMPLE_NORMALIZE = 1;
+ var ALWAYS_NORMALIZE = 2;
+
+ // wrapper function for providing a more flexible interface
+ // without getting yelled at by flow
+ function createElement (
+ context,
+ tag,
+ data,
+ children,
+ normalizationType,
+ alwaysNormalize
+ ) {
+ if (Array.isArray(data) || isPrimitive(data)) {
+ normalizationType = children;
+ children = data;
+ data = undefined;
+ }
+ if (isTrue(alwaysNormalize)) {
+ normalizationType = ALWAYS_NORMALIZE;
+ }
+ return _createElement(context, tag, data, children, normalizationType)
+ }
+
+ function _createElement (
+ context,
+ tag,
+ data,
+ children,
+ normalizationType
+ ) {
+ if (isDef(data) && isDef((data).__ob__)) {
+ warn(
+ "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
+ 'Always create fresh vnode data objects in each render!',
+ context
+ );
+ return createEmptyVNode()
+ }
+ // object syntax in v-bind
+ if (isDef(data) && isDef(data.is)) {
+ tag = data.is;
+ }
+ if (!tag) {
+ // in case of component :is set to falsy value
+ return createEmptyVNode()
+ }
+ // warn against non-primitive key
+ if (isDef(data) && isDef(data.key) && !isPrimitive(data.key)
+ ) {
+ {
+ warn(
+ 'Avoid using non-primitive value as key, ' +
+ 'use string/number value instead.',
+ context
+ );
+ }
+ }
+ // support single function children as default scoped slot
+ if (Array.isArray(children) &&
+ typeof children[0] === 'function'
+ ) {
+ data = data || {};
+ data.scopedSlots = { default: children[0] };
+ children.length = 0;
+ }
+ if (normalizationType === ALWAYS_NORMALIZE) {
+ children = normalizeChildren(children);
+ } else if (normalizationType === SIMPLE_NORMALIZE) {
+ children = simpleNormalizeChildren(children);
+ }
+ var vnode, ns;
+ if (typeof tag === 'string') {
+ var Ctor;
+ ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
+ if (config.isReservedTag(tag)) {
+ // platform built-in elements
+ if (isDef(data) && isDef(data.nativeOn)) {
+ warn(
+ ("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."),
+ context
+ );
+ }
+ vnode = new VNode(
+ config.parsePlatformTagName(tag), data, children,
+ undefined, undefined, context
+ );
+ } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
+ // component
+ vnode = createComponent(Ctor, data, context, children, tag);
+ } else {
+ // unknown or unlisted namespaced elements
+ // check at runtime because it may get assigned a namespace when its
+ // parent normalizes children
+ vnode = new VNode(
+ tag, data, children,
+ undefined, undefined, context
+ );
+ }
+ } else {
+ // direct component options / constructor
+ vnode = createComponent(tag, data, context, children);
+ }
+ if (Array.isArray(vnode)) {
+ return vnode
+ } else if (isDef(vnode)) {
+ if (isDef(ns)) { applyNS(vnode, ns); }
+ if (isDef(data)) { registerDeepBindings(data); }
+ return vnode
+ } else {
+ return createEmptyVNode()
+ }
+ }
+
+ function applyNS (vnode, ns, force) {
+ vnode.ns = ns;
+ if (vnode.tag === 'foreignObject') {
+ // use default namespace inside foreignObject
+ ns = undefined;
+ force = true;
+ }
+ if (isDef(vnode.children)) {
+ for (var i = 0, l = vnode.children.length; i < l; i++) {
+ var child = vnode.children[i];
+ if (isDef(child.tag) && (
+ isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
+ applyNS(child, ns, force);
+ }
+ }
+ }
+ }
+
+ // ref #5318
+ // necessary to ensure parent re-render when deep bindings like :style and
+ // :class are used on slot nodes
+ function registerDeepBindings (data) {
+ if (isObject(data.style)) {
+ traverse(data.style);
+ }
+ if (isObject(data.class)) {
+ traverse(data.class);
+ }
+ }
+
+ /* */
+
+ function initRender (vm) {
+ vm._vnode = null; // the root of the child tree
+ vm._staticTrees = null; // v-once cached trees
+ var options = vm.$options;
+ var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree
+ var renderContext = parentVnode && parentVnode.context;
+ vm.$slots = resolveSlots(options._renderChildren, renderContext);
+ vm.$scopedSlots = emptyObject;
+ // bind the createElement fn to this instance
+ // so that we get proper render context inside it.
+ // args order: tag, data, children, normalizationType, alwaysNormalize
+ // internal version is used by render functions compiled from templates
+ vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
+ // normalization is always applied for the public version, used in
+ // user-written render functions.
+ vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
+
+ // $attrs & $listeners are exposed for easier HOC creation.
+ // they need to be reactive so that HOCs using them are always updated
+ var parentData = parentVnode && parentVnode.data;
+
+ /* istanbul ignore else */
+ {
+ defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {
+ !isUpdatingChildComponent && warn("$attrs is readonly.", vm);
+ }, true);
+ defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () {
+ !isUpdatingChildComponent && warn("$listeners is readonly.", vm);
+ }, true);
+ }
+ }
+
+ var currentRenderingInstance = null;
+
+ function renderMixin (Vue) {
+ // install runtime convenience helpers
+ installRenderHelpers(Vue.prototype);
+
+ Vue.prototype.$nextTick = function (fn) {
+ return nextTick(fn, this)
+ };
+
+ Vue.prototype._render = function () {
+ var vm = this;
+ var ref = vm.$options;
+ var render = ref.render;
+ var _parentVnode = ref._parentVnode;
+
+ if (_parentVnode) {
+ vm.$scopedSlots = normalizeScopedSlots(
+ _parentVnode.data.scopedSlots,
+ vm.$slots,
+ vm.$scopedSlots
+ );
+ }
+
+ // set parent vnode. this allows render functions to have access
+ // to the data on the placeholder node.
+ vm.$vnode = _parentVnode;
+ // render self
+ var vnode;
+ try {
+ // There's no need to maintain a stack because all render fns are called
+ // separately from one another. Nested component's render fns are called
+ // when parent component is patched.
+ currentRenderingInstance = vm;
+ vnode = render.call(vm._renderProxy, vm.$createElement);
+ } catch (e) {
+ handleError(e, vm, "render");
+ // return error render result,
+ // or previous vnode to prevent render error causing blank component
+ /* istanbul ignore else */
+ if (vm.$options.renderError) {
+ try {
+ vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);
+ } catch (e) {
+ handleError(e, vm, "renderError");
+ vnode = vm._vnode;
+ }
+ } else {
+ vnode = vm._vnode;
+ }
+ } finally {
+ currentRenderingInstance = null;
+ }
+ // if the returned array contains only a single node, allow it
+ if (Array.isArray(vnode) && vnode.length === 1) {
+ vnode = vnode[0];
+ }
+ // return empty vnode in case the render function errored out
+ if (!(vnode instanceof VNode)) {
+ if (Array.isArray(vnode)) {
+ warn(
+ 'Multiple root nodes returned from render function. Render function ' +
+ 'should return a single root node.',
+ vm
+ );
+ }
+ vnode = createEmptyVNode();
+ }
+ // set parent
+ vnode.parent = _parentVnode;
+ return vnode
+ };
+ }
+
+ /* */
+
+ function ensureCtor (comp, base) {
+ if (
+ comp.__esModule ||
+ (hasSymbol && comp[Symbol.toStringTag] === 'Module')
+ ) {
+ comp = comp.default;
+ }
+ return isObject(comp)
+ ? base.extend(comp)
+ : comp
+ }
+
+ function createAsyncPlaceholder (
+ factory,
+ data,
+ context,
+ children,
+ tag
+ ) {
+ var node = createEmptyVNode();
+ node.asyncFactory = factory;
+ node.asyncMeta = { data: data, context: context, children: children, tag: tag };
+ return node
+ }
+
+ function resolveAsyncComponent (
+ factory,
+ baseCtor
+ ) {
+ if (isTrue(factory.error) && isDef(factory.errorComp)) {
+ return factory.errorComp
+ }
+
+ if (isDef(factory.resolved)) {
+ return factory.resolved
+ }
+
+ var owner = currentRenderingInstance;
+ if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) {
+ // already pending
+ factory.owners.push(owner);
+ }
+
+ if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
+ return factory.loadingComp
+ }
+
+ if (owner && !isDef(factory.owners)) {
+ var owners = factory.owners = [owner];
+ var sync = true;
+ var timerLoading = null;
+ var timerTimeout = null
+
+ ;(owner).$on('hook:destroyed', function () { return remove(owners, owner); });
+
+ var forceRender = function (renderCompleted) {
+ for (var i = 0, l = owners.length; i < l; i++) {
+ (owners[i]).$forceUpdate();
+ }
+
+ if (renderCompleted) {
+ owners.length = 0;
+ if (timerLoading !== null) {
+ clearTimeout(timerLoading);
+ timerLoading = null;
+ }
+ if (timerTimeout !== null) {
+ clearTimeout(timerTimeout);
+ timerTimeout = null;
+ }
+ }
+ };
+
+ var resolve = once(function (res) {
+ // cache resolved
+ factory.resolved = ensureCtor(res, baseCtor);
+ // invoke callbacks only if this is not a synchronous resolve
+ // (async resolves are shimmed as synchronous during SSR)
+ if (!sync) {
+ forceRender(true);
+ } else {
+ owners.length = 0;
+ }
+ });
+
+ var reject = once(function (reason) {
+ warn(
+ "Failed to resolve async component: " + (String(factory)) +
+ (reason ? ("\nReason: " + reason) : '')
+ );
+ if (isDef(factory.errorComp)) {
+ factory.error = true;
+ forceRender(true);
+ }
+ });
+
+ var res = factory(resolve, reject);
+
+ if (isObject(res)) {
+ if (isPromise(res)) {
+ // () => Promise
+ if (isUndef(factory.resolved)) {
+ res.then(resolve, reject);
+ }
+ } else if (isPromise(res.component)) {
+ res.component.then(resolve, reject);
+
+ if (isDef(res.error)) {
+ factory.errorComp = ensureCtor(res.error, baseCtor);
+ }
+
+ if (isDef(res.loading)) {
+ factory.loadingComp = ensureCtor(res.loading, baseCtor);
+ if (res.delay === 0) {
+ factory.loading = true;
+ } else {
+ timerLoading = setTimeout(function () {
+ timerLoading = null;
+ if (isUndef(factory.resolved) && isUndef(factory.error)) {
+ factory.loading = true;
+ forceRender(false);
+ }
+ }, res.delay || 200);
+ }
+ }
+
+ if (isDef(res.timeout)) {
+ timerTimeout = setTimeout(function () {
+ timerTimeout = null;
+ if (isUndef(factory.resolved)) {
+ reject(
+ "timeout (" + (res.timeout) + "ms)"
+ );
+ }
+ }, res.timeout);
+ }
+ }
+ }
+
+ sync = false;
+ // return in case resolved synchronously
+ return factory.loading
+ ? factory.loadingComp
+ : factory.resolved
+ }
+ }
+
+ /* */
+
+ function isAsyncPlaceholder (node) {
+ return node.isComment && node.asyncFactory
+ }
+
+ /* */
+
+ function getFirstComponentChild (children) {
+ if (Array.isArray(children)) {
+ for (var i = 0; i < children.length; i++) {
+ var c = children[i];
+ if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
+ return c
+ }
+ }
+ }
+ }
+
+ /* */
+
+ /* */
+
+ function initEvents (vm) {
+ vm._events = Object.create(null);
+ vm._hasHookEvent = false;
+ // init parent attached events
+ var listeners = vm.$options._parentListeners;
+ if (listeners) {
+ updateComponentListeners(vm, listeners);
+ }
+ }
+
+ var target;
+
+ function add (event, fn) {
+ target.$on(event, fn);
+ }
+
+ function remove$1 (event, fn) {
+ target.$off(event, fn);
+ }
+
+ function createOnceHandler (event, fn) {
+ var _target = target;
+ return function onceHandler () {
+ var res = fn.apply(null, arguments);
+ if (res !== null) {
+ _target.$off(event, onceHandler);
+ }
+ }
+ }
+
+ function updateComponentListeners (
+ vm,
+ listeners,
+ oldListeners
+ ) {
+ target = vm;
+ updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);
+ target = undefined;
+ }
+
+ function eventsMixin (Vue) {
+ var hookRE = /^hook:/;
+ Vue.prototype.$on = function (event, fn) {
+ var vm = this;
+ if (Array.isArray(event)) {
+ for (var i = 0, l = event.length; i < l; i++) {
+ vm.$on(event[i], fn);
+ }
+ } else {
+ (vm._events[event] || (vm._events[event] = [])).push(fn);
+ // optimize hook:event cost by using a boolean flag marked at registration
+ // instead of a hash lookup
+ if (hookRE.test(event)) {
+ vm._hasHookEvent = true;
+ }
+ }
+ return vm
+ };
+
+ Vue.prototype.$once = function (event, fn) {
+ var vm = this;
+ function on () {
+ vm.$off(event, on);
+ fn.apply(vm, arguments);
+ }
+ on.fn = fn;
+ vm.$on(event, on);
+ return vm
+ };
+
+ Vue.prototype.$off = function (event, fn) {
+ var vm = this;
+ // all
+ if (!arguments.length) {
+ vm._events = Object.create(null);
+ return vm
+ }
+ // array of events
+ if (Array.isArray(event)) {
+ for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
+ vm.$off(event[i$1], fn);
+ }
+ return vm
+ }
+ // specific event
+ var cbs = vm._events[event];
+ if (!cbs) {
+ return vm
+ }
+ if (!fn) {
+ vm._events[event] = null;
+ return vm
+ }
+ // specific handler
+ var cb;
+ var i = cbs.length;
+ while (i--) {
+ cb = cbs[i];
+ if (cb === fn || cb.fn === fn) {
+ cbs.splice(i, 1);
+ break
+ }
+ }
+ return vm
+ };
+
+ Vue.prototype.$emit = function (event) {
+ var vm = this;
+ {
+ var lowerCaseEvent = event.toLowerCase();
+ if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
+ tip(
+ "Event \"" + lowerCaseEvent + "\" is emitted in component " +
+ (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
+ "Note that HTML attributes are case-insensitive and you cannot use " +
+ "v-on to listen to camelCase events when using in-DOM templates. " +
+ "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
+ );
+ }
+ }
+ var cbs = vm._events[event];
+ if (cbs) {
+ cbs = cbs.length > 1 ? toArray(cbs) : cbs;
+ var args = toArray(arguments, 1);
+ var info = "event handler for \"" + event + "\"";
+ for (var i = 0, l = cbs.length; i < l; i++) {
+ invokeWithErrorHandling(cbs[i], vm, args, vm, info);
+ }
+ }
+ return vm
+ };
+ }
+
+ /* */
+
+ var activeInstance = null;
+ var isUpdatingChildComponent = false;
+
+ function setActiveInstance(vm) {
+ var prevActiveInstance = activeInstance;
+ activeInstance = vm;
+ return function () {
+ activeInstance = prevActiveInstance;
+ }
+ }
+
+ function initLifecycle (vm) {
+ var options = vm.$options;
+
+ // locate first non-abstract parent
+ var parent = options.parent;
+ if (parent && !options.abstract) {
+ while (parent.$options.abstract && parent.$parent) {
+ parent = parent.$parent;
+ }
+ parent.$children.push(vm);
+ }
+
+ vm.$parent = parent;
+ vm.$root = parent ? parent.$root : vm;
+
+ vm.$children = [];
+ vm.$refs = {};
+
+ vm._watcher = null;
+ vm._inactive = null;
+ vm._directInactive = false;
+ vm._isMounted = false;
+ vm._isDestroyed = false;
+ vm._isBeingDestroyed = false;
+ }
+
+ function lifecycleMixin (Vue) {
+ Vue.prototype._update = function (vnode, hydrating) {
+ var vm = this;
+ var prevEl = vm.$el;
+ var prevVnode = vm._vnode;
+ var restoreActiveInstance = setActiveInstance(vm);
+ vm._vnode = vnode;
+ // Vue.prototype.__patch__ is injected in entry points
+ // based on the rendering backend used.
+ if (!prevVnode) {
+ // initial render
+ vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */);
+ } else {
+ // updates
+ vm.$el = vm.__patch__(prevVnode, vnode);
+ }
+ restoreActiveInstance();
+ // update __vue__ reference
+ if (prevEl) {
+ prevEl.__vue__ = null;
+ }
+ if (vm.$el) {
+ vm.$el.__vue__ = vm;
+ }
+ // if parent is an HOC, update its $el as well
+ if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
+ vm.$parent.$el = vm.$el;
+ }
+ // updated hook is called by the scheduler to ensure that children are
+ // updated in a parent's updated hook.
+ };
+
+ Vue.prototype.$forceUpdate = function () {
+ var vm = this;
+ if (vm._watcher) {
+ vm._watcher.update();
+ }
+ };
+
+ Vue.prototype.$destroy = function () {
+ var vm = this;
+ if (vm._isBeingDestroyed) {
+ return
+ }
+ callHook(vm, 'beforeDestroy');
+ vm._isBeingDestroyed = true;
+ // remove self from parent
+ var parent = vm.$parent;
+ if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
+ remove(parent.$children, vm);
+ }
+ // teardown watchers
+ if (vm._watcher) {
+ vm._watcher.teardown();
+ }
+ var i = vm._watchers.length;
+ while (i--) {
+ vm._watchers[i].teardown();
+ }
+ // remove reference from data ob
+ // frozen object may not have observer.
+ if (vm._data.__ob__) {
+ vm._data.__ob__.vmCount--;
+ }
+ // call the last hook...
+ vm._isDestroyed = true;
+ // invoke destroy hooks on current rendered tree
+ vm.__patch__(vm._vnode, null);
+ // fire destroyed hook
+ callHook(vm, 'destroyed');
+ // turn off all instance listeners.
+ vm.$off();
+ // remove __vue__ reference
+ if (vm.$el) {
+ vm.$el.__vue__ = null;
+ }
+ // release circular reference (#6759)
+ if (vm.$vnode) {
+ vm.$vnode.parent = null;
+ }
+ };
+ }
+
+ function mountComponent (
+ vm,
+ el,
+ hydrating
+ ) {
+ vm.$el = el;
+ if (!vm.$options.render) {
+ vm.$options.render = createEmptyVNode;
+ {
+ /* istanbul ignore if */
+ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
+ vm.$options.el || el) {
+ warn(
+ 'You are using the runtime-only build of Vue where the template ' +
+ 'compiler is not available. Either pre-compile the templates into ' +
+ 'render functions, or use the compiler-included build.',
+ vm
+ );
+ } else {
+ warn(
+ 'Failed to mount component: template or render function not defined.',
+ vm
+ );
+ }
+ }
+ }
+ callHook(vm, 'beforeMount');
+
+ var updateComponent;
+ /* istanbul ignore if */
+ if (config.performance && mark) {
+ updateComponent = function () {
+ var name = vm._name;
+ var id = vm._uid;
+ var startTag = "vue-perf-start:" + id;
+ var endTag = "vue-perf-end:" + id;
+
+ mark(startTag);
+ var vnode = vm._render();
+ mark(endTag);
+ measure(("vue " + name + " render"), startTag, endTag);
+
+ mark(startTag);
+ vm._update(vnode, hydrating);
+ mark(endTag);
+ measure(("vue " + name + " patch"), startTag, endTag);
+ };
+ } else {
+ updateComponent = function () {
+ vm._update(vm._render(), hydrating);
+ };
+ }
+
+ // we set this to vm._watcher inside the watcher's constructor
+ // since the watcher's initial patch may call $forceUpdate (e.g. inside child
+ // component's mounted hook), which relies on vm._watcher being already defined
+ new Watcher(vm, updateComponent, noop, {
+ before: function before () {
+ if (vm._isMounted && !vm._isDestroyed) {
+ callHook(vm, 'beforeUpdate');
+ }
+ }
+ }, true /* isRenderWatcher */);
+ hydrating = false;
+
+ // manually mounted instance, call mounted on self
+ // mounted is called for render-created child components in its inserted hook
+ if (vm.$vnode == null) {
+ vm._isMounted = true;
+ callHook(vm, 'mounted');
+ }
+ return vm
+ }
+
+ function updateChildComponent (
+ vm,
+ propsData,
+ listeners,
+ parentVnode,
+ renderChildren
+ ) {
+ {
+ isUpdatingChildComponent = true;
+ }
+
+ // determine whether component has slot children
+ // we need to do this before overwriting $options._renderChildren.
+
+ // check if there are dynamic scopedSlots (hand-written or compiled but with
+ // dynamic slot names). Static scoped slots compiled from template has the
+ // "$stable" marker.
+ var newScopedSlots = parentVnode.data.scopedSlots;
+ var oldScopedSlots = vm.$scopedSlots;
+ var hasDynamicScopedSlot = !!(
+ (newScopedSlots && !newScopedSlots.$stable) ||
+ (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) ||
+ (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key)
+ );
+
+ // Any static slot children from the parent may have changed during parent's
+ // update. Dynamic scoped slots may also have changed. In such cases, a forced
+ // update is necessary to ensure correctness.
+ var needsForceUpdate = !!(
+ renderChildren || // has new static slots
+ vm.$options._renderChildren || // has old static slots
+ hasDynamicScopedSlot
+ );
+
+ vm.$options._parentVnode = parentVnode;
+ vm.$vnode = parentVnode; // update vm's placeholder node without re-render
+
+ if (vm._vnode) { // update child tree's parent
+ vm._vnode.parent = parentVnode;
+ }
+ vm.$options._renderChildren = renderChildren;
+
+ // update $attrs and $listeners hash
+ // these are also reactive so they may trigger child update if the child
+ // used them during render
+ vm.$attrs = parentVnode.data.attrs || emptyObject;
+ vm.$listeners = listeners || emptyObject;
+
+ // update props
+ if (propsData && vm.$options.props) {
+ toggleObserving(false);
+ var props = vm._props;
+ var propKeys = vm.$options._propKeys || [];
+ for (var i = 0; i < propKeys.length; i++) {
+ var key = propKeys[i];
+ var propOptions = vm.$options.props; // wtf flow?
+ props[key] = validateProp(key, propOptions, propsData, vm);
+ }
+ toggleObserving(true);
+ // keep a copy of raw propsData
+ vm.$options.propsData = propsData;
+ }
+
+ // update listeners
+ listeners = listeners || emptyObject;
+ var oldListeners = vm.$options._parentListeners;
+ vm.$options._parentListeners = listeners;
+ updateComponentListeners(vm, listeners, oldListeners);
+
+ // resolve slots + force update if has children
+ if (needsForceUpdate) {
+ vm.$slots = resolveSlots(renderChildren, parentVnode.context);
+ vm.$forceUpdate();
+ }
+
+ {
+ isUpdatingChildComponent = false;
+ }
+ }
+
+ function isInInactiveTree (vm) {
+ while (vm && (vm = vm.$parent)) {
+ if (vm._inactive) { return true }
+ }
+ return false
+ }
+
+ function activateChildComponent (vm, direct) {
+ if (direct) {
+ vm._directInactive = false;
+ if (isInInactiveTree(vm)) {
+ return
+ }
+ } else if (vm._directInactive) {
+ return
+ }
+ if (vm._inactive || vm._inactive === null) {
+ vm._inactive = false;
+ for (var i = 0; i < vm.$children.length; i++) {
+ activateChildComponent(vm.$children[i]);
+ }
+ callHook(vm, 'activated');
+ }
+ }
+
+ function deactivateChildComponent (vm, direct) {
+ if (direct) {
+ vm._directInactive = true;
+ if (isInInactiveTree(vm)) {
+ return
+ }
+ }
+ if (!vm._inactive) {
+ vm._inactive = true;
+ for (var i = 0; i < vm.$children.length; i++) {
+ deactivateChildComponent(vm.$children[i]);
+ }
+ callHook(vm, 'deactivated');
+ }
+ }
+
+ function callHook (vm, hook) {
+ // #7573 disable dep collection when invoking lifecycle hooks
+ pushTarget();
+ var handlers = vm.$options[hook];
+ var info = hook + " hook";
+ if (handlers) {
+ for (var i = 0, j = handlers.length; i < j; i++) {
+ invokeWithErrorHandling(handlers[i], vm, null, vm, info);
+ }
+ }
+ if (vm._hasHookEvent) {
+ vm.$emit('hook:' + hook);
+ }
+ popTarget();
+ }
+
+ /* */
+
+ var MAX_UPDATE_COUNT = 100;
+
+ var queue = [];
+ var activatedChildren = [];
+ var has = {};
+ var circular = {};
+ var waiting = false;
+ var flushing = false;
+ var index = 0;
+
+ /**
+ * Reset the scheduler's state.
+ */
+ function resetSchedulerState () {
+ index = queue.length = activatedChildren.length = 0;
+ has = {};
+ {
+ circular = {};
+ }
+ waiting = flushing = false;
+ }
+
+ // Async edge case #6566 requires saving the timestamp when event listeners are
+ // attached. However, calling performance.now() has a perf overhead especially
+ // if the page has thousands of event listeners. Instead, we take a timestamp
+ // every time the scheduler flushes and use that for all event listeners
+ // attached during that flush.
+ var currentFlushTimestamp = 0;
+
+ // Async edge case fix requires storing an event listener's attach timestamp.
+ var getNow = Date.now;
+
+ // Determine what event timestamp the browser is using. Annoyingly, the
+ // timestamp can either be hi-res (relative to page load) or low-res
+ // (relative to UNIX epoch), so in order to compare time we have to use the
+ // same timestamp type when saving the flush timestamp.
+ // All IE versions use low-res event timestamps, and have problematic clock
+ // implementations (#9632)
+ if (inBrowser && !isIE) {
+ var performance = window.performance;
+ if (
+ performance &&
+ typeof performance.now === 'function' &&
+ getNow() > document.createEvent('Event').timeStamp
+ ) {
+ // if the event timestamp, although evaluated AFTER the Date.now(), is
+ // smaller than it, it means the event is using a hi-res timestamp,
+ // and we need to use the hi-res version for event listener timestamps as
+ // well.
+ getNow = function () { return performance.now(); };
+ }
+ }
+
+ /**
+ * Flush both queues and run the watchers.
+ */
+ function flushSchedulerQueue () {
+ currentFlushTimestamp = getNow();
+ flushing = true;
+ var watcher, id;
+
+ // Sort queue before flush.
+ // This ensures that:
+ // 1. Components are updated from parent to child. (because parent is always
+ // created before the child)
+ // 2. A component's user watchers are run before its render watcher (because
+ // user watchers are created before the render watcher)
+ // 3. If a component is destroyed during a parent component's watcher run,
+ // its watchers can be skipped.
+ queue.sort(function (a, b) { return a.id - b.id; });
+
+ // do not cache length because more watchers might be pushed
+ // as we run existing watchers
+ for (index = 0; index < queue.length; index++) {
+ watcher = queue[index];
+ if (watcher.before) {
+ watcher.before();
+ }
+ id = watcher.id;
+ has[id] = null;
+ watcher.run();
+ // in dev build, check and stop circular updates.
+ if (has[id] != null) {
+ circular[id] = (circular[id] || 0) + 1;
+ if (circular[id] > MAX_UPDATE_COUNT) {
+ warn(
+ 'You may have an infinite update loop ' + (
+ watcher.user
+ ? ("in watcher with expression \"" + (watcher.expression) + "\"")
+ : "in a component render function."
+ ),
+ watcher.vm
+ );
+ break
+ }
+ }
+ }
+
+ // keep copies of post queues before resetting state
+ var activatedQueue = activatedChildren.slice();
+ var updatedQueue = queue.slice();
+
+ resetSchedulerState();
+
+ // call component updated and activated hooks
+ callActivatedHooks(activatedQueue);
+ callUpdatedHooks(updatedQueue);
+
+ // devtool hook
+ /* istanbul ignore if */
+ if (devtools && config.devtools) {
+ devtools.emit('flush');
+ }
+ }
+
+ function callUpdatedHooks (queue) {
+ var i = queue.length;
+ while (i--) {
+ var watcher = queue[i];
+ var vm = watcher.vm;
+ if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
+ callHook(vm, 'updated');
+ }
+ }
+ }
+
+ /**
+ * Queue a kept-alive component that was activated during patch.
+ * The queue will be processed after the entire tree has been patched.
+ */
+ function queueActivatedComponent (vm) {
+ // setting _inactive to false here so that a render function can
+ // rely on checking whether it's in an inactive tree (e.g. router-view)
+ vm._inactive = false;
+ activatedChildren.push(vm);
+ }
+
+ function callActivatedHooks (queue) {
+ for (var i = 0; i < queue.length; i++) {
+ queue[i]._inactive = true;
+ activateChildComponent(queue[i], true /* true */);
+ }
+ }
+
+ /**
+ * Push a watcher into the watcher queue.
+ * Jobs with duplicate IDs will be skipped unless it's
+ * pushed when the queue is being flushed.
+ */
+ function queueWatcher (watcher) {
+ var id = watcher.id;
+ if (has[id] == null) {
+ has[id] = true;
+ if (!flushing) {
+ queue.push(watcher);
+ } else {
+ // if already flushing, splice the watcher based on its id
+ // if already past its id, it will be run next immediately.
+ var i = queue.length - 1;
+ while (i > index && queue[i].id > watcher.id) {
+ i--;
+ }
+ queue.splice(i + 1, 0, watcher);
+ }
+ // queue the flush
+ if (!waiting) {
+ waiting = true;
+
+ if (!config.async) {
+ flushSchedulerQueue();
+ return
+ }
+ nextTick(flushSchedulerQueue);
+ }
+ }
+ }
+
+ /* */
+
+
+
+ var uid$2 = 0;
+
+ /**
+ * A watcher parses an expression, collects dependencies,
+ * and fires callback when the expression value changes.
+ * This is used for both the $watch() api and directives.
+ */
+ var Watcher = function Watcher (
+ vm,
+ expOrFn,
+ cb,
+ options,
+ isRenderWatcher
+ ) {
+ this.vm = vm;
+ if (isRenderWatcher) {
+ vm._watcher = this;
+ }
+ vm._watchers.push(this);
+ // options
+ if (options) {
+ this.deep = !!options.deep;
+ this.user = !!options.user;
+ this.lazy = !!options.lazy;
+ this.sync = !!options.sync;
+ this.before = options.before;
+ } else {
+ this.deep = this.user = this.lazy = this.sync = false;
+ }
+ this.cb = cb;
+ this.id = ++uid$2; // uid for batching
+ this.active = true;
+ this.dirty = this.lazy; // for lazy watchers
+ this.deps = [];
+ this.newDeps = [];
+ this.depIds = new _Set();
+ this.newDepIds = new _Set();
+ this.expression = expOrFn.toString();
+ // parse expression for getter
+ if (typeof expOrFn === 'function') {
+ this.getter = expOrFn;
+ } else {
+ this.getter = parsePath(expOrFn);
+ if (!this.getter) {
+ this.getter = noop;
+ warn(
+ "Failed watching path: \"" + expOrFn + "\" " +
+ 'Watcher only accepts simple dot-delimited paths. ' +
+ 'For full control, use a function instead.',
+ vm
+ );
+ }
+ }
+ this.value = this.lazy
+ ? undefined
+ : this.get();
+ };
+
+ /**
+ * Evaluate the getter, and re-collect dependencies.
+ */
+ Watcher.prototype.get = function get () {
+ pushTarget(this);
+ var value;
+ var vm = this.vm;
+ try {
+ value = this.getter.call(vm, vm);
+ } catch (e) {
+ if (this.user) {
+ handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
+ } else {
+ throw e
+ }
+ } finally {
+ // "touch" every property so they are all tracked as
+ // dependencies for deep watching
+ if (this.deep) {
+ traverse(value);
+ }
+ popTarget();
+ this.cleanupDeps();
+ }
+ return value
+ };
+
+ /**
+ * Add a dependency to this directive.
+ */
+ Watcher.prototype.addDep = function addDep (dep) {
+ var id = dep.id;
+ if (!this.newDepIds.has(id)) {
+ this.newDepIds.add(id);
+ this.newDeps.push(dep);
+ if (!this.depIds.has(id)) {
+ dep.addSub(this);
+ }
+ }
+ };
+
+ /**
+ * Clean up for dependency collection.
+ */
+ Watcher.prototype.cleanupDeps = function cleanupDeps () {
+ var i = this.deps.length;
+ while (i--) {
+ var dep = this.deps[i];
+ if (!this.newDepIds.has(dep.id)) {
+ dep.removeSub(this);
+ }
+ }
+ var tmp = this.depIds;
+ this.depIds = this.newDepIds;
+ this.newDepIds = tmp;
+ this.newDepIds.clear();
+ tmp = this.deps;
+ this.deps = this.newDeps;
+ this.newDeps = tmp;
+ this.newDeps.length = 0;
+ };
+
+ /**
+ * Subscriber interface.
+ * Will be called when a dependency changes.
+ */
+ Watcher.prototype.update = function update () {
+ /* istanbul ignore else */
+ if (this.lazy) {
+ this.dirty = true;
+ } else if (this.sync) {
+ this.run();
+ } else {
+ queueWatcher(this);
+ }
+ };
+
+ /**
+ * Scheduler job interface.
+ * Will be called by the scheduler.
+ */
+ Watcher.prototype.run = function run () {
+ if (this.active) {
+ var value = this.get();
+ if (
+ value !== this.value ||
+ // Deep watchers and watchers on Object/Arrays should fire even
+ // when the value is the same, because the value may
+ // have mutated.
+ isObject(value) ||
+ this.deep
+ ) {
+ // set new value
+ var oldValue = this.value;
+ this.value = value;
+ if (this.user) {
+ try {
+ this.cb.call(this.vm, value, oldValue);
+ } catch (e) {
+ handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
+ }
+ } else {
+ this.cb.call(this.vm, value, oldValue);
+ }
+ }
+ }
+ };
+
+ /**
+ * Evaluate the value of the watcher.
+ * This only gets called for lazy watchers.
+ */
+ Watcher.prototype.evaluate = function evaluate () {
+ this.value = this.get();
+ this.dirty = false;
+ };
+
+ /**
+ * Depend on all deps collected by this watcher.
+ */
+ Watcher.prototype.depend = function depend () {
+ var i = this.deps.length;
+ while (i--) {
+ this.deps[i].depend();
+ }
+ };
+
+ /**
+ * Remove self from all dependencies' subscriber list.
+ */
+ Watcher.prototype.teardown = function teardown () {
+ if (this.active) {
+ // remove self from vm's watcher list
+ // this is a somewhat expensive operation so we skip it
+ // if the vm is being destroyed.
+ if (!this.vm._isBeingDestroyed) {
+ remove(this.vm._watchers, this);
+ }
+ var i = this.deps.length;
+ while (i--) {
+ this.deps[i].removeSub(this);
+ }
+ this.active = false;
+ }
+ };
+
+ /* */
+
+ var sharedPropertyDefinition = {
+ enumerable: true,
+ configurable: true,
+ get: noop,
+ set: noop
+ };
+
+ function proxy (target, sourceKey, key) {
+ sharedPropertyDefinition.get = function proxyGetter () {
+ return this[sourceKey][key]
+ };
+ sharedPropertyDefinition.set = function proxySetter (val) {
+ this[sourceKey][key] = val;
+ };
+ Object.defineProperty(target, key, sharedPropertyDefinition);
+ }
+
+ function initState (vm) {
+ vm._watchers = [];
+ var opts = vm.$options;
+ if (opts.props) { initProps(vm, opts.props); }
+ if (opts.methods) { initMethods(vm, opts.methods); }
+ if (opts.data) {
+ initData(vm);
+ } else {
+ observe(vm._data = {}, true /* asRootData */);
+ }
+ if (opts.computed) { initComputed(vm, opts.computed); }
+ if (opts.watch && opts.watch !== nativeWatch) {
+ initWatch(vm, opts.watch);
+ }
+ }
+
+ function initProps (vm, propsOptions) {
+ var propsData = vm.$options.propsData || {};
+ var props = vm._props = {};
+ // cache prop keys so that future props updates can iterate using Array
+ // instead of dynamic object key enumeration.
+ var keys = vm.$options._propKeys = [];
+ var isRoot = !vm.$parent;
+ // root instance props should be converted
+ if (!isRoot) {
+ toggleObserving(false);
+ }
+ var loop = function ( key ) {
+ keys.push(key);
+ var value = validateProp(key, propsOptions, propsData, vm);
+ /* istanbul ignore else */
+ {
+ var hyphenatedKey = hyphenate(key);
+ if (isReservedAttribute(hyphenatedKey) ||
+ config.isReservedAttr(hyphenatedKey)) {
+ warn(
+ ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."),
+ vm
+ );
+ }
+ defineReactive$$1(props, key, value, function () {
+ if (!isRoot && !isUpdatingChildComponent) {
+ warn(
+ "Avoid mutating a prop directly since the value will be " +
+ "overwritten whenever the parent component re-renders. " +
+ "Instead, use a data or computed property based on the prop's " +
+ "value. Prop being mutated: \"" + key + "\"",
+ vm
+ );
+ }
+ });
+ }
+ // static props are already proxied on the component's prototype
+ // during Vue.extend(). We only need to proxy props defined at
+ // instantiation here.
+ if (!(key in vm)) {
+ proxy(vm, "_props", key);
+ }
+ };
+
+ for (var key in propsOptions) loop( key );
+ toggleObserving(true);
+ }
+
+ function initData (vm) {
+ var data = vm.$options.data;
+ data = vm._data = typeof data === 'function'
+ ? getData(data, vm)
+ : data || {};
+ if (!isPlainObject(data)) {
+ data = {};
+ warn(
+ 'data functions should return an object:\n' +
+ 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
+ vm
+ );
+ }
+ // proxy data on instance
+ var keys = Object.keys(data);
+ var props = vm.$options.props;
+ var methods = vm.$options.methods;
+ var i = keys.length;
+ while (i--) {
+ var key = keys[i];
+ {
+ if (methods && hasOwn(methods, key)) {
+ warn(
+ ("Method \"" + key + "\" has already been defined as a data property."),
+ vm
+ );
+ }
+ }
+ if (props && hasOwn(props, key)) {
+ warn(
+ "The data property \"" + key + "\" is already declared as a prop. " +
+ "Use prop default value instead.",
+ vm
+ );
+ } else if (!isReserved(key)) {
+ proxy(vm, "_data", key);
+ }
+ }
+ // observe data
+ observe(data, true /* asRootData */);
+ }
+
+ function getData (data, vm) {
+ // #7573 disable dep collection when invoking data getters
+ pushTarget();
+ try {
+ return data.call(vm, vm)
+ } catch (e) {
+ handleError(e, vm, "data()");
+ return {}
+ } finally {
+ popTarget();
+ }
+ }
+
+ var computedWatcherOptions = { lazy: true };
+
+ function initComputed (vm, computed) {
+ // $flow-disable-line
+ var watchers = vm._computedWatchers = Object.create(null);
+ // computed properties are just getters during SSR
+ var isSSR = isServerRendering();
+
+ for (var key in computed) {
+ var userDef = computed[key];
+ var getter = typeof userDef === 'function' ? userDef : userDef.get;
+ if (getter == null) {
+ warn(
+ ("Getter is missing for computed property \"" + key + "\"."),
+ vm
+ );
+ }
+
+ if (!isSSR) {
+ // create internal watcher for the computed property.
+ watchers[key] = new Watcher(
+ vm,
+ getter || noop,
+ noop,
+ computedWatcherOptions
+ );
+ }
+
+ // component-defined computed properties are already defined on the
+ // component prototype. We only need to define computed properties defined
+ // at instantiation here.
+ if (!(key in vm)) {
+ defineComputed(vm, key, userDef);
+ } else {
+ if (key in vm.$data) {
+ warn(("The computed property \"" + key + "\" is already defined in data."), vm);
+ } else if (vm.$options.props && key in vm.$options.props) {
+ warn(("The computed property \"" + key + "\" is already defined as a prop."), vm);
+ }
+ }
+ }
+ }
+
+ function defineComputed (
+ target,
+ key,
+ userDef
+ ) {
+ var shouldCache = !isServerRendering();
+ if (typeof userDef === 'function') {
+ sharedPropertyDefinition.get = shouldCache
+ ? createComputedGetter(key)
+ : createGetterInvoker(userDef);
+ sharedPropertyDefinition.set = noop;
+ } else {
+ sharedPropertyDefinition.get = userDef.get
+ ? shouldCache && userDef.cache !== false
+ ? createComputedGetter(key)
+ : createGetterInvoker(userDef.get)
+ : noop;
+ sharedPropertyDefinition.set = userDef.set || noop;
+ }
+ if (sharedPropertyDefinition.set === noop) {
+ sharedPropertyDefinition.set = function () {
+ warn(
+ ("Computed property \"" + key + "\" was assigned to but it has no setter."),
+ this
+ );
+ };
+ }
+ Object.defineProperty(target, key, sharedPropertyDefinition);
+ }
+
+ function createComputedGetter (key) {
+ return function computedGetter () {
+ var watcher = this._computedWatchers && this._computedWatchers[key];
+ if (watcher) {
+ if (watcher.dirty) {
+ watcher.evaluate();
+ }
+ if (Dep.target) {
+ watcher.depend();
+ }
+ return watcher.value
+ }
+ }
+ }
+
+ function createGetterInvoker(fn) {
+ return function computedGetter () {
+ return fn.call(this, this)
+ }
+ }
+
+ function initMethods (vm, methods) {
+ var props = vm.$options.props;
+ for (var key in methods) {
+ {
+ if (typeof methods[key] !== 'function') {
+ warn(
+ "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
+ "Did you reference the function correctly?",
+ vm
+ );
+ }
+ if (props && hasOwn(props, key)) {
+ warn(
+ ("Method \"" + key + "\" has already been defined as a prop."),
+ vm
+ );
+ }
+ if ((key in vm) && isReserved(key)) {
+ warn(
+ "Method \"" + key + "\" conflicts with an existing Vue instance method. " +
+ "Avoid defining component methods that start with _ or $."
+ );
+ }
+ }
+ vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
+ }
+ }
+
+ function initWatch (vm, watch) {
+ for (var key in watch) {
+ var handler = watch[key];
+ if (Array.isArray(handler)) {
+ for (var i = 0; i < handler.length; i++) {
+ createWatcher(vm, key, handler[i]);
+ }
+ } else {
+ createWatcher(vm, key, handler);
+ }
+ }
+ }
+
+ function createWatcher (
+ vm,
+ expOrFn,
+ handler,
+ options
+ ) {
+ if (isPlainObject(handler)) {
+ options = handler;
+ handler = handler.handler;
+ }
+ if (typeof handler === 'string') {
+ handler = vm[handler];
+ }
+ return vm.$watch(expOrFn, handler, options)
+ }
+
+ function stateMixin (Vue) {
+ // flow somehow has problems with directly declared definition object
+ // when using Object.defineProperty, so we have to procedurally build up
+ // the object here.
+ var dataDef = {};
+ dataDef.get = function () { return this._data };
+ var propsDef = {};
+ propsDef.get = function () { return this._props };
+ {
+ dataDef.set = function () {
+ warn(
+ 'Avoid replacing instance root $data. ' +
+ 'Use nested data properties instead.',
+ this
+ );
+ };
+ propsDef.set = function () {
+ warn("$props is readonly.", this);
+ };
+ }
+ Object.defineProperty(Vue.prototype, '$data', dataDef);
+ Object.defineProperty(Vue.prototype, '$props', propsDef);
+
+ Vue.prototype.$set = set;
+ Vue.prototype.$delete = del;
+
+ Vue.prototype.$watch = function (
+ expOrFn,
+ cb,
+ options
+ ) {
+ var vm = this;
+ if (isPlainObject(cb)) {
+ return createWatcher(vm, expOrFn, cb, options)
+ }
+ options = options || {};
+ options.user = true;
+ var watcher = new Watcher(vm, expOrFn, cb, options);
+ if (options.immediate) {
+ try {
+ cb.call(vm, watcher.value);
+ } catch (error) {
+ handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\""));
+ }
+ }
+ return function unwatchFn () {
+ watcher.teardown();
+ }
+ };
+ }
+
+ /* */
+
+ var uid$3 = 0;
+
+ function initMixin (Vue) {
+ Vue.prototype._init = function (options) {
+ var vm = this;
+ // a uid
+ vm._uid = uid$3++;
+
+ var startTag, endTag;
+ /* istanbul ignore if */
+ if (config.performance && mark) {
+ startTag = "vue-perf-start:" + (vm._uid);
+ endTag = "vue-perf-end:" + (vm._uid);
+ mark(startTag);
+ }
+
+ // a flag to avoid this being observed
+ vm._isVue = true;
+ // merge options
+ if (options && options._isComponent) {
+ // optimize internal component instantiation
+ // since dynamic options merging is pretty slow, and none of the
+ // internal component options needs special treatment.
+ initInternalComponent(vm, options);
+ } else {
+ vm.$options = mergeOptions(
+ resolveConstructorOptions(vm.constructor),
+ options || {},
+ vm
+ );
+ }
+ /* istanbul ignore else */
+ {
+ initProxy(vm);
+ }
+ // expose real self
+ vm._self = vm;
+ initLifecycle(vm);
+ initEvents(vm);
+ initRender(vm);
+ callHook(vm, 'beforeCreate');
+ initInjections(vm); // resolve injections before data/props
+ initState(vm);
+ initProvide(vm); // resolve provide after data/props
+ callHook(vm, 'created');
+
+ /* istanbul ignore if */
+ if (config.performance && mark) {
+ vm._name = formatComponentName(vm, false);
+ mark(endTag);
+ measure(("vue " + (vm._name) + " init"), startTag, endTag);
+ }
+
+ if (vm.$options.el) {
+ vm.$mount(vm.$options.el);
+ }
+ };
+ }
+
+ function initInternalComponent (vm, options) {
+ var opts = vm.$options = Object.create(vm.constructor.options);
+ // doing this because it's faster than dynamic enumeration.
+ var parentVnode = options._parentVnode;
+ opts.parent = options.parent;
+ opts._parentVnode = parentVnode;
+
+ var vnodeComponentOptions = parentVnode.componentOptions;
+ opts.propsData = vnodeComponentOptions.propsData;
+ opts._parentListeners = vnodeComponentOptions.listeners;
+ opts._renderChildren = vnodeComponentOptions.children;
+ opts._componentTag = vnodeComponentOptions.tag;
+
+ if (options.render) {
+ opts.render = options.render;
+ opts.staticRenderFns = options.staticRenderFns;
+ }
+ }
+
+ function resolveConstructorOptions (Ctor) {
+ var options = Ctor.options;
+ if (Ctor.super) {
+ var superOptions = resolveConstructorOptions(Ctor.super);
+ var cachedSuperOptions = Ctor.superOptions;
+ if (superOptions !== cachedSuperOptions) {
+ // super option changed,
+ // need to resolve new options.
+ Ctor.superOptions = superOptions;
+ // check if there are any late-modified/attached options (#4976)
+ var modifiedOptions = resolveModifiedOptions(Ctor);
+ // update base extend options
+ if (modifiedOptions) {
+ extend(Ctor.extendOptions, modifiedOptions);
+ }
+ options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
+ if (options.name) {
+ options.components[options.name] = Ctor;
+ }
+ }
+ }
+ return options
+ }
+
+ function resolveModifiedOptions (Ctor) {
+ var modified;
+ var latest = Ctor.options;
+ var sealed = Ctor.sealedOptions;
+ for (var key in latest) {
+ if (latest[key] !== sealed[key]) {
+ if (!modified) { modified = {}; }
+ modified[key] = latest[key];
+ }
+ }
+ return modified
+ }
+
+ function Vue (options) {
+ if (!(this instanceof Vue)
+ ) {
+ warn('Vue is a constructor and should be called with the `new` keyword');
+ }
+ this._init(options);
+ }
+
+ initMixin(Vue);
+ stateMixin(Vue);
+ eventsMixin(Vue);
+ lifecycleMixin(Vue);
+ renderMixin(Vue);
+
+ /* */
+
+ function initUse (Vue) {
+ Vue.use = function (plugin) {
+ var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
+ if (installedPlugins.indexOf(plugin) > -1) {
+ return this
+ }
+
+ // additional parameters
+ var args = toArray(arguments, 1);
+ args.unshift(this);
+ if (typeof plugin.install === 'function') {
+ plugin.install.apply(plugin, args);
+ } else if (typeof plugin === 'function') {
+ plugin.apply(null, args);
+ }
+ installedPlugins.push(plugin);
+ return this
+ };
+ }
+
+ /* */
+
+ function initMixin$1 (Vue) {
+ Vue.mixin = function (mixin) {
+ this.options = mergeOptions(this.options, mixin);
+ return this
+ };
+ }
+
+ /* */
+
+ function initExtend (Vue) {
+ /**
+ * Each instance constructor, including Vue, has a unique
+ * cid. This enables us to create wrapped "child
+ * constructors" for prototypal inheritance and cache them.
+ */
+ Vue.cid = 0;
+ var cid = 1;
+
+ /**
+ * Class inheritance
+ */
+ Vue.extend = function (extendOptions) {
+ extendOptions = extendOptions || {};
+ var Super = this;
+ var SuperId = Super.cid;
+ var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
+ if (cachedCtors[SuperId]) {
+ return cachedCtors[SuperId]
+ }
+
+ var name = extendOptions.name || Super.options.name;
+ if (name) {
+ validateComponentName(name);
+ }
+
+ var Sub = function VueComponent (options) {
+ this._init(options);
+ };
+ Sub.prototype = Object.create(Super.prototype);
+ Sub.prototype.constructor = Sub;
+ Sub.cid = cid++;
+ Sub.options = mergeOptions(
+ Super.options,
+ extendOptions
+ );
+ Sub['super'] = Super;
+
+ // For props and computed properties, we define the proxy getters on
+ // the Vue instances at extension time, on the extended prototype. This
+ // avoids Object.defineProperty calls for each instance created.
+ if (Sub.options.props) {
+ initProps$1(Sub);
+ }
+ if (Sub.options.computed) {
+ initComputed$1(Sub);
+ }
+
+ // allow further extension/mixin/plugin usage
+ Sub.extend = Super.extend;
+ Sub.mixin = Super.mixin;
+ Sub.use = Super.use;
+
+ // create asset registers, so extended classes
+ // can have their private assets too.
+ ASSET_TYPES.forEach(function (type) {
+ Sub[type] = Super[type];
+ });
+ // enable recursive self-lookup
+ if (name) {
+ Sub.options.components[name] = Sub;
+ }
+
+ // keep a reference to the super options at extension time.
+ // later at instantiation we can check if Super's options have
+ // been updated.
+ Sub.superOptions = Super.options;
+ Sub.extendOptions = extendOptions;
+ Sub.sealedOptions = extend({}, Sub.options);
+
+ // cache constructor
+ cachedCtors[SuperId] = Sub;
+ return Sub
+ };
+ }
+
+ function initProps$1 (Comp) {
+ var props = Comp.options.props;
+ for (var key in props) {
+ proxy(Comp.prototype, "_props", key);
+ }
+ }
+
+ function initComputed$1 (Comp) {
+ var computed = Comp.options.computed;
+ for (var key in computed) {
+ defineComputed(Comp.prototype, key, computed[key]);
+ }
+ }
+
+ /* */
+
+ function initAssetRegisters (Vue) {
+ /**
+ * Create asset registration methods.
+ */
+ ASSET_TYPES.forEach(function (type) {
+ Vue[type] = function (
+ id,
+ definition
+ ) {
+ if (!definition) {
+ return this.options[type + 's'][id]
+ } else {
+ /* istanbul ignore if */
+ if (type === 'component') {
+ validateComponentName(id);
+ }
+ if (type === 'component' && isPlainObject(definition)) {
+ definition.name = definition.name || id;
+ definition = this.options._base.extend(definition);
+ }
+ if (type === 'directive' && typeof definition === 'function') {
+ definition = { bind: definition, update: definition };
+ }
+ this.options[type + 's'][id] = definition;
+ return definition
+ }
+ };
+ });
+ }
+
+ /* */
+
+
+
+ function getComponentName (opts) {
+ return opts && (opts.Ctor.options.name || opts.tag)
+ }
+
+ function matches (pattern, name) {
+ if (Array.isArray(pattern)) {
+ return pattern.indexOf(name) > -1
+ } else if (typeof pattern === 'string') {
+ return pattern.split(',').indexOf(name) > -1
+ } else if (isRegExp(pattern)) {
+ return pattern.test(name)
+ }
+ /* istanbul ignore next */
+ return false
+ }
+
+ function pruneCache (keepAliveInstance, filter) {
+ var cache = keepAliveInstance.cache;
+ var keys = keepAliveInstance.keys;
+ var _vnode = keepAliveInstance._vnode;
+ for (var key in cache) {
+ var cachedNode = cache[key];
+ if (cachedNode) {
+ var name = getComponentName(cachedNode.componentOptions);
+ if (name && !filter(name)) {
+ pruneCacheEntry(cache, key, keys, _vnode);
+ }
+ }
+ }
+ }
+
+ function pruneCacheEntry (
+ cache,
+ key,
+ keys,
+ current
+ ) {
+ var cached$$1 = cache[key];
+ if (cached$$1 && (!current || cached$$1.tag !== current.tag)) {
+ cached$$1.componentInstance.$destroy();
+ }
+ cache[key] = null;
+ remove(keys, key);
+ }
+
+ var patternTypes = [String, RegExp, Array];
+
+ var KeepAlive = {
+ name: 'keep-alive',
+ abstract: true,
+
+ props: {
+ include: patternTypes,
+ exclude: patternTypes,
+ max: [String, Number]
+ },
+
+ created: function created () {
+ this.cache = Object.create(null);
+ this.keys = [];
+ },
+
+ destroyed: function destroyed () {
+ for (var key in this.cache) {
+ pruneCacheEntry(this.cache, key, this.keys);
+ }
+ },
+
+ mounted: function mounted () {
+ var this$1 = this;
+
+ this.$watch('include', function (val) {
+ pruneCache(this$1, function (name) { return matches(val, name); });
+ });
+ this.$watch('exclude', function (val) {
+ pruneCache(this$1, function (name) { return !matches(val, name); });
+ });
+ },
+
+ render: function render () {
+ var slot = this.$slots.default;
+ var vnode = getFirstComponentChild(slot);
+ var componentOptions = vnode && vnode.componentOptions;
+ if (componentOptions) {
+ // check pattern
+ var name = getComponentName(componentOptions);
+ var ref = this;
+ var include = ref.include;
+ var exclude = ref.exclude;
+ if (
+ // not included
+ (include && (!name || !matches(include, name))) ||
+ // excluded
+ (exclude && name && matches(exclude, name))
+ ) {
+ return vnode
+ }
+
+ var ref$1 = this;
+ var cache = ref$1.cache;
+ var keys = ref$1.keys;
+ var key = vnode.key == null
+ // same constructor may get registered as different local components
+ // so cid alone is not enough (#3269)
+ ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
+ : vnode.key;
+ if (cache[key]) {
+ vnode.componentInstance = cache[key].componentInstance;
+ // make current key freshest
+ remove(keys, key);
+ keys.push(key);
+ } else {
+ cache[key] = vnode;
+ keys.push(key);
+ // prune oldest entry
+ if (this.max && keys.length > parseInt(this.max)) {
+ pruneCacheEntry(cache, keys[0], keys, this._vnode);
+ }
+ }
+
+ vnode.data.keepAlive = true;
+ }
+ return vnode || (slot && slot[0])
+ }
+ };
+
+ var builtInComponents = {
+ KeepAlive: KeepAlive
+ };
+
+ /* */
+
+ function initGlobalAPI (Vue) {
+ // config
+ var configDef = {};
+ configDef.get = function () { return config; };
+ {
+ configDef.set = function () {
+ warn(
+ 'Do not replace the Vue.config object, set individual fields instead.'
+ );
+ };
+ }
+ Object.defineProperty(Vue, 'config', configDef);
+
+ // exposed util methods.
+ // NOTE: these are not considered part of the public API - avoid relying on
+ // them unless you are aware of the risk.
+ Vue.util = {
+ warn: warn,
+ extend: extend,
+ mergeOptions: mergeOptions,
+ defineReactive: defineReactive$$1
+ };
+
+ Vue.set = set;
+ Vue.delete = del;
+ Vue.nextTick = nextTick;
+
+ // 2.6 explicit observable API
+ Vue.observable = function (obj) {
+ observe(obj);
+ return obj
+ };
+
+ Vue.options = Object.create(null);
+ ASSET_TYPES.forEach(function (type) {
+ Vue.options[type + 's'] = Object.create(null);
+ });
+
+ // this is used to identify the "base" constructor to extend all plain-object
+ // components with in Weex's multi-instance scenarios.
+ Vue.options._base = Vue;
+
+ extend(Vue.options.components, builtInComponents);
+
+ initUse(Vue);
+ initMixin$1(Vue);
+ initExtend(Vue);
+ initAssetRegisters(Vue);
+ }
+
+ initGlobalAPI(Vue);
+
+ Object.defineProperty(Vue.prototype, '$isServer', {
+ get: isServerRendering
+ });
+
+ Object.defineProperty(Vue.prototype, '$ssrContext', {
+ get: function get () {
+ /* istanbul ignore next */
+ return this.$vnode && this.$vnode.ssrContext
+ }
+ });
+
+ // expose FunctionalRenderContext for ssr runtime helper installation
+ Object.defineProperty(Vue, 'FunctionalRenderContext', {
+ value: FunctionalRenderContext
+ });
+
+ Vue.version = '2.6.11';
+
+ /* */
+
+ // these are reserved for web because they are directly compiled away
+ // during template compilation
+ var isReservedAttr = makeMap('style,class');
+
+ // attributes that should be using props for binding
+ var acceptValue = makeMap('input,textarea,option,select,progress');
+ var mustUseProp = function (tag, type, attr) {
+ return (
+ (attr === 'value' && acceptValue(tag)) && type !== 'button' ||
+ (attr === 'selected' && tag === 'option') ||
+ (attr === 'checked' && tag === 'input') ||
+ (attr === 'muted' && tag === 'video')
+ )
+ };
+
+ var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
+
+ var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only');
+
+ var convertEnumeratedValue = function (key, value) {
+ return isFalsyAttrValue(value) || value === 'false'
+ ? 'false'
+ // allow arbitrary string value for contenteditable
+ : key === 'contenteditable' && isValidContentEditableValue(value)
+ ? value
+ : 'true'
+ };
+
+ var isBooleanAttr = makeMap(
+ 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
+ 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
+ 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
+ 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
+ 'required,reversed,scoped,seamless,selected,sortable,translate,' +
+ 'truespeed,typemustmatch,visible'
+ );
+
+ var xlinkNS = 'http://www.w3.org/1999/xlink';
+
+ var isXlink = function (name) {
+ return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
+ };
+
+ var getXlinkProp = function (name) {
+ return isXlink(name) ? name.slice(6, name.length) : ''
+ };
+
+ var isFalsyAttrValue = function (val) {
+ return val == null || val === false
+ };
+
+ /* */
+
+ function genClassForVnode (vnode) {
+ var data = vnode.data;
+ var parentNode = vnode;
+ var childNode = vnode;
+ while (isDef(childNode.componentInstance)) {
+ childNode = childNode.componentInstance._vnode;
+ if (childNode && childNode.data) {
+ data = mergeClassData(childNode.data, data);
+ }
+ }
+ while (isDef(parentNode = parentNode.parent)) {
+ if (parentNode && parentNode.data) {
+ data = mergeClassData(data, parentNode.data);
+ }
+ }
+ return renderClass(data.staticClass, data.class)
+ }
+
+ function mergeClassData (child, parent) {
+ return {
+ staticClass: concat(child.staticClass, parent.staticClass),
+ class: isDef(child.class)
+ ? [child.class, parent.class]
+ : parent.class
+ }
+ }
+
+ function renderClass (
+ staticClass,
+ dynamicClass
+ ) {
+ if (isDef(staticClass) || isDef(dynamicClass)) {
+ return concat(staticClass, stringifyClass(dynamicClass))
+ }
+ /* istanbul ignore next */
+ return ''
+ }
+
+ function concat (a, b) {
+ return a ? b ? (a + ' ' + b) : a : (b || '')
+ }
+
+ function stringifyClass (value) {
+ if (Array.isArray(value)) {
+ return stringifyArray(value)
+ }
+ if (isObject(value)) {
+ return stringifyObject(value)
+ }
+ if (typeof value === 'string') {
+ return value
+ }
+ /* istanbul ignore next */
+ return ''
+ }
+
+ function stringifyArray (value) {
+ var res = '';
+ var stringified;
+ for (var i = 0, l = value.length; i < l; i++) {
+ if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
+ if (res) { res += ' '; }
+ res += stringified;
+ }
+ }
+ return res
+ }
+
+ function stringifyObject (value) {
+ var res = '';
+ for (var key in value) {
+ if (value[key]) {
+ if (res) { res += ' '; }
+ res += key;
+ }
+ }
+ return res
+ }
+
+ /* */
+
+ var namespaceMap = {
+ svg: 'http://www.w3.org/2000/svg',
+ math: 'http://www.w3.org/1998/Math/MathML'
+ };
+
+ var isHTMLTag = makeMap(
+ 'html,body,base,head,link,meta,style,title,' +
+ 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
+ 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
+ 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
+ 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
+ 'embed,object,param,source,canvas,script,noscript,del,ins,' +
+ 'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
+ 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
+ 'output,progress,select,textarea,' +
+ 'details,dialog,menu,menuitem,summary,' +
+ 'content,element,shadow,template,blockquote,iframe,tfoot'
+ );
+
+ // this map is intentionally selective, only covering SVG elements that may
+ // contain child elements.
+ var isSVG = makeMap(
+ 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
+ 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
+ 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
+ true
+ );
+
+ var isPreTag = function (tag) { return tag === 'pre'; };
+
+ var isReservedTag = function (tag) {
+ return isHTMLTag(tag) || isSVG(tag)
+ };
+
+ function getTagNamespace (tag) {
+ if (isSVG(tag)) {
+ return 'svg'
+ }
+ // basic support for MathML
+ // note it doesn't support other MathML elements being component roots
+ if (tag === 'math') {
+ return 'math'
+ }
+ }
+
+ var unknownElementCache = Object.create(null);
+ function isUnknownElement (tag) {
+ /* istanbul ignore if */
+ if (!inBrowser) {
+ return true
+ }
+ if (isReservedTag(tag)) {
+ return false
+ }
+ tag = tag.toLowerCase();
+ /* istanbul ignore if */
+ if (unknownElementCache[tag] != null) {
+ return unknownElementCache[tag]
+ }
+ var el = document.createElement(tag);
+ if (tag.indexOf('-') > -1) {
+ // http://stackoverflow.com/a/28210364/1070244
+ return (unknownElementCache[tag] = (
+ el.constructor === window.HTMLUnknownElement ||
+ el.constructor === window.HTMLElement
+ ))
+ } else {
+ return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
+ }
+ }
+
+ var isTextInputType = makeMap('text,number,password,search,email,tel,url');
+
+ /* */
+
+ /**
+ * Query an element selector if it's not an element already.
+ */
+ function query (el) {
+ if (typeof el === 'string') {
+ var selected = document.querySelector(el);
+ if (!selected) {
+ warn(
+ 'Cannot find element: ' + el
+ );
+ return document.createElement('div')
+ }
+ return selected
+ } else {
+ return el
+ }
+ }
+
+ /* */
+
+ function createElement$1 (tagName, vnode) {
+ var elm = document.createElement(tagName);
+ if (tagName !== 'select') {
+ return elm
+ }
+ // false or null will remove the attribute but undefined will not
+ if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
+ elm.setAttribute('multiple', 'multiple');
+ }
+ return elm
+ }
+
+ function createElementNS (namespace, tagName) {
+ return document.createElementNS(namespaceMap[namespace], tagName)
+ }
+
+ function createTextNode (text) {
+ return document.createTextNode(text)
+ }
+
+ function createComment (text) {
+ return document.createComment(text)
+ }
+
+ function insertBefore (parentNode, newNode, referenceNode) {
+ parentNode.insertBefore(newNode, referenceNode);
+ }
+
+ function removeChild (node, child) {
+ node.removeChild(child);
+ }
+
+ function appendChild (node, child) {
+ node.appendChild(child);
+ }
+
+ function parentNode (node) {
+ return node.parentNode
+ }
+
+ function nextSibling (node) {
+ return node.nextSibling
+ }
+
+ function tagName (node) {
+ return node.tagName
+ }
+
+ function setTextContent (node, text) {
+ node.textContent = text;
+ }
+
+ function setStyleScope (node, scopeId) {
+ node.setAttribute(scopeId, '');
+ }
+
+ var nodeOps = /*#__PURE__*/Object.freeze({
+ createElement: createElement$1,
+ createElementNS: createElementNS,
+ createTextNode: createTextNode,
+ createComment: createComment,
+ insertBefore: insertBefore,
+ removeChild: removeChild,
+ appendChild: appendChild,
+ parentNode: parentNode,
+ nextSibling: nextSibling,
+ tagName: tagName,
+ setTextContent: setTextContent,
+ setStyleScope: setStyleScope
+ });
+
+ /* */
+
+ var ref = {
+ create: function create (_, vnode) {
+ registerRef(vnode);
+ },
+ update: function update (oldVnode, vnode) {
+ if (oldVnode.data.ref !== vnode.data.ref) {
+ registerRef(oldVnode, true);
+ registerRef(vnode);
+ }
+ },
+ destroy: function destroy (vnode) {
+ registerRef(vnode, true);
+ }
+ };
+
+ function registerRef (vnode, isRemoval) {
+ var key = vnode.data.ref;
+ if (!isDef(key)) { return }
+
+ var vm = vnode.context;
+ var ref = vnode.componentInstance || vnode.elm;
+ var refs = vm.$refs;
+ if (isRemoval) {
+ if (Array.isArray(refs[key])) {
+ remove(refs[key], ref);
+ } else if (refs[key] === ref) {
+ refs[key] = undefined;
+ }
+ } else {
+ if (vnode.data.refInFor) {
+ if (!Array.isArray(refs[key])) {
+ refs[key] = [ref];
+ } else if (refs[key].indexOf(ref) < 0) {
+ // $flow-disable-line
+ refs[key].push(ref);
+ }
+ } else {
+ refs[key] = ref;
+ }
+ }
+ }
+
+ /**
+ * Virtual DOM patching algorithm based on Snabbdom by
+ * Simon Friis Vindum (@paldepind)
+ * Licensed under the MIT License
+ * https://github.com/paldepind/snabbdom/blob/master/LICENSE
+ *
+ * modified by Evan You (@yyx990803)
+ *
+ * Not type-checking this because this file is perf-critical and the cost
+ * of making flow understand it is not worth it.
+ */
+
+ var emptyNode = new VNode('', {}, []);
+
+ var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];
+
+ function sameVnode (a, b) {
+ return (
+ a.key === b.key && (
+ (
+ a.tag === b.tag &&
+ a.isComment === b.isComment &&
+ isDef(a.data) === isDef(b.data) &&
+ sameInputType(a, b)
+ ) || (
+ isTrue(a.isAsyncPlaceholder) &&
+ a.asyncFactory === b.asyncFactory &&
+ isUndef(b.asyncFactory.error)
+ )
+ )
+ )
+ }
+
+ function sameInputType (a, b) {
+ if (a.tag !== 'input') { return true }
+ var i;
+ var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;
+ var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
+ return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)
+ }
+
+ function createKeyToOldIdx (children, beginIdx, endIdx) {
+ var i, key;
+ var map = {};
+ for (i = beginIdx; i <= endIdx; ++i) {
+ key = children[i].key;
+ if (isDef(key)) { map[key] = i; }
+ }
+ return map
+ }
+
+ function createPatchFunction (backend) {
+ var i, j;
+ var cbs = {};
+
+ var modules = backend.modules;
+ var nodeOps = backend.nodeOps;
+
+ for (i = 0; i < hooks.length; ++i) {
+ cbs[hooks[i]] = [];
+ for (j = 0; j < modules.length; ++j) {
+ if (isDef(modules[j][hooks[i]])) {
+ cbs[hooks[i]].push(modules[j][hooks[i]]);
+ }
+ }
+ }
+
+ function emptyNodeAt (elm) {
+ return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
+ }
+
+ function createRmCb (childElm, listeners) {
+ function remove$$1 () {
+ if (--remove$$1.listeners === 0) {
+ removeNode(childElm);
+ }
+ }
+ remove$$1.listeners = listeners;
+ return remove$$1
+ }
+
+ function removeNode (el) {
+ var parent = nodeOps.parentNode(el);
+ // element may have already been removed due to v-html / v-text
+ if (isDef(parent)) {
+ nodeOps.removeChild(parent, el);
+ }
+ }
+
+ function isUnknownElement$$1 (vnode, inVPre) {
+ return (
+ !inVPre &&
+ !vnode.ns &&
+ !(
+ config.ignoredElements.length &&
+ config.ignoredElements.some(function (ignore) {
+ return isRegExp(ignore)
+ ? ignore.test(vnode.tag)
+ : ignore === vnode.tag
+ })
+ ) &&
+ config.isUnknownElement(vnode.tag)
+ )
+ }
+
+ var creatingElmInVPre = 0;
+
+ function createElm (
+ vnode,
+ insertedVnodeQueue,
+ parentElm,
+ refElm,
+ nested,
+ ownerArray,
+ index
+ ) {
+ if (isDef(vnode.elm) && isDef(ownerArray)) {
+ // This vnode was used in a previous render!
+ // now it's used as a new node, overwriting its elm would cause
+ // potential patch errors down the road when it's used as an insertion
+ // reference node. Instead, we clone the node on-demand before creating
+ // associated DOM element for it.
+ vnode = ownerArray[index] = cloneVNode(vnode);
+ }
+
+ vnode.isRootInsert = !nested; // for transition enter check
+ if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
+ return
+ }
+
+ var data = vnode.data;
+ var children = vnode.children;
+ var tag = vnode.tag;
+ if (isDef(tag)) {
+ {
+ if (data && data.pre) {
+ creatingElmInVPre++;
+ }
+ if (isUnknownElement$$1(vnode, creatingElmInVPre)) {
+ warn(
+ 'Unknown custom element: <' + tag + '> - did you ' +
+ 'register the component correctly? For recursive components, ' +
+ 'make sure to provide the "name" option.',
+ vnode.context
+ );
+ }
+ }
+
+ vnode.elm = vnode.ns
+ ? nodeOps.createElementNS(vnode.ns, tag)
+ : nodeOps.createElement(tag, vnode);
+ setScope(vnode);
+
+ /* istanbul ignore if */
+ {
+ createChildren(vnode, children, insertedVnodeQueue);
+ if (isDef(data)) {
+ invokeCreateHooks(vnode, insertedVnodeQueue);
+ }
+ insert(parentElm, vnode.elm, refElm);
+ }
+
+ if (data && data.pre) {
+ creatingElmInVPre--;
+ }
+ } else if (isTrue(vnode.isComment)) {
+ vnode.elm = nodeOps.createComment(vnode.text);
+ insert(parentElm, vnode.elm, refElm);
+ } else {
+ vnode.elm = nodeOps.createTextNode(vnode.text);
+ insert(parentElm, vnode.elm, refElm);
+ }
+ }
+
+ function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
+ var i = vnode.data;
+ if (isDef(i)) {
+ var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
+ if (isDef(i = i.hook) && isDef(i = i.init)) {
+ i(vnode, false /* hydrating */);
+ }
+ // after calling the init hook, if the vnode is a child component
+ // it should've created a child instance and mounted it. the child
+ // component also has set the placeholder vnode's elm.
+ // in that case we can just return the element and be done.
+ if (isDef(vnode.componentInstance)) {
+ initComponent(vnode, insertedVnodeQueue);
+ insert(parentElm, vnode.elm, refElm);
+ if (isTrue(isReactivated)) {
+ reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
+ }
+ return true
+ }
+ }
+ }
+
+ function initComponent (vnode, insertedVnodeQueue) {
+ if (isDef(vnode.data.pendingInsert)) {
+ insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
+ vnode.data.pendingInsert = null;
+ }
+ vnode.elm = vnode.componentInstance.$el;
+ if (isPatchable(vnode)) {
+ invokeCreateHooks(vnode, insertedVnodeQueue);
+ setScope(vnode);
+ } else {
+ // empty component root.
+ // skip all element-related modules except for ref (#3455)
+ registerRef(vnode);
+ // make sure to invoke the insert hook
+ insertedVnodeQueue.push(vnode);
+ }
+ }
+
+ function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
+ var i;
+ // hack for #4339: a reactivated component with inner transition
+ // does not trigger because the inner node's created hooks are not called
+ // again. It's not ideal to involve module-specific logic in here but
+ // there doesn't seem to be a better way to do it.
+ var innerNode = vnode;
+ while (innerNode.componentInstance) {
+ innerNode = innerNode.componentInstance._vnode;
+ if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
+ for (i = 0; i < cbs.activate.length; ++i) {
+ cbs.activate[i](emptyNode, innerNode);
+ }
+ insertedVnodeQueue.push(innerNode);
+ break
+ }
+ }
+ // unlike a newly created component,
+ // a reactivated keep-alive component doesn't insert itself
+ insert(parentElm, vnode.elm, refElm);
+ }
+
+ function insert (parent, elm, ref$$1) {
+ if (isDef(parent)) {
+ if (isDef(ref$$1)) {
+ if (nodeOps.parentNode(ref$$1) === parent) {
+ nodeOps.insertBefore(parent, elm, ref$$1);
+ }
+ } else {
+ nodeOps.appendChild(parent, elm);
+ }
+ }
+ }
+
+ function createChildren (vnode, children, insertedVnodeQueue) {
+ if (Array.isArray(children)) {
+ {
+ checkDuplicateKeys(children);
+ }
+ for (var i = 0; i < children.length; ++i) {
+ createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i);
+ }
+ } else if (isPrimitive(vnode.text)) {
+ nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));
+ }
+ }
+
+ function isPatchable (vnode) {
+ while (vnode.componentInstance) {
+ vnode = vnode.componentInstance._vnode;
+ }
+ return isDef(vnode.tag)
+ }
+
+ function invokeCreateHooks (vnode, insertedVnodeQueue) {
+ for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
+ cbs.create[i$1](emptyNode, vnode);
+ }
+ i = vnode.data.hook; // Reuse variable
+ if (isDef(i)) {
+ if (isDef(i.create)) { i.create(emptyNode, vnode); }
+ if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }
+ }
+ }
+
+ // set scope id attribute for scoped CSS.
+ // this is implemented as a special case to avoid the overhead
+ // of going through the normal attribute patching process.
+ function setScope (vnode) {
+ var i;
+ if (isDef(i = vnode.fnScopeId)) {
+ nodeOps.setStyleScope(vnode.elm, i);
+ } else {
+ var ancestor = vnode;
+ while (ancestor) {
+ if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
+ nodeOps.setStyleScope(vnode.elm, i);
+ }
+ ancestor = ancestor.parent;
+ }
+ }
+ // for slot content they should also get the scopeId from the host instance.
+ if (isDef(i = activeInstance) &&
+ i !== vnode.context &&
+ i !== vnode.fnContext &&
+ isDef(i = i.$options._scopeId)
+ ) {
+ nodeOps.setStyleScope(vnode.elm, i);
+ }
+ }
+
+ function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
+ for (; startIdx <= endIdx; ++startIdx) {
+ createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx);
+ }
+ }
+
+ function invokeDestroyHook (vnode) {
+ var i, j;
+ var data = vnode.data;
+ if (isDef(data)) {
+ if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
+ for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
+ }
+ if (isDef(i = vnode.children)) {
+ for (j = 0; j < vnode.children.length; ++j) {
+ invokeDestroyHook(vnode.children[j]);
+ }
+ }
+ }
+
+ function removeVnodes (vnodes, startIdx, endIdx) {
+ for (; startIdx <= endIdx; ++startIdx) {
+ var ch = vnodes[startIdx];
+ if (isDef(ch)) {
+ if (isDef(ch.tag)) {
+ removeAndInvokeRemoveHook(ch);
+ invokeDestroyHook(ch);
+ } else { // Text node
+ removeNode(ch.elm);
+ }
+ }
+ }
+ }
+
+ function removeAndInvokeRemoveHook (vnode, rm) {
+ if (isDef(rm) || isDef(vnode.data)) {
+ var i;
+ var listeners = cbs.remove.length + 1;
+ if (isDef(rm)) {
+ // we have a recursively passed down rm callback
+ // increase the listeners count
+ rm.listeners += listeners;
+ } else {
+ // directly removing
+ rm = createRmCb(vnode.elm, listeners);
+ }
+ // recursively invoke hooks on child component root node
+ if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
+ removeAndInvokeRemoveHook(i, rm);
+ }
+ for (i = 0; i < cbs.remove.length; ++i) {
+ cbs.remove[i](vnode, rm);
+ }
+ if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
+ i(vnode, rm);
+ } else {
+ rm();
+ }
+ } else {
+ removeNode(vnode.elm);
+ }
+ }
+
+ function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
+ var oldStartIdx = 0;
+ var newStartIdx = 0;
+ var oldEndIdx = oldCh.length - 1;
+ var oldStartVnode = oldCh[0];
+ var oldEndVnode = oldCh[oldEndIdx];
+ var newEndIdx = newCh.length - 1;
+ var newStartVnode = newCh[0];
+ var newEndVnode = newCh[newEndIdx];
+ var oldKeyToIdx, idxInOld, vnodeToMove, refElm;
+
+ // removeOnly is a special flag used only by
+ // to ensure removed elements stay in correct relative positions
+ // during leaving transitions
+ var canMove = !removeOnly;
+
+ {
+ checkDuplicateKeys(newCh);
+ }
+
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
+ if (isUndef(oldStartVnode)) {
+ oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
+ } else if (isUndef(oldEndVnode)) {
+ oldEndVnode = oldCh[--oldEndIdx];
+ } else if (sameVnode(oldStartVnode, newStartVnode)) {
+ patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
+ oldStartVnode = oldCh[++oldStartIdx];
+ newStartVnode = newCh[++newStartIdx];
+ } else if (sameVnode(oldEndVnode, newEndVnode)) {
+ patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
+ oldEndVnode = oldCh[--oldEndIdx];
+ newEndVnode = newCh[--newEndIdx];
+ } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
+ patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
+ canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
+ oldStartVnode = oldCh[++oldStartIdx];
+ newEndVnode = newCh[--newEndIdx];
+ } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
+ patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
+ canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
+ oldEndVnode = oldCh[--oldEndIdx];
+ newStartVnode = newCh[++newStartIdx];
+ } else {
+ if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
+ idxInOld = isDef(newStartVnode.key)
+ ? oldKeyToIdx[newStartVnode.key]
+ : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx);
+ if (isUndef(idxInOld)) { // New element
+ createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
+ } else {
+ vnodeToMove = oldCh[idxInOld];
+ if (sameVnode(vnodeToMove, newStartVnode)) {
+ patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
+ oldCh[idxInOld] = undefined;
+ canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm);
+ } else {
+ // same key but different element. treat as new element
+ createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
+ }
+ }
+ newStartVnode = newCh[++newStartIdx];
+ }
+ }
+ if (oldStartIdx > oldEndIdx) {
+ refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
+ addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
+ } else if (newStartIdx > newEndIdx) {
+ removeVnodes(oldCh, oldStartIdx, oldEndIdx);
+ }
+ }
+
+ function checkDuplicateKeys (children) {
+ var seenKeys = {};
+ for (var i = 0; i < children.length; i++) {
+ var vnode = children[i];
+ var key = vnode.key;
+ if (isDef(key)) {
+ if (seenKeys[key]) {
+ warn(
+ ("Duplicate keys detected: '" + key + "'. This may cause an update error."),
+ vnode.context
+ );
+ } else {
+ seenKeys[key] = true;
+ }
+ }
+ }
+ }
+
+ function findIdxInOld (node, oldCh, start, end) {
+ for (var i = start; i < end; i++) {
+ var c = oldCh[i];
+ if (isDef(c) && sameVnode(node, c)) { return i }
+ }
+ }
+
+ function patchVnode (
+ oldVnode,
+ vnode,
+ insertedVnodeQueue,
+ ownerArray,
+ index,
+ removeOnly
+ ) {
+ if (oldVnode === vnode) {
+ return
+ }
+
+ if (isDef(vnode.elm) && isDef(ownerArray)) {
+ // clone reused vnode
+ vnode = ownerArray[index] = cloneVNode(vnode);
+ }
+
+ var elm = vnode.elm = oldVnode.elm;
+
+ if (isTrue(oldVnode.isAsyncPlaceholder)) {
+ if (isDef(vnode.asyncFactory.resolved)) {
+ hydrate(oldVnode.elm, vnode, insertedVnodeQueue);
+ } else {
+ vnode.isAsyncPlaceholder = true;
+ }
+ return
+ }
+
+ // reuse element for static trees.
+ // note we only do this if the vnode is cloned -
+ // if the new node is not cloned it means the render functions have been
+ // reset by the hot-reload-api and we need to do a proper re-render.
+ if (isTrue(vnode.isStatic) &&
+ isTrue(oldVnode.isStatic) &&
+ vnode.key === oldVnode.key &&
+ (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
+ ) {
+ vnode.componentInstance = oldVnode.componentInstance;
+ return
+ }
+
+ var i;
+ var data = vnode.data;
+ if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
+ i(oldVnode, vnode);
+ }
+
+ var oldCh = oldVnode.children;
+ var ch = vnode.children;
+ if (isDef(data) && isPatchable(vnode)) {
+ for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
+ if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
+ }
+ if (isUndef(vnode.text)) {
+ if (isDef(oldCh) && isDef(ch)) {
+ if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
+ } else if (isDef(ch)) {
+ {
+ checkDuplicateKeys(ch);
+ }
+ if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
+ addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
+ } else if (isDef(oldCh)) {
+ removeVnodes(oldCh, 0, oldCh.length - 1);
+ } else if (isDef(oldVnode.text)) {
+ nodeOps.setTextContent(elm, '');
+ }
+ } else if (oldVnode.text !== vnode.text) {
+ nodeOps.setTextContent(elm, vnode.text);
+ }
+ if (isDef(data)) {
+ if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
+ }
+ }
+
+ function invokeInsertHook (vnode, queue, initial) {
+ // delay insert hooks for component root nodes, invoke them after the
+ // element is really inserted
+ if (isTrue(initial) && isDef(vnode.parent)) {
+ vnode.parent.data.pendingInsert = queue;
+ } else {
+ for (var i = 0; i < queue.length; ++i) {
+ queue[i].data.hook.insert(queue[i]);
+ }
+ }
+ }
+
+ var hydrationBailed = false;
+ // list of modules that can skip create hook during hydration because they
+ // are already rendered on the client or has no need for initialization
+ // Note: style is excluded because it relies on initial clone for future
+ // deep updates (#7063).
+ var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key');
+
+ // Note: this is a browser-only function so we can assume elms are DOM nodes.
+ function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {
+ var i;
+ var tag = vnode.tag;
+ var data = vnode.data;
+ var children = vnode.children;
+ inVPre = inVPre || (data && data.pre);
+ vnode.elm = elm;
+
+ if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {
+ vnode.isAsyncPlaceholder = true;
+ return true
+ }
+ // assert node match
+ {
+ if (!assertNodeMatch(elm, vnode, inVPre)) {
+ return false
+ }
+ }
+ if (isDef(data)) {
+ if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
+ if (isDef(i = vnode.componentInstance)) {
+ // child component. it should have hydrated its own tree.
+ initComponent(vnode, insertedVnodeQueue);
+ return true
+ }
+ }
+ if (isDef(tag)) {
+ if (isDef(children)) {
+ // empty element, allow client to pick up and populate children
+ if (!elm.hasChildNodes()) {
+ createChildren(vnode, children, insertedVnodeQueue);
+ } else {
+ // v-html and domProps: innerHTML
+ if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {
+ if (i !== elm.innerHTML) {
+ /* istanbul ignore if */
+ if (typeof console !== 'undefined' &&
+ !hydrationBailed
+ ) {
+ hydrationBailed = true;
+ console.warn('Parent: ', elm);
+ console.warn('server innerHTML: ', i);
+ console.warn('client innerHTML: ', elm.innerHTML);
+ }
+ return false
+ }
+ } else {
+ // iterate and compare children lists
+ var childrenMatch = true;
+ var childNode = elm.firstChild;
+ for (var i$1 = 0; i$1 < children.length; i$1++) {
+ if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) {
+ childrenMatch = false;
+ break
+ }
+ childNode = childNode.nextSibling;
+ }
+ // if childNode is not null, it means the actual childNodes list is
+ // longer than the virtual children list.
+ if (!childrenMatch || childNode) {
+ /* istanbul ignore if */
+ if (typeof console !== 'undefined' &&
+ !hydrationBailed
+ ) {
+ hydrationBailed = true;
+ console.warn('Parent: ', elm);
+ console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
+ }
+ return false
+ }
+ }
+ }
+ }
+ if (isDef(data)) {
+ var fullInvoke = false;
+ for (var key in data) {
+ if (!isRenderedModule(key)) {
+ fullInvoke = true;
+ invokeCreateHooks(vnode, insertedVnodeQueue);
+ break
+ }
+ }
+ if (!fullInvoke && data['class']) {
+ // ensure collecting deps for deep class bindings for future updates
+ traverse(data['class']);
+ }
+ }
+ } else if (elm.data !== vnode.text) {
+ elm.data = vnode.text;
+ }
+ return true
+ }
+
+ function assertNodeMatch (node, vnode, inVPre) {
+ if (isDef(vnode.tag)) {
+ return vnode.tag.indexOf('vue-component') === 0 || (
+ !isUnknownElement$$1(vnode, inVPre) &&
+ vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
+ )
+ } else {
+ return node.nodeType === (vnode.isComment ? 8 : 3)
+ }
+ }
+
+ return function patch (oldVnode, vnode, hydrating, removeOnly) {
+ if (isUndef(vnode)) {
+ if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }
+ return
+ }
+
+ var isInitialPatch = false;
+ var insertedVnodeQueue = [];
+
+ if (isUndef(oldVnode)) {
+ // empty mount (likely as component), create new root element
+ isInitialPatch = true;
+ createElm(vnode, insertedVnodeQueue);
+ } else {
+ var isRealElement = isDef(oldVnode.nodeType);
+ if (!isRealElement && sameVnode(oldVnode, vnode)) {
+ // patch existing root node
+ patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly);
+ } else {
+ if (isRealElement) {
+ // mounting to a real element
+ // check if this is server-rendered content and if we can perform
+ // a successful hydration.
+ if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
+ oldVnode.removeAttribute(SSR_ATTR);
+ hydrating = true;
+ }
+ if (isTrue(hydrating)) {
+ if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
+ invokeInsertHook(vnode, insertedVnodeQueue, true);
+ return oldVnode
+ } else {
+ warn(
+ 'The client-side rendered virtual DOM tree is not matching ' +
+ 'server-rendered content. This is likely caused by incorrect ' +
+ 'HTML markup, for example nesting block-level elements inside ' +
+ ', or missing
. Bailing hydration and performing ' +
+ 'full client-side render.'
+ );
+ }
+ }
+ // either not server-rendered, or hydration failed.
+ // create an empty node and replace it
+ oldVnode = emptyNodeAt(oldVnode);
+ }
+
+ // replacing existing element
+ var oldElm = oldVnode.elm;
+ var parentElm = nodeOps.parentNode(oldElm);
+
+ // create new node
+ createElm(
+ vnode,
+ insertedVnodeQueue,
+ // extremely rare edge case: do not insert if old element is in a
+ // leaving transition. Only happens when combining transition +
+ // keep-alive + HOCs. (#4590)
+ oldElm._leaveCb ? null : parentElm,
+ nodeOps.nextSibling(oldElm)
+ );
+
+ // update parent placeholder node element, recursively
+ if (isDef(vnode.parent)) {
+ var ancestor = vnode.parent;
+ var patchable = isPatchable(vnode);
+ while (ancestor) {
+ for (var i = 0; i < cbs.destroy.length; ++i) {
+ cbs.destroy[i](ancestor);
+ }
+ ancestor.elm = vnode.elm;
+ if (patchable) {
+ for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
+ cbs.create[i$1](emptyNode, ancestor);
+ }
+ // #6513
+ // invoke insert hooks that may have been merged by create hooks.
+ // e.g. for directives that uses the "inserted" hook.
+ var insert = ancestor.data.hook.insert;
+ if (insert.merged) {
+ // start at index 1 to avoid re-invoking component mounted hook
+ for (var i$2 = 1; i$2 < insert.fns.length; i$2++) {
+ insert.fns[i$2]();
+ }
+ }
+ } else {
+ registerRef(ancestor);
+ }
+ ancestor = ancestor.parent;
+ }
+ }
+
+ // destroy old node
+ if (isDef(parentElm)) {
+ removeVnodes([oldVnode], 0, 0);
+ } else if (isDef(oldVnode.tag)) {
+ invokeDestroyHook(oldVnode);
+ }
+ }
+ }
+
+ invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
+ return vnode.elm
+ }
+ }
+
+ /* */
+
+ var directives = {
+ create: updateDirectives,
+ update: updateDirectives,
+ destroy: function unbindDirectives (vnode) {
+ updateDirectives(vnode, emptyNode);
+ }
+ };
+
+ function updateDirectives (oldVnode, vnode) {
+ if (oldVnode.data.directives || vnode.data.directives) {
+ _update(oldVnode, vnode);
+ }
+ }
+
+ function _update (oldVnode, vnode) {
+ var isCreate = oldVnode === emptyNode;
+ var isDestroy = vnode === emptyNode;
+ var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
+ var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
+
+ var dirsWithInsert = [];
+ var dirsWithPostpatch = [];
+
+ var key, oldDir, dir;
+ for (key in newDirs) {
+ oldDir = oldDirs[key];
+ dir = newDirs[key];
+ if (!oldDir) {
+ // new directive, bind
+ callHook$1(dir, 'bind', vnode, oldVnode);
+ if (dir.def && dir.def.inserted) {
+ dirsWithInsert.push(dir);
+ }
+ } else {
+ // existing directive, update
+ dir.oldValue = oldDir.value;
+ dir.oldArg = oldDir.arg;
+ callHook$1(dir, 'update', vnode, oldVnode);
+ if (dir.def && dir.def.componentUpdated) {
+ dirsWithPostpatch.push(dir);
+ }
+ }
+ }
+
+ if (dirsWithInsert.length) {
+ var callInsert = function () {
+ for (var i = 0; i < dirsWithInsert.length; i++) {
+ callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
+ }
+ };
+ if (isCreate) {
+ mergeVNodeHook(vnode, 'insert', callInsert);
+ } else {
+ callInsert();
+ }
+ }
+
+ if (dirsWithPostpatch.length) {
+ mergeVNodeHook(vnode, 'postpatch', function () {
+ for (var i = 0; i < dirsWithPostpatch.length; i++) {
+ callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
+ }
+ });
+ }
+
+ if (!isCreate) {
+ for (key in oldDirs) {
+ if (!newDirs[key]) {
+ // no longer present, unbind
+ callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
+ }
+ }
+ }
+ }
+
+ var emptyModifiers = Object.create(null);
+
+ function normalizeDirectives$1 (
+ dirs,
+ vm
+ ) {
+ var res = Object.create(null);
+ if (!dirs) {
+ // $flow-disable-line
+ return res
+ }
+ var i, dir;
+ for (i = 0; i < dirs.length; i++) {
+ dir = dirs[i];
+ if (!dir.modifiers) {
+ // $flow-disable-line
+ dir.modifiers = emptyModifiers;
+ }
+ res[getRawDirName(dir)] = dir;
+ dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
+ }
+ // $flow-disable-line
+ return res
+ }
+
+ function getRawDirName (dir) {
+ return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
+ }
+
+ function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
+ var fn = dir.def && dir.def[hook];
+ if (fn) {
+ try {
+ fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
+ } catch (e) {
+ handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook"));
+ }
+ }
+ }
+
+ var baseModules = [
+ ref,
+ directives
+ ];
+
+ /* */
+
+ function updateAttrs (oldVnode, vnode) {
+ var opts = vnode.componentOptions;
+ if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) {
+ return
+ }
+ if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {
+ return
+ }
+ var key, cur, old;
+ var elm = vnode.elm;
+ var oldAttrs = oldVnode.data.attrs || {};
+ var attrs = vnode.data.attrs || {};
+ // clone observed objects, as the user probably wants to mutate it
+ if (isDef(attrs.__ob__)) {
+ attrs = vnode.data.attrs = extend({}, attrs);
+ }
+
+ for (key in attrs) {
+ cur = attrs[key];
+ old = oldAttrs[key];
+ if (old !== cur) {
+ setAttr(elm, key, cur);
+ }
+ }
+ // #4391: in IE9, setting type can reset value for input[type=radio]
+ // #6666: IE/Edge forces progress value down to 1 before setting a max
+ /* istanbul ignore if */
+ if ((isIE || isEdge) && attrs.value !== oldAttrs.value) {
+ setAttr(elm, 'value', attrs.value);
+ }
+ for (key in oldAttrs) {
+ if (isUndef(attrs[key])) {
+ if (isXlink(key)) {
+ elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
+ } else if (!isEnumeratedAttr(key)) {
+ elm.removeAttribute(key);
+ }
+ }
+ }
+ }
+
+ function setAttr (el, key, value) {
+ if (el.tagName.indexOf('-') > -1) {
+ baseSetAttr(el, key, value);
+ } else if (isBooleanAttr(key)) {
+ // set attribute for blank value
+ // e.g.
+ if (isFalsyAttrValue(value)) {
+ el.removeAttribute(key);
+ } else {
+ // technically allowfullscreen is a boolean attribute for